Handle file download from ajax post

前端 未结 20 2678
心在旅途
心在旅途 2020-11-21 05:46

I have a javascript app that sends ajax POST requests to a certain URL. Response might be a JSON string or it might be a file (as an attachment). I can easily detect Content

20条回答
  •  闹比i
    闹比i (楼主)
    2020-11-21 06:18

    I used this FileSaver.js. In my case with csv files, i did this (in coffescript):

      $.ajax
        url: "url-to-server"
        data: "data-to-send"
        success: (csvData)->
          blob = new Blob([csvData], { type: 'text/csv' })
          saveAs(blob, "filename.csv")
    

    I think for most complicated case, the data must be processed properly. Under the hood FileSaver.js implement the same approach of the answer of Jonathan Amend.

提交回复
热议问题