1

Is there a way to download a file that has been uploaded in the browser using a file input? This will need to be a client-side solution(will save me time rather than uploading and deleting the file in the server if they cancel the form). I did ask my project manager "Why would you want to download a file you just uploaded seconds ago?", I didn't get a good answer, but they want it.

Select a file: <input type="file" id="file">
<a id='link' href="" download="download">Download</a>

<script>
link = document.querySelector("#link");
file = document.querySelector("#file");

// NEED TO DOWNLOAD SELECTED FILE LOCALLY
file.onchange = function() {
  link.href = file.value;  
}
</script>
RedLotus
  • 79
  • 8
  • 4
    if the form is not submitted the file is not on the server yet and you can access it with the FileReader API: https://developer.mozilla.org/en-US/docs/Web/API/FileReader – Paul G Mihai Nov 05 '18 at 23:09
  • 1
    Yes I'm aware the file is not on the server. How would I download from the FileReader API ? This has to support pdf, docx, and txt extensions. – RedLotus Nov 05 '18 at 23:19
  • 1
    the filereader is binary it doesn't know what it is reading neither should you care in your situation. Try reading through the filereader api and get the binary from the file then encode it as base64 and open a window or make a redirect to "data:application/octet-stream,"+mybase64encodedfile check this out for more details https://stackoverflow.com/questions/2897619/using-html5-javascript-to-generate-and-save-a-file – Paul G Mihai Nov 05 '18 at 23:27
  • 1
    Thanks Paul, I was able to download it by getting the filereader's target result. – RedLotus Nov 05 '18 at 23:53
  • 2
    // For those interested var reader = new FileReader(); reader.onload = function(event){ the_url = event.target.result $('#link').attr("href", the_url) $('#link').attr("download", file.name) } – RedLotus Nov 05 '18 at 23:55
  • 2
    What is the point for your users of downloading something they already have on their disk? Beside, to download a Blob (or a File), you don't need to read it, and thus you don't need a FileReader. Simply create a BlobURI pointing to it using `URL.createObjectURL(file)` – Kaiido Nov 06 '18 at 00:46

0 Answers0