Ajax post download flash file stream and Chinese file name problems


Ajax post download file

The back end returns the file stream, which can be used in flagreturn send_file(file path) returns the binary file stream and transmits the file related information (such as the file name) in the headers.

Front end useURL.createObjectURL() Create create aDOMString URLObject, create a a node, assign the URL object to the href attribute of the a node, and finally call the click () method to click the a node to pop up the browser download box.

Show pictures

The method is the same as above. Change a to img, and change the URL object to SRC of the target img tag.

The other method is to return the image to Base64 string. The SRC value is as follows" data:image/svg+xml;base64 , ${base string}“。 (SVG + XML here means that the image format is SVG, if it is PNG, it will be changed to PNG)

Chinese file name garbled

In this case, the method of HTTP header transfer is simple urllib.parse.quote ), front end usedecodeURI() decode.

In addition, you can set the headersContent-Disposition: attachment; filename*=UTF-8''xxxxx But compatibility The trouble is not as good as direct urlcode. Moreover, it’s too lazy to set the content disposition. The front-end uses the Content-Disposition It’s troublesome to get the file name in. You will get a long string of strings, and then try to find a way to get the information after the file name =.

The code is as follows:


from urllib.parse import quote
@file.route('/download', methods=["POST"])
def download_file():
  File name = XX 'ා file name
  Filepath = XX / XX 'ා file path
  res = make_response(send_file(filepath))
  #A customized header to facilitate the front end to get the name
  res.headers['filename'] = quote(filename.encode('utf-8'))
  return res
JavaScript -- Take async asynchronous fetch as an example:

async function download() {
  const res = await fetch(`http://xxx/file/download`, {
  method: "POST",
  body:  JSON.stringify ({}), // body contains the data to be sent
  headers: { "Content-Type": "application/json" },
  responseType: 'blob'

 if (res.ok) {
  const blData = await  res.blob () // get BLOB data
  const urlObjData =  window.URL.createObjectURL (New blob ([bldata])) // create a URL object
  //Get file for down transcoding
  const fileName = decodeURI(fileNameres.headers.get('filename'))
  //Create a tag and click a tag to download
  const link = document.createElement('a')
  link.href = urlObjData
  link.download  =Filename // the name of the downloaded file
  //Show pictures

PS: Flash Download File — file stream


< a name = / downloadfile /? Filename = / root / allfile / 123. TXT “> Download</a>


@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, '')
    #General download
    # 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)
    #Streaming read
    def send_file():
      store_path = fullfilename
      with open(store_path, 'rb') as targetfile:
        while 1:
          data =  targetfile.read (20 * 1024 * 1024) ා 20m each time
          if not data:
          yield data

    response = Response(send_file(), content_type='application/octet-stream')
    response.headers ["content disposition"] ='attachment; filename =% s'% filename # if this line of code is not added, it will cause the problem in the following figure
    return response

There is no file name, and file format. In this case, open F12 and view response.headers Comparison with normal


This article on the Ajax post download flash file stream and Chinese file name of the article introduced here, more related Ajax post download flash file stream content, please search the previous articles of developeppaer or continue to browse the related articles below, I hope you can support developeppaer more in the future!

Recommended Today

Tutorial on sending e-mail using net:: SMTP class in Ruby

Simple Mail Transfer Protocol(SMTP)SendE-mailAnd routing protocol processing between e-mail servers. RubyIt provides the connection of simple mail transfer protocol (SMTP) client of net:: SMTP class, and provides two new methods: new and start New takes two parameters: Server name defaults to localhost Port number defaults to 25 The start method takes these parameters: Server – […]