JavaScript: Upload file


Translate

Let's say I have this element on the page:

<input id="image-file" type="file" />

This will create a button that allows the users of the web page to select a file via an OS "File open..." dialog in the browser.

Let's say the user clicks said button, selects a file in the dialog, then clicks the "Ok" button to close the dialog.

The selected file name is now stored in:

document.getElementById("image-file").value

Now, let's say that the server handles multi-part POSTs at the URL "/upload/image".

How do I send the file to "/upload/image"?

Also, how do I listen for notification that the file is finished uploading?



All Answers
  • Translate

    Unless you're trying to upload the file using ajax, just submit the form to /upload/image.

    <form enctype="multipart/form-data" action="/upload/image" method="post">
        <input id="image-file" type="file" />
    </form>
    

    If you do want to upload the image in the background (e.g. without submitting the whole form), you can use ajax:


  • Translate

    Pure JS

    You can use fetch optionally with await-try-catch

    let photo = document.getElementById("image-file").files[0];
    let formData = new FormData();
    
    formData.append("photo", photo);
    fetch('/upload/image', {method: "POST", body: formData});
    

    async function SavePhoto(inp) 
    {
        let user = { name:'john', age:34 };
        let formData = new FormData();
        let photo = inp.files[0];      
             
        formData.append("photo", photo);
        formData.append("user", JSON.stringify(user));  
        
        try {
           let r = await fetch('/upload/image', {method: "POST", body: formData}); 
           console.log('HTTP response code:',r.status); 
        } catch(e) {
           console.log('Huston we have problem...:', e);
        }
        
    }
    <input id="image-file" type="file" onchange="SavePhoto(this)" >
    <br><br>
    Before selecting the file open chrome console > network tab to see the request details.
    <br><br>
    <small>Because in this example we send request to https://stacksnippets.net/upload/image the response code will be 404 ofcourse...</small>
    
    <br><br>
    (in stack overflow snippets there is problem with error handling, however in <a href="https://jsfiddle.net/Lamik/b8ed5x3y/5/">jsfiddle version</a> for 404 errors 4xx/5xx are <a href="https://stackoverflow.com/a/33355142/860099">not throwing</a> at all but we can read response status which contains code)

  • Translate

    As its creator I'm biased ;) but you could also consider using something like https://uppy.io. It does file uploading without navigating away from the page and offers a few bonuses like drag & drop, resuming uploads in case of browser crashes/flaky networks, and importing from e.g. Instagram. It's also open source and does not rely on jQuery or anything like that.