1

I have a reference to a javascript File object (image) which was provided by the user from a "open file dialog". How do I load this image file into a css background-image without having to read all data into a base64-string first?

The examples I have found use a FileReader to read the data and then load that into the css-tag but this seems like a bit of ineffective use of memory. Since I have the File-reference it would be nice if I could pass that into the css-tag somehow instead and let the image be streamed into memory instead. The url()-wrapper for "background-image" supports local filenames but for security reasons the full path of the File is not available to my script so I can't use that.

Any suggestions?

1
  • how about you use a blob URL to reference your image in CSS? Commented Mar 25, 2017 at 16:45

1 Answer 1

4

Let's say you have your File object in a variable called file.

var url = URL.createObjectURL(file)
yourElement.style.background = `url(${url})`

https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.