Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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) ?

like image 597
phepa Avatar asked Oct 19 '25 23:10

phepa


2 Answers

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.

like image 86
Timo Avatar answered Oct 22 '25 12:10

Timo


This is the same snippet from above, with 2 improvements:

  • Download link is not visible
  • Download starts automatically (if not blocked by browser)

Filename is still not getting taken

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.href = objectURL;
  link.click();
});
<input type="file" id="upload" />
<a id="link" download style="display: none">shouldnt be visible</a>
like image 33
Tobias Fuchs Avatar answered Oct 22 '25 12:10

Tobias Fuchs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!