File object to image with correct file name instead of src=“blob…”

岁酱吖の 提交于 2020-01-13 10:15:05

问题


I have a File object myFile 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?


回答1:


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.

Workarounds

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



来源:https://stackoverflow.com/questions/37726789/file-object-to-image-with-correct-file-name-instead-of-src-blob

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!