1

I want to save a blob downloaded from a server onto the file system, so i use

window.open( window.URL.createObjectURL(myBlob));

to save it. But when i do that, then the saved file gets a completly jumbled random name.
Is there any way to give the saved file my own name?

EDIT: Server side looks like this (Spring Data REST controller):

@RequestMapping(value = "/downloadFile/{fileName}", method = RequestMethod.GET)
public void downloadFile(@PathVariable(value="fileName") String fileName, HttpServletResponse response) throws IOException {    
    File file = getMyFile(fileName)

    response.addHeader("Content-Disposition", "attachment; filename="+file.getName());
    response.setContentType(Files.probeContentType(file.toPath()));
    response.setContentLengthLong(file.length());

    response.getOutputStream().write(FileUtils.readFileToByteArray(file));
}
M364M4N cro
  • 680
  • 2
  • 10
  • 23

1 Answers1

4

I've been searching for a similar answer myself and found several possibilities to save a downloaded file.

In your case you can use the download attribute of the <a> element: <a href="bloburl" download="filename"></a>. You can dynamically add this element when for instance a button is clicked, and programmatically perform the click event.

 var a = document.createElement("a"),
     fileURL = URL.createObjectURL(blob);
 a.style = "display:none";
 a.href = fileURL;
 a.download = fileName;
 window.document.body.appendChild(a);
 a.click();
 window.document.body.removeChild(a);
 URL.revokeObjectURL(fileURL);

The download atrribute only has recent support: http://www.w3schools.com/tags/att_a_download.asp

For older versions of IE, use

if (typeof window.navigator.msSaveBlob !== 'undefined') {
    window.navigator.msSaveOrOpenBlob(blob, fileName);
}
SBylemans
  • 1,764
  • 13
  • 28