I am allowing the user to load images into a page via drag&drop and other methods. When an image is dropped, I'm using URL.createObjectURL
to convert to an object URL to display the image. I am not revoking the url, as I do reuse it.
So, when it comes time to create a FormData
object so I can allow them to upload a form with one of those images in it, is there some way I can then reverse that Object URL back into a Blob
or File
so I can then append it to a FormData
object?
Maybe someone finds this useful when working with React/Node/Axios. I used this for my Cloudinary image upload feature with
react-dropzone
on the UI.If you show the file in a canvas anyway you can also convert the canvas content to a blob object.
Unfortunately @BrianFreud's answer doesn't fit my needs, I had a little different need, and I know that is not the answer for @BrianFreud's question, but I am leaving it here because a lot of persons got here with my same need. I needed something like 'How to get a file or blob from an URL?', and the current correct answer does not fit my needs because its not cross-domain.
I have a website that consumes images from an Amazon S3/Azure Storage, and there I store objects named with uniqueidentifiers:
sample: http://****.blob.core.windows.net/systemimages/bf142dc9-0185-4aee-a3f4-1e5e95a09bcf
Some of this images should be download from our system interface. To avoid passing this traffic through my HTTP server, since this objects does not require any security to be accessed (except by domain filtering), I decided to make a direct request on user's browser and use local processing to give the file a real name and extension.
To accomplish that I have used this great article from Henry Algus: http://www.henryalgus.com/reading-binary-files-using-jquery-ajax/
1. First step: Add binary support to jquery
2. Second step: Make a request using this transport type.
Now you can use the Blob created as you want to, in my case I want to save it to disk.
3. Optional: Save file on user's computer using FileSaver
I have used FileSaver.js to save to disk the downloaded file, if you need to accomplish that, please use this javascript library:
https://github.com/eligrey/FileSaver.js/
I expect this to help others with more specific needs.
As gengkev alludes to in his comment above, it looks like the best/only way to do this is with an async xhr2 call:
Update (2018): For situations where ES5 can safely be used, Joe has a simpler ES5-based answer below.
See Getting BLOB data from XHR request which points out that BlobBuilder doesn't work in Chrome so you need to use:
Modern solution:
The url can be an object url or a normal url.