Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to upload files for web development

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

Most people do not understand the knowledge of this article "how to upload files for web development", so the editor summarizes the following contents, detailed contents, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "how to upload files for web development" article.

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 more than one file 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 element's target attribute value as the element's name attribute value

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

FileAPI 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.

Varinput=document.querySelector ('input [type = "file"]')

Varfile=input.files [0]

Console.log (file.name) / / File name

Console.log (file.size) / / File size

Console.log (file.type) / / File Type

Browsers that support FileAPI can refer to caniuse

Ajax upload

Since the contents of the file can be accessed directly through FileAPI, and then uploaded directly with the XMLHttpRequest object, it can be passed as a parameter to the send method of the XMLHttpRequest object.

Varxhr=newXMLHttpRequest ()

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.

VarformData=newFormData ()

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.

VarformData=newFormData (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

Varxhr=newXMLHttpRequest ()

Xhr.open ('POST','/upload/url',true)

Xhr.send (formData)

Monitor the progress of upload

The XMLHttpRequest object also provides a progress event based on which you can know how the upload is progressing.

Varxhr=newXMLHttpRequest ()

Xhr.open ('POST','/upload/url',true)

The function xhr.upload.onprogress=progressHandler// 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.

FunctionprogressHandler (e) {

Varpercent=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.

FunctionprogressHandler (e) {

If (e.lengthComputable) {

Varpercent=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 fileinstanceofBlob, and Blob is the parent class of File)

Varblob=file.slice (0J01024) / / 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.

Functionupload (file) {

LetformData=newFormData ()

FormData.append ('file',file)

Letxhr=newXMLHttpRequest ()

Xhr.open ('POST','/upload/url',true)

Xhr.send (formData)

}

Varblob=file.slice (0pc1024)

Upload (blob) / / upload the first part

Varblob2=file.slice (1024pd2048)

Upload (blob2) / / upload the second part

/ / upload the rest

It is usually more convenient to use a loop to deal with

Varpos=0// start position

The size of the varsize=1024// block

While (posresolve (xhr.responseText))

Xhr.onerror= () = > reject (xhr.statusText)

Xhr.send (formData)

})

}

When everything is done,

Promise.all (promises) .then ((response) = > {

Console.log ('upload upload')

}) .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.

Varslice=file.slice | | file.webkitSlice | | file.mozSlice

If (slice) {

Letblob=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 drop 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

Varelement=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.

Varfile=e.dataTransfer.files [0]

The upload (file) / / upload function has been defined previously

Select Typ

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 is judged by navigator.userAgent

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.

The above is about the content of this article on "how to upload files for web development". I believe we all have a certain understanding. I hope the content shared by the editor will be helpful to you. If you want to know more about the relevant knowledge, please 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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report