Handle file download from ajax post

前端 未结 20 2676
心在旅途
心在旅途 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条回答
  •  梦谈多话
    2020-11-21 06:05

    I want to point out some difficulties that arise when using the technique in the accepted answer, i.e. using a form post:

    1. You can't set headers on the request. If your authentication schema involves headers, a Json-Web-Token passed in the Authorization header, you'll have to find other way to send it, for example as a query parameter.

    2. You can't really tell when the request has finished. Well, you can use a cookie that gets set on response, as done by jquery.fileDownload, but it's FAR from perfect. It won't work for concurrent requests and it will break if a response never arrives.

    3. If the server responds with a error, the user will be redirected to the error page.

    4. You can only use the content types supported by a form. Which means you can't use JSON.

    I ended up using the method of saving the file on S3 and sending a pre-signed URL to get the file.

提交回复
热议问题