Search code examples
javascripthtmlfile

Download file just uploaded with html input file


I have classic HTML input type for file

<input type="file" id="xxx" name="xxx" />

And I want the user to have an option to download back the file he just uploaded.

I tried to do it with javascript to download via filepath, but chrome seems to have some security feature that replaces the real path with "fakepath"

C:\fakepath\xxx.pdf

Any idea how to download the uploaded file (just client side, not submitting the form yet) ?


Solution

  • You can use URL.createObjectURL() to create a link that allows the user to download the file.

    const input = document.getElementById('upload');
    const link = document.getElementById('link');
    let objectURL;
    
    input.addEventListener('change', function () {
      if (objectURL) {
        // revoke the old object url to avoid using more memory than needed
        URL.revokeObjectURL(objectURL);  
      }
    
      const file = this.files[0];
      objectURL = URL.createObjectURL(file);
    
      link.download = file.name; // this name is used when the user downloads the file
      link.href = objectURL;
    });
    <input type="file" id="upload" />
    <a id="link" download>link to your file (upload a file first)</a>

    Note on the snippet: The browser may block doing multiple downloads this way.