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?

sublime
  • 4,013
  • 9
  • 53
  • 92
  • 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. – mason Jul 14 '14 at 22:51
  • 1
    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. – sublime Jul 14 '14 at 22:52
  • 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. – mason Jul 14 '14 at 22:55
  • because I don't own the server... I need to send them actual bits of the file in order to upload. – sublime Jul 14 '14 at 22:58

1 Answers1

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.

Marius Butuc
  • 17,781
  • 22
  • 77
  • 111
Cat Chen
  • 2,387
  • 17
  • 12
  • 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? – sublime Jul 15 '14 at 23:08
  • @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. – Cat Chen Jul 16 '14 at 03:00
  • 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? – sublime Jul 16 '14 at 19:10
  • nevermind, I found this on how to convert dataURI to image blob http://stackoverflow.com/questions/4998908/convert-data-uri-to-file-then-append-to-formdata – sublime Jul 16 '14 at 20:26