Python二进制文件excel、word、txt及pdf相互转换问题,pythonpdf,公司的一个项目有这么一个


公司的一个项目有这么一个需求,就是将文件转成二进制存入mysql数据库中,前端需要实现点击下载,
但跳转URL的时候后台读取数据库中的二进制,并返回文件如(word,excel,pdf,txt)等格式。

现在还有个问题木有解决,就是从前端上传的文件,我在后台用FILES对象获取到了,但是在存入数据库的过程中遇到了问题,请问如何将文件转成二进制并插入数据库中?

给你一个web中,浏览器中得解决方案,你在返回的文件流中确定好文件类型,例如:

response.headers['Content-Type'] = 'application/vnd.ms-excel'
response.headers['Content-Disposition'] = 'attachment; filename=' + filename + '.xls'

Content-Type 是指文件类型,这里是excel。
再把filename的文件名后缀修改正确的,如:xls、doc等。

-------------增加如何将文件写入response里-----------
主要是使用到python 的StringIO,这里是写excel的,写其他种类的文件情况通用。

book = xlwt.Workbook(encoding='utf-8')
(此处省略一些写excel操作。。。)
output = StringIO.StringIO()
book.save(output)
response = make_response(output.getvalue())
response.headers['Content-Type'] = 'application/vnd.ms-excel'
response.headers['Content-Disposition'] = 'attachment; filename=' + filename + '.xls'
output.closed
return response

编橙之家文章,

评论关闭