File uploading is a common requirement in Web development. You need to use the file input box to upload files. If you add a multiple attribute to the file input box, you can select multiple files at once. File (unsupported browsers will automatically ignore this attribute)
<input multiple type="file">
Click this input box to open the browse file dialog box to select files. Generally, one input box is enough to upload one file, and multiple files can be uploaded. You can use multiple input boxes to handle this. This is done to be compatible with browsers that do not support the multiple attribute. At the same time, users generally will not select multiple files
(recommended Study: HTML video tutorial )
Basic upload method
Put the file input box into the form. When submitting the form, you can submit the selected files together and upload them to the server. It should be noted that since the submitted form contains files, you need to modify the enctype of the form elements. The attribute is multipart/form-data
<form action="#" enctype="multipart/form-data" method="post"> <input name="file" type="file"> <button type="submit">Upload</button> </form>
This upload method is a traditional synchronous upload. If the uploaded file is large, you often need to wait for a long time, and the page will be reloaded after the upload is completed. And you must wait for the upload to complete before continuing.
Early browsers do not support asynchronous upload, but you can use iframe to simulate it, hide an
<form action="#" enctype="multipart/form-data" method="post" target="upload-frame"> <input name="file" type="file"> <button type="submit">Upload</button> </form> <iframe id="upload-frame" name="upload-frame" src="about:blank" style="display: none;"></iframe>
In this way, when the form is submitted for upload, the page will not be reloaded. Instead, the iframe will be reloaded. However, the iframe is originally hidden and will not be noticed even if it is reloaded.
Accessing files
File API provides the ability to access files through the files attribute of the input box. This will get a FileList, which is a collection. If only one is selected file, then the first element in the collection is this file
var input = document.querySelector('input[type="file"]') var file = input.files[0] console.log(file.name) // 文件名称 console.log(file.size) // 文件大小 console.log(file.type) // 文件类型
Browsers that support File API can refer to caniuse
Ajax upload
Because You can directly access the file content through the File API, then upload the file directly with the XMLHttpRequest object, and pass it as a parameter to the send method of the XMLHttpRequest object
var xhr = new XMLHttpRequest() xhr.open('POST', '/upload/url', true) xhr.send(file)
However, for some reasons it is not recommended to pass files directly like this. Instead, use the FormData object to package the files that need to be uploaded. FormData is a constructor. When using it, first create a new instance, and then pass the append of the instance. Method to add data to it, directly add the files that need to be uploaded
var formData = new FormData() formData.append('file', file, file.name) // 第 3 个参数是文件名称 formData.append('username', 'Mary') // 还可以添加额外的参数
You can even directly use the form elements as instantiation parameters, so that all the data in the entire form is included
var formData = new FormData(document.querySelector('form'))
After the data is ready, it is uploaded. It is also passed as a parameter to the send method of the XMLHttpRequest object
var xhr = new XMLHttpRequest() xhr.open('POST', '/upload/url', true) xhr.send(formData)
The XMLHttpRequest object also provides a progress Event, based on this event you can know the upload progress
var xhr = new XMLHttpRequest() xhr.open('POST', '/upload/url', true) xhr.upload.onprogress = progressHandler // 这个函数接下来定义
The upload progress event is triggered by the xhr.upload object, use the of this event object in the event handler loaded (number of bytes uploaded) and total (total number) properties to calculate the upload progress
function progressHandler(e) { var percent = Math.round((e.loaded / e.total) * 100) }
上面的计算会得到一个表示完成百分比的数字,不过这两个值也不一定总会有,保险一点先判断一下事件对象的 lengthComputable 属性
function progressHandler(e) { if (e.lengthComputable) { var percent = Math.round((e.loaded / e.total) * 100) } }
支持 Ajax 上传的浏览器可以参考 caniuse https://caniuse.com/#feat=xhr2
分割上传
使用文件对象的 slice 方法可以分割文件,给该方法传递两个参数,一个起始位置和一个结束位置,这会返回一个新的 Blob 对象,包含原文件从起始位置到结束位置的那一部分(文件 File 对象其实也是 Blob 对象,这可以通过 file instanceof Blob 确定,Blob 是 File 的父类)
var blob = file.slice(0, 1024) // 文件从字节位置 0 到字节位置 1024 那 1KB
将文件分割成几个 Blob 对象分别上传就能实现将大文件分割上传
function upload(file) { let formData = new FormData() formData.append('file', file) let xhr = new XMLHttpRequest() xhr.open('POST', '/upload/url', true) xhr.send(formData) } var blob = file.slice(0, 1024) upload(blob) // 上传第一部分 var blob2 = file.slice(1024, 2048) upload(blob2) // 上传第二部分 // 上传剩余部分
通常用一个循环来处理更方便
var pos = 0 // 起始位置 var size = 1024 // 块的大小 while (pos < file.size) { let blob = file.slice(pos, pos + size) // 结束位置 = 起始位置 + 块大小 upload(blob) pos += size // 下次从结束位置开始继续分割 }
服务器接收到分块文件进行重新组装的代码就不在这里展示了
使用这种方式上传文件会一次性发送多个 HTTP 请求,那么如何处理这种多个请求同时发送的情况呢?方法有很多,可以用 Promise 来处理,让每次上传都返回一个 promise 对象,然后用 Promise.all 方法来合并处理,Promise.all 方法接受一个数组作为参数,因此将每次上传返回的 promise 对象放在一个数组中
var promises = [] while (pos < file.size) { let blob = file.slice(pos, pos + size) promises.push(upload(blob)) // upload 应该返回一个 promise pos += size }
同时改造一下 upload 函数使其返回一个 promise
function upload(file) { return new Promise((resolve, reject) => { let formData = new FormData() formData.append('file', file) let xhr = new XMLHttpRequest() xhr.open('POST', '/upload/url', true) xhr.onload = () => resolve(xhr.responseText) xhr.onerror = () => reject(xhr.statusText) xhr.send(formData) }) }
当一切完成后
Promise.all(promises).then((response) => { console.log('Upload success!') }).catch((err) => { console.log(err) })
支持文件分割的浏览器可以参考 caniuse
判断一下文件对象是否有该方法就能知道浏览器是否支持该方法,对于早期的部分版本浏览器需要加上对应的浏览器厂商前缀
var slice = file.slice || file.webkitSlice || file.mozSlice if (slice) { let blob = slice.call(file, 0, 1024) // call upload(blob) } else { upload(file) // 不支持分割就只能直接上传整个文件了,或者提示文件过大 }
拖拽上传
通过拖拽 API 可以实现拖拽文件上传,默认情况下,拖拽一个文件到浏览器中,浏览器会尝试打开这个文件,要使用拖拽功能需要阻止这个默认行为
document.addEventListener('dragover', function(e) { e.preventDefault() e.stopPropagation() })
任意指定一个元素来作为释放拖拽的区域,给一个元素绑定 drop 事件
var element = document.querySelector('label') element.addEventListener('drop', function(e) { e.preventDefault() e.stopPropagation() // ... })
通过该事件对象的 dataTransfer 属性获取文件,然后上传即可
var file = e.dataTransfer.files[0] upload(file) // upload 函数前面已经定义
选择类型
给文件输入框添加 accept 属性即可指定选择文件的类型,比如要选择 png 格式的图片,则指定其值为 image/png,如果要允许选择所有类型的图片,就是 image/*
<input accept="image/*" type="file">
添加 capture 属性可以调用设备机能,比如 capture="camera" 可以调用相机拍照,不过这并不是一个标准属性,不同设备实现方式也不一样,需要注意
<input accept="image/*" capture="camera" type="file">
经测 iOS 设备添加该属性后只能拍照而不能从相册选择文件了,所以判断一下
if (iOS) { // iOS 用 navigator.userAgent 判断 input.removeAttribute('capture') }
不支持的浏览器会自动忽略这些属性
自定义样式
文件输入框在各个浏览器中呈现的样子都不大相同,而且给 input 定义样式也不是那么方便,如果有需要应用自定义样式,有一个技巧,可以用一个 label 关联到这个文件输入框,当点击这个 label 元素的时候就会触发文件输入框的点击,打开浏览文件的对话框,相当于点击了文件输入框一样的效果
<label for="file-input"></label> <input id="file-input" style="clip: rect(0,0,0,0); position: absolute;" type="file">
这时就可以将原本的文件输入框隐藏了,然后给 label 元素任意地应用样式,毕竟要给 label 元素应用样式比 input 方便得多
本文来自PHP中文网,html教程栏目,欢迎学习
The above is the detailed content of Various implementation methods of file upload in web development (with code). For more information, please follow other related articles on the PHP Chinese website!