1

I have a problem when I try to download a file stored on a server. I make a call and get a right response in which I have all the information I need, in the headers I have the content type and the file name, and I have the file body in the response body.

What I want to do is to simply make a download process, so I tried to do so, data being the http call response :

// Get headers info
let headers = data.headers
let contentType = headers.get("Content-Type")
let name = headers.get("name")

// Initialize Blob
let blob = new Blob([data.text()], {type: contentType})

// Make the download process
let a = window.document.createElement("a")
a.href = window.URL.createObjectURL(blob)
a.download = name
document.body.appendChild(a)
a.click()
document.body.removeChild(a)

For a text file, it's working as it's an easy format, but for like a picture or a PDF file it makes download a file of the right name and type, but they can't be well read.

Has anyone an idea ? Thanks !

Guigui
  • 641
  • 4
  • 8
  • 23
  • I suspect that you're having problems with the content encoding. But wouldn't it be simpler (and a lot more portable) to just inject an iframe pointing at the content? – symcbean Jun 20 '16 at 14:11
  • If the content is third party iframe's may be the way to go, if not i would avoid. I'm stuck supporting a legacy application where devs long gone thought modular design through Iframes would be a good idea. Now they just cause huge headaches and generally a pain. – ste2425 Jun 20 '16 at 14:13
  • Yeah it would be indeed easier I think. Unfortunately I have to use it this way with how things are designed. The files are on a separated server and I have to provide some parameters to get them so there's no physical path for them :( – Guigui Jun 20 '16 at 14:16
  • Found a temporary solution by doing a `window.open(mycalltogetthefileinfo)` which only opens the file so we then can download it manually – Guigui Jun 20 '16 at 14:46
  • You have to download the data as a binary type instead of text. – Musa Jun 20 '16 at 15:41

1 Answers1

1

Found a way to do it using the way described below by simulating an tag with href and download parameters :)

how to set a file name using window.open

Community
  • 1
  • 1
Guigui
  • 641
  • 4
  • 8
  • 23