In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
This article mainly introduces the web development of file upload implementation of what is the relevant knowledge, the content is detailed and easy to understand, the operation is simple and fast, with a certain reference value, I believe that everyone after reading this web development of file upload implementation of which articles will have a harvest, let's take a look at it.
File upload is a common requirement in Web development. File input box is needed to upload files. If you add a multiple attribute to the file input box, you can select multiple files at a time (unsupported browsers will automatically ignore this attribute)
Click on this input box to open the browse file dialog box to select a file. Generally, one file can be uploaded in one input box, and multiple input boxes can be used to upload multiple files. This is done in order to be compatible with browsers that do not support multiple attributes, and users generally do not select multiple files.
Basically the mode of transmission
When the file input box is put into the form, the selected files can be submitted and uploaded to the server when the form is submitted. It should be noted that since the submitted form contains files, the enctype attribute of the form element should be changed to multipart/form-data.
Upload
In this way, the upload method is the traditional synchronous upload. If the uploaded file is very large, you often have to wait a long time, and the page will be reloaded after the upload is completed, and you must wait for the upload to be completed before you can continue the operation.
Early browsers did not support asynchronous upload, but you could use iframe to simulate, hide an element in the page, specify a name value, and associate the two by specifying the target attribute value of the element as the name attribute value of the element
Upload
In this way, when the form is submitted for upload, the page will not be reloaded. Instead, the iframe will be reloaded, but the iframe is already hidden and will not be perceived even if it is reloaded.
Access Fil
File API provides the ability to access files, which is accessed through the files attribute of the input box, which results in a FileList, which is a collection. If only one file is selected, 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) / / file name console.log (file.size) / / file size console.log (file.type) / / file type
Browsers that support File API can refer to caniuse
Ajax upload
Since the contents of the file can be accessed directly through File API, and then uploaded directly with the XMLHttpRequest object, it can be passed 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 transfer files directly in this way, but to use FormData objects to wrap the files that need to be uploaded. FormData is a constructor. When you use it, you first new an instance, and then add data to it through the append method of the instance, directly adding the files to be uploaded.
Var formData = new FormData () formData.append ('file', file, file.name) / / the third parameter is the file name formData.append (' username', 'Mary') / / additional parameters can be added
You can even directly use the form element as an instantiation parameter so that all the data in the entire form is included.
Var formData = new FormData (document.querySelector ('form'))
When the data is ready, it is uploaded, which 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) to monitor the upload progress
The XMLHttpRequest object also provides a progress event based on which you can know how the upload is progressing.
Var xhr = new XMLHttpRequest () xhr.open ('POST',' / upload/url', true) xhr.upload.onprogress = progressHandler / / this function is then defined
The uploaded progress event is triggered by the xhr.upload object, and the loaded (uploaded bytes) and total (total) properties of this event object are used in the event handler to calculate the upload progress.
Function progressHandler (e) {var percent = Math.round ((e.loaded / e.total) * 100)}
The above calculation will get a number that represents the percentage of completion, but these two values may not always be there, so let's first judge the lengthComputable property of the event object.
Function progressHandler (e) {if (e.lengthComputable) {var percent = Math.round ((e.loaded / e.total) * 100)}}
Browsers that support Ajax upload can refer to caniuse https://caniuse.com/#feat=xhr2
Split upload
Using the slice method of the file object, you can split the file, passing the method two parameters, a start position and an end position, which returns a new Blob object that contains the part of the original file from the start position to the end position (the file File object is also a Blob object, which can be determined by file instanceof Blob, and Blob is the parent class of File)
Var blob = file.slice (0, 1024) / / the file 1KB from byte position 0 to byte position 1024
By dividing the file into several Blob objects and uploading them separately, you can upload large files separately.
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) / / upload the first part var blob2 = file.slice (1024, 2048) upload (blob2) / / upload the second part / / upload the rest
It is usually more convenient to use a loop to deal with
Var pos = 0 / / start position var size = 1024 / / the size of the block 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)})}
When everything is done,
Promise.all (promises) .then ((response) = > {console.log ('Upload roommates')}) .catch ((err) = > {console.log (err)})
Browsers that support file segmentation can refer to caniuse
Determine whether the file object has this method to know whether the browser supports this method. For some early versions of browsers, you need to add the corresponding browser vendor prefix.
Var slice = file.slice | | file.webkitSlice | | file.mozSliceif (slice) {let blob = slice.call (file, 0, 1024) / / call upload (blob)} else {upload (file) / / if split is not supported, you can only upload the entire file directly, or prompt that the file is too large} drag and upload
You can upload files by dragging and dropping API. By default, dragging a file to the browser will try to open the file. To use the drag-and-drop function, you need to prevent this default behavior.
Document.addEventListener ('dragover', function (e) {e.preventDefault () e.stopPropagation ()})
Arbitrarily specify an element as the area to release the drag and bind an element to the drop event
Var element = document.querySelector ('label') element.addEventListener (' drop', function (e) {e.preventDefault () e.stopPropagation () / /...})
Get the file through the dataTransfer attribute of the event object, and then upload it.
Var file = e.dataTransfer.files [0] upload (file) / / upload function has already defined the selection type
Add the accept attribute to the file input box to specify the type of file to be selected. For example, if you want to select a picture in png format, specify its value as image/png. If you want to allow all types of pictures to be selected, it is image/*.
Add the capture attribute to call the device function, for example, capture= "camera" can call the camera to take pictures, but this is not a standard attribute, and different devices are implemented in different ways, so you should pay attention to it.
After testing the iOS device to add this attribute, you can only take pictures instead of selecting files from the album, so judge
If (iOS) {/ / iOS uses navigator.userAgent to judge input.removeAttribute ('capture')}
Unsupported browsers automatically ignore these attributes
Custom style
The appearance of the file input box is different in different browsers, and it is not so convenient to define styles for input. If you need to apply custom styles, there is a technique that you can use a label to associate to the file input box. When you click on this label element, it will trigger the click of the file input box and open the dialog box for browsing the file, which is equivalent to clicking on the file input box.
At this point, you can hide the original file input box and apply styles to label elements arbitrarily. After all, it is much more convenient to apply styles to label elements than to input.
This is the end of the article on "what are the ways to upload files developed by web?" Thank you for your reading! I believe that everyone has a certain understanding of the knowledge of "what is the way to upload files developed by web". If you want to learn more knowledge, you are welcome to follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.