Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
238 views
in Technique[技术] by (71.8m points)

Directly Download POST Response With Javascript

I have a service that accepts a POST request and returns a zip file of arbitrary size. I want to send a POST request to that service from a web page and initiate a download of the response.

Since the zip file can be quite large, I need to initiate the download immediately to let the browser start writing to disk. The javscript solutions I've seen so far append the download to the document as a link, then initiate the download by clicking on the link when it's done - that won't work for me.

Is there a way to do this in javascript?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The common way of doing this would be as follows:

  1. Make the post request from the client and on the server store the request in a DB using a random ID (UUID).
  2. Respond to the post with a URL that is a unique link /download/[UUID]
  3. From the client use window.open([the unique URL]) this will download the file instantly from the new URL in the client browser.
  4. On the server make an endpoint respond to the unique URL, get the UUID, read from the DB using the UUID and do a response with the file making sure you set the HTTP headers as download (this forces the client to download rather than open).

For security the request stored in the DB can have a timestamp and the GET endpoint could fail the download if x amount of time has expired - rendering the URL defective after download.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...