加入收藏 | 设为首页 | 会员中心 | 我要投稿 湖南网 (https://www.hunanwang.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 活动 > 正文

ajax post下载flask文件流以及中文文件名问题

发布时间:2020-11-30 08:22:28 所属栏目:活动 来源:网络整理
导读:这篇文章首要先容了ajax post下载flask文件流以及中文文件名题目,本文给各人先容的很是具体,对各人的进修或事变具有必然的参考小心代价,必要的伴侣可以参考下

前端行使 URL.createObjectURL() 建设建设一个 DOMString URL工具,建设一个 a 节点,将URL工具赋给a节点的 href 属性,最后挪用 click() 要领点击该 a 节点即可弹出赏识器下载框。

展示图片

要领同上,将 a 改成 img , href 改成 src 即可,将URL工具写入到方针img标签的src即可。

另一种要领是后端返回图片转base64的字符串,src的值形如 "data:image/svg+xml;base64,${base字符串}" 。(这里的 svg+xml 暗示图片名目是svg,假如是png则改成png)

中文文件名乱码

http headers中直接传输中文文件名,较量简朴的要领是后端举办url转码(这里行使python的 urllib.parse.quote ),前端行使 decodeURI() 解码。

另外还可以配置headers的 Content-Disposition: attachment; filename*=UTF-8''xxxxx ,不外兼容性嘛……贫困还不如直接urlcode算了,并且也懒得配置 Content-Disposition 了,前端从 Content-Disposition 中取 filename 也是够贫困的,会取到一长串字符串然后本身再想步伐取出来 filename= 后头的信息。

代码如下:

flask

from urllib.parse import quote
@file.route('/download', methods=["POST"])
def download_file():
  filename='xx' #文件名
  filepath='xx/xx' #文件路径
  res = make_response(send_file(filepath))
  #自界说的一个header,利便前端取到名字
  res.headers['filename'] = quote(filename.encode('utf-8'))
  return res
javascript——以async异步fetch为例:

async function download() {
  const res = await fetch(``, {
  method: "POST",
  body: JSON.stringify({}), //body内里是要发送的数据
  headers: { "Content-Type": "application/json" },
  responseType: 'blob'
 })

if (res.ok) {
  const blData = await res.blob() //拿到blob数据
  const urlObjData = window.URL.createObjectURL(new Blob([blData])) //建设url工具
 
  //获取文件 举办下转码
  const fileName = decodeURI(fileNameres.headers.get('filename'))
 
  //建设a标签 点击a标签 到达下载目标
  const link = document.createElement('a')
  link.href = urlObjData
  link.download = fileName //下载文件的名字
  document.body.appendChild(link)
  link.click()
 
  document.body.removeChild(link)
  window.URL.revokeObjectURL(urlObjData);
 
  //展示图片
  //xxx.src=urlObjData
 }
}

ps:flask下载文件---文件流

html:

<a href="http://www.admin5.com/downloadfile/?filename=/root/allfile/123.txt">下载</a>

py:

@app.route('/downloadfile/', methods=['GET', 'POST'])
def downloadfile():
  if request.method == 'GET':
    fullfilename = request.args.get('filename')
    # fullfilename = '/root/allfile/123.txt'
    fullfilenamelist = fullfilename.split('/')
    filename = fullfilenamelist[-1]
    filepath = fullfilename.replace('/%s'%filename, '')
    #平凡下载
    # response = make_response(send_from_directory(filepath, filename, as_attachment=True))
    # response.headers["Content-Disposition"] = "attachment; filename={}".format(filepath.encode().decode('latin-1'))
    #return send_from_directory(filepath, filename, as_attachment=True)
    #流式读取
    def send_file():
      store_path = fullfilename
      with open(store_path, 'rb') as targetfile:
        while 1:
          data = targetfile.read(20 * 1024 * 1024)  # 每次读取20M
          if not data:
            break
          yield data

response = Response(send_file(), content_type='application/octet-stream')
    response.headers["Content-disposition"] = 'attachment; filename=%s' % filename  # 假如不加上这行代码,导致下图的题目
    return response

没有文件名,和文件名目,碰着这种环境,打开F12,查察response.headers 与正常的较量

总结

到此这篇关于ajax post下载flask文件流以及中文文件名的文章就先容到这了,更多相干ajax post下载flask文件流内容请搜刮剧本之家早年的文章或继承赏识下面的相干文章但愿各人往后多多支持剧本之家!

(编辑:湖南网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读