


Various implementation methods of file upload in web development (with code)
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>
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
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
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)
Monitoring the upload progress
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 <p>服务器接收到分块文件进行重新组装的代码就不在这里展示了</p><p>使用这种方式上传文件会一次性发送多个 HTTP 请求,那么如何处理这种多个请求同时发送的情况呢?方法有很多,可以用 Promise 来处理,让每次上传都返回一个 promise 对象,然后用 Promise.all 方法来合并处理,Promise.all 方法接受一个数组作为参数,因此将每次上传返回的 promise 对象放在一个数组中</p><pre class="brush:php;toolbar:false">var promises = [] while (pos <p>同时改造一下 upload 函数使其返回一个 <span style="color: rgb(255, 0, 0); background-color: rgb(253, 234, 218);">promise</span></p><pre class="brush:php;toolbar:false">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>
添加 capture 属性可以调用设备机能,比如 capture="camera" 可以调用相机拍照,不过这并不是一个标准属性,不同设备实现方式也不一样,需要注意
<input>
经测 iOS 设备添加该属性后只能拍照而不能从相册选择文件了,所以判断一下
if (iOS) { // iOS 用 navigator.userAgent 判断 input.removeAttribute('capture') }
不支持的浏览器会自动忽略这些属性
自定义样式
文件输入框在各个浏览器中呈现的样子都不大相同,而且给 input 定义样式也不是那么方便,如果有需要应用自定义样式,有一个技巧,可以用一个 label 关联到这个文件输入框,当点击这个 label 元素的时候就会触发文件输入框的点击,打开浏览文件的对话框,相当于点击了文件输入框一样的效果
<input>
这时就可以将原本的文件输入框隐藏了,然后给 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!

The function of HTML is to define the structure and content of a web page, and its purpose is to provide a standardized way to display information. 1) HTML organizes various parts of the web page through tags and attributes, such as titles and paragraphs. 2) It supports the separation of content and performance and improves maintenance efficiency. 3) HTML is extensible, allowing custom tags to enhance SEO.

The future trends of HTML are semantics and web components, the future trends of CSS are CSS-in-JS and CSSHoudini, and the future trends of JavaScript are WebAssembly and Serverless. 1. HTML semantics improve accessibility and SEO effects, and Web components improve development efficiency, but attention should be paid to browser compatibility. 2. CSS-in-JS enhances style management flexibility but may increase file size. CSSHoudini allows direct operation of CSS rendering. 3.WebAssembly optimizes browser application performance but has a steep learning curve, and Serverless simplifies development but requires optimization of cold start problems.

The roles of HTML, CSS and JavaScript in web development are: 1. HTML defines the web page structure, 2. CSS controls the web page style, and 3. JavaScript adds dynamic behavior. Together, they build the framework, aesthetics and interactivity of modern websites.

The future of HTML is full of infinite possibilities. 1) New features and standards will include more semantic tags and the popularity of WebComponents. 2) The web design trend will continue to develop towards responsive and accessible design. 3) Performance optimization will improve the user experience through responsive image loading and lazy loading technologies.

The roles of HTML, CSS and JavaScript in web development are: HTML is responsible for content structure, CSS is responsible for style, and JavaScript is responsible for dynamic behavior. 1. HTML defines the web page structure and content through tags to ensure semantics. 2. CSS controls the web page style through selectors and attributes to make it beautiful and easy to read. 3. JavaScript controls web page behavior through scripts to achieve dynamic and interactive functions.

HTMLisnotaprogramminglanguage;itisamarkuplanguage.1)HTMLstructuresandformatswebcontentusingtags.2)ItworkswithCSSforstylingandJavaScriptforinteractivity,enhancingwebdevelopment.

HTML is the cornerstone of building web page structure. 1. HTML defines the content structure and semantics, and uses, etc. tags. 2. Provide semantic markers, such as, etc., to improve SEO effect. 3. To realize user interaction through tags, pay attention to form verification. 4. Use advanced elements such as, combined with JavaScript to achieve dynamic effects. 5. Common errors include unclosed labels and unquoted attribute values, and verification tools are required. 6. Optimization strategies include reducing HTTP requests, compressing HTML, using semantic tags, etc.

HTML is a language used to build web pages, defining web page structure and content through tags and attributes. 1) HTML organizes document structure through tags, such as,. 2) The browser parses HTML to build the DOM and renders the web page. 3) New features of HTML5, such as, enhance multimedia functions. 4) Common errors include unclosed labels and unquoted attribute values. 5) Optimization suggestions include using semantic tags and reducing file size.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

SublimeText3 Linux new version
SublimeText3 Linux latest version

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.