Mick Mick - 2 years ago 70
Javascript Question

File object to image with correct file name instead of src="blob..."

I have a File object

that looks like this in console:

File {
name: "myimage.jpg",
lastModified: 1465476925001,
lastModifiedDate: Thu Jun 09 2016 14:55:25 GMT+0200 (CEST),
size: 33002
type: "image/jpeg"

But when i create an image out of it with

var image = new Image();
image.src = URL.createObjectURL(myFile);

I get:

<img src="blob:http://myurl.com/6b2b83d8-ac36-40c1-8ab1-c4f07b019ba5">

When i try to save the file with right-click, the file-name is empty or "6b2b83d8-ac36-40c1-8ab1-c4f07b019ba5" instead of "myimage.jpg". The file-name from the file-object is gone. Is there any way to set the image file name?

Answer Source

The Problem

The File object is sort of an extended version of a Blob that allows it to hold metadata such as filename, size etc.

However, while createObjectURL() will reference both File and Blob the data read through the blob: protocol will only consist of the binary file data itself as when loading via other protocols. No metadata (such as filename) will be provided via the protocol.

Other examples where filename is not considered could be when an image is loaded via for example a PHP or ASPX page (/getimage.aspx?id=1). Also here there is no metadata provided and browser would suggest something like "getimage.aspx%3Fid=1" as filename in this case. As expected.

The IMG tag itself never assumes any filename even if one is used at source point; it only holds what is given to it via the src attribute/property as-is, as a connection point to retrieve the needed binary data for decoding.

In this case the source point is blob:*/* which then will be what IMG tag references via src, and is what the browser use when the data is to be saved.


The only way to hold on to a filename from the File object is to keep track of it so you have access to it when needed for download.

But also this is limited as you can only specify a filename using the download attribute in an A tag. And of course, some browsers such as <= IE11 does not support this attribute.

<a href="blob:.." download="filename.jpg"><img ..></a>

In IE10+ there is the proprietary method msSaveBlob() which can be used instead though:

window.navigator.msSaveBlob(myBlob, 'filename.jpg');

Besides from these there are no common way to specify a default filename from within the client.

Example fiddle

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download