What is the best way to upload files in a modern browser

后端 未结 5 2145
孤街浪徒
孤街浪徒 2020-12-22 22:43

I want to upload a (single) file to a server and show the progress of the upload.

I know I can upload a file using HTTP POST. I\'m not familiar with web-sockets, but

5条回答
  •  难免孤独
    2020-12-22 23:35

    My answer is quite late but here it goes:


    Short answer:

    XMLHttpRequest is the best way to upload files in a modern browser.



    What is XMLHttpRequest?

    XMLHttpRequest is a JavaScript object that was designed by Microsoft and adopted by Mozilla, Apple, and Google. It's now being standardized in the W3C. It provides an easy way to retrieve data from a URL without having to do a full page refresh. A Web page can update just a part of the page without disrupting what the user is doing. XMLHttpRequest is used heavily in AJAX programming.

    Despite its name, XMLHttpRequest can be used to retrieve any type of data, not just XML, and it supports protocols other than HTTP (including file and ftp).

    The XMLHttpRequest object has gotten a facelift in the Html5 specifications. Specifically the XMLHttpRequest Level 2.


    Advantages:

    • Handling of byte streams such as File, Blob and FormData objects for uploading and downloading
    • Progress events during uploading and downloading
    • Cross-origin requests
    • Allow making anonymous request - that is not send HTTP Referer
    • The ability to set a Timeout for the Request
    • Uploading is happening in the background
    • The page the user is on remains intact
    • Does not require any change to the server side, so existing server side logic should remain unchanged, which makes adapting this technology that much easier.

    The Html5 Progress Event:

    As per the Html5 Progress Events spec, the Html5 progress event provides, among others, the following information :

    total - Total bytes being transferred
    loaded - Bytes uploaded thus far
    lengthComputable - Specifies if the total size of the data/file being uploaded is known 
    

    Using the information above, it is fairly easy to provide the "Time remaining" information to the user.


    Keep the user informed:

    Information about the file that can be made available to the user:

    1. File Name
    2. File Size
    3. Mime Type
    4. A Progress bar with percent complete
    5. The upload speed or upload bandwidth
    6. The approximate time remaining
    7. The bytes uploaded thus far
    8. A response from the server side

    File Upload using XMLHttpRequest Demo

    Please check "Uploading files using Html5 with Progress indication demo" for an example. All of the JavaScript code required is in the page but no CSS is included. For security reasons, the file types are limited to jpg, png, gif and txt. Max file size is 2MB.


    XMLHttpRequest Browser Compatibility:

    XMLHttpRequest Browser compatibility


提交回复
热议问题