文件api
Working with file uploads, especially on the front end, was always a hassle. We didn't use to be able to drag and drop files, complete AJAX uploads, provide multiple files, and hell, we couldn't get any information about the file until it hit the server; you'd need to upload the damn file before you could reject it!
处理文件上传,尤其是在前端,总是很麻烦。 我们过去不能拖放文件 ,完成AJAX上传,提供多个文件,而且,在文件到达服务器之前,我们无法获得有关该文件的任何信息。 您需要先上传该死的文件,然后才能拒绝该文件!
Nowadays we have the File API which provides us access to file information via JavaScript and an input[type=file] element. Let's have a look at how the File API works!
如今,我们拥有File API,该API可让我们通过JavaScript和input[type=file]元素访问文件信息。 让我们看一下File API的工作原理!
To get the list of files mapped to a given input[type=file], you use the files property:
要获取映射到给定input[type=file]的文件列表,请使用files属性:
// Assuming <input type="file" id="upload" multiple> var uploadInput = document.getElementById('upload'); uploadInput.addEventListener('change', function() { console.log(uploadInput.files) // File listing! });Unfortunately the FileList doesn't have a forEach method like Array so we'll need to do some old school looping through the FileList:
不幸的是, FileList没有像Array这样的forEach方法,因此我们需要做一些古老的循环遍历FileList :
for (var i = 0, fileCount = uploadInput.files.length; i < fileCount; i++) { console.log(files[i]); }It's important to note that FileList does have a length property.
重要的是要注意FileList确实具有length属性。
Each file in the FileList provides a good set of information on each file, including file size, MIME type, last modified date, and name:
FileList中的每个文件都提供了有关每个文件的一组很好的信息,包括文件大小,MIME类型,上次修改日期和名称:
{ lastModified: 1428005315000, lastModifiedDate: Thu Apr 02 2015 15:08:35 GMT-0500 (CDT), name: "profile.pdf", size: 135568, type: "application/pdf", webkitRelativePath: "" }What's nice about getting this file information is that you can do some very basic validation before uploading the file. For example, you can validate MIME type or total file size:
获得此文件信息的好处是,您可以在上传文件之前进行一些非常基本的验证。 例如,您可以验证MIME类型或文件总大小:
var maxAllowedSize = 500000; for (var i = 0, fileCount = uploadInput.files.length, totalSize = 0; i < fileCount; i++) { totalSize += files[i].size; if(totalSize > maxAllowedSize) { // Notify the user that their file(s) are too large } if(files[i].type != 'application/pdf') { // Notify of invalid file type for file in question } }Total file size is too large or a file doesn't pass the test? Now you can present the user with a message without needing to upload and assess the file first.
文件总大小太大或文件未通过测试? 现在,您可以向用户显示一条消息,而无需先上载和评估文件。
That's my quick look at the File API. It's a sweet little API that can save you and your user some wasted upload time. There's lots more than can be done with the file API, much of which you can find on MDN.
这就是我快速浏览File API的过程。 这是一个可爱的小API,可以为您和您的用户节省一些浪费的上传时间。 文件API可以做很多事情,您可以在MDN上找到很多。
翻译自: https://davidwalsh.name/file-api
文件api