0

I'm attempting to display both PDF and JPG files that are served from my backend to a new tab inside of the user's web browser. The code below works great for PDF files (opens them in new tabs and has adjustable sizing) but it automatically downloads the JPG files.

I've looked into embedding the images and making them fullscreen in a new tab as well as some react packages but I'm curious to see if there is a better way of doing this

openFile(file) {
  var url = url/path/to/backend/request;
  window.open(url, this.state.song.Title)
}

How can I force the JPG files to be displayed in a new tab like the PDF files are?

Scott.F
  • 57
  • 1
  • 11

2 Answers2

2

window.open should work fine, if it download the file, please check the response header Content-Type of your url is set correctly, it should be image/jpeg or image/png, etc, which depends on your image format.

You can use curl in terminal or use chrome developer tool to find it. If you use curl, try to run curl -I -X GET "your image url" to find out your response headers. You should get something output like this:

HTTP/2 200
server: nginx/1.12.2
date: Sun, 14 Jul 2019 16:26:25 GMT
content-type: image/svg+xml
content-length: 5501
Aprillion
  • 21,510
  • 5
  • 55
  • 89
acrazing
  • 1,955
  • 16
  • 24
0

For one, window.open() is kind of a mean way to do this: it bypasses the normal browser navigation system, so you really want to build an a with target="_blank" instead, which will do the same thing while respecting the user.

(set its style to display:none, remember to add it to the document, then call a.click(), then remove it again)

That said, browsers decide on whether to show or download based on mime-type, so make sure your server responds with the appropriate mime type for the files you want your users to see in-browser rather than download (e.g. don't send images with application/octet-stream)

Mike 'Pomax' Kamermans
  • 49,297
  • 16
  • 112
  • 153