0

How do I serve a file from a REST api backend to the frontend?

  1. User click on download link which programmatically (using ajax) sends a POST request with authentication details is passed to REST api backend.
  2. Authentication check occurs.
  3. Some file processing occurs.
  4. Serve file to frontend as a download.

Point 5 is where I am having an issue. I can see the binary data is returned from the backend but no download pops up.

async function apiExportProject(projectID, fileType) {
  
    // Create url.
    let url = new URL(urlBaseAPI + "/project/export");
  
    // Prepare POST data.
    let formData = new FormData();
    formData.append("sessionKey", getSessionKeyCookieValue());
    formData.append("projectID", projectID);
    formData.append("fileType", fileType);
  
    // Send the POST request.
    await sendPOSTRequest(url, formData);
}

//GO CODE
    responseWriter.Header().Set("Content-Disposition", "attachment; filename="+strconv.Quote(postFormData.Get("projectID")))
    responseWriter.Header().Set("Content-Type", "application/octet-stream")
    http.ServeFile(responseWriter, request, filePath)
user1406186
  • 940
  • 3
  • 16
  • 28
  • The code looks fine. Try returning `Content-Type` header first and `Content-Disposition` header second, maybe the order matters. – Vitalii Mar 12 '21 at 08:06
  • To debug the issue, before calling http.FileServe(...), try to open filePath with os.Open() and see if you can read the bytes of the file in a buffer. If you cannot, then the issue may be local paths... check the docs for http.FileServer(...) - mind the last "r" letter – luben Mar 12 '21 at 08:06
  • You can also try to send the file directly with io.Copy(responseWriter, fileReader) instead of using http.ServeFile. – luben Mar 12 '21 at 08:10
  • I'm receiving the file in the ajax response but I don't know how to get the download prompt. – user1406186 Mar 12 '21 at 08:19

0 Answers0