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

I have a File myFile object that looks like on the 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 from it using

 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 a file with a right-click, the file name is empty or "6b2b83d8-ac36-40c1-8ab1-c4f07b019ba5" instead of "myimage.jpg". The file name from the object file is missing. Is there any way to set the image file name?

+5
source share
1 answer

Problem

The File object is an extended version of Blob that allows you to store metadata such as file name, size, etc.

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

Other examples in which the file name is not considered may be when the image is uploaded, for example, to a PHP or ASPX page ( /getimage.aspx?id=1 ). There is also no metadata, in which case the browser will offer something like "getimage.aspx% 3Fid = 1" as the file name. As expected.

The IMG tag itself never accepts a single file name, even if it is used at the origin; it contains only what is given to it using the src attribute / property as-is attribute, as a connection point for retrieving the necessary binary data for decoding.

In this case, the starting point is blob:*/* , which will then be what the IMG tag is referenced via src , and this is what the browser uses when the data needs to be saved.

Bypass

The only way to save the file name from the File object is to track it so that you have access to it when it is needed for downloading.

But it’s also limited since you can only specify the file name using the download attribute in tag A And of course, some browsers, such as <= IE11, do not support this attribute.

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

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

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

In addition, there is no general way to specify a default file name from within the client.

Violin example

+4
source

All Articles