上传图片时的预览功能在很多产品中都是一项基本的需求,展示输入进input的图片,涉及到几个浏览器的api: FileUpload,URL.createObjectURL, DataTransfer
FileUpload
在HTML文档中<input type="file">
标签每出现一次,一个FileUpload对象就会被创建。该元素包含一个文本输入字段,用来输入文件名,还有一个按钮,用来打开文件选择对话框以便图形化选择文件。该元素的value
属性保存了用户指定的文件的名称,但是当包含一个file-upload
元素的表单被提交的时候,浏览器同时会向服务器发送选中的文件的内容而不仅仅是发送文件名。
1 | //获取input[type="file"] |
上传图片后,控制台输出结果如下:
1 | FileList{ |
可以看到,图片上传输入框拥有files属性,该属性为一个类数组对象,当前只有一张图片,该图片的各种信息也被以对象的形式保存在浏览器中,可以用这些属性搞事情
。
window.URL.createObjectURL&&revokeObjectURL
引用自MDN
The URL.createObjectURL() static method creates a DOMString containing a URL representing the object given in the parameter. The URL lifetime is tied to the document in the window on which it was created. The new object URL represents the specified File object or Blob object.
Each time you call createObjectURL(), a new object URL is created, even if you’ve already created one for the same object. Each of these must be released by calling URL.revokeObjectURL() when you no longer need them. Browsers will release these automatically when the document is unloaded; however, for optimal performance and memory usage, if there are safe times when you can explicitly unload them, you should do so.
1 | let newUrlObj=window.URL.revokeObjectURL(objectURL); |
dataTransfer
引自MDN
The DataTransfer object is used to hold the data that is being dragged during a drag and drop operation. It may hold one or more data items, each of one or more data types.
DataTransfer.files
Contains a list of all the local files available on the data transfer. If the drag operation doesn’t involve dragging files, this property is an empty list.(其他属性参见DataTransfer)
示例完整代码,使用拖拽上传图片&&使用createObjectURL展示图片
以下是来自mdn的官方示例,经由个人做了少许的改动并详细注释
See the Pen Using files from web applications by MachineGun (@ThunderboltSmile) on CodePen.