Read File stored on some URL using HTML5 File API
Asked Answered
H

1

9

I'm using HTML5 file API to upload files to my web application.

I have an input element on my web page using which I read files and call upload function

<input type="file">

$('input[type="file"]').on("change",function(e){
      console.log(this.files);
      // upload each file in this.files
});

This works perfectly for native files on os. I want to now upload remote files e.g., example.com/blah/file1.jpg My question is how do I read this file using File API? Is there a way to do it?

Hedy answered 14/7, 2014 at 22:49 Comment(4)
Just a provide a TextBox for the user to paste the URL. Then on the server side you can retrieve the file based on the URL.Reimer
no this has to be done on client side, it's a browser extension. I need to download the file first into user's browser and then upload.Hedy
Why do you need to download to the user's computer, then upload to a server? That's an extra step. Storing it in JavaScript's memory would be bad performance wise, as well as eating up the user's bandwidth.Reimer
because I don't own the server... I need to send them actual bits of the file in order to upload.Hedy
L
8

You can download remote files over XMLHttpRequest, and process them as Blob. Then upload it to another server. The upload has to be over XMLHttpRequest. It relies on the browser's implementation of XHR Level 2. This link contains the code snippets you will need:

http://www.html5rocks.com/en/tutorials/file/xhr2/

It has both snippets for downloading remote file as a Blob and uploading a Blob to a server.

Legendre answered 15/7, 2014 at 3:16 Comment(4)
thanks tiger, it worked like a charm except I lose all the metadata when I say var blob = new Blob([this.response], {type: 'image/png'}); how do I get the filename after doing this?Hedy
@sublime: I don't think there's "filename" if we are retrieving a file over network. Say it's /download?id=1234, there's no filename at all. So you need to set up your own rules about getting the filename. You can follow what most browsers do: 1. Take the last part of the URI path and treat it as a file; 2. If content-disposition exists in response header, follow the standard and use what's in it as filename.Legendre
Thanks, one last question: some image urls that I'm getting are base64 encoded data strings. data:image/jpeg;base64,/9j/4AAQSkZJRgABAQ... and when that's the case browser throws an error saying XMLHttpRequest cannot load data:image, cross origin requests are only supported for HTTP. How do I download those images?Hedy
nevermind, I found this on how to convert dataURI to image blob #4999408Hedy

© 2022 - 2024 — McMap. All rights reserved.