<input type="file" @change="handleUpdateFIle">
I’m having trouble running the following code snippet in my application. When I try to set the src of an img element using the result of a FileReader object, I get an error saying "img src is not valid". Can you help me fix this issue?
const handleUpdateFIle = (e: file) => {
const file= e.target.files[0]
const reader = new FileReader()
const img = new Image()
reader.onload = () => {
const arrayBuffer = reader.result
const blob = new Blob([arrayBuffer],{type: file.type || 'image/png'})
console.log('blob',blob)
const URL = window.URL || window.webkitURL
const url = URL.createObjectURL(blob)
img.src = url
//img.src blob:http:xxx
}
reader.readAsArrayBuffer(file)
}
console tip
Uncaught (in promise) img src is not valid
I’ve tried using readAsDataURL instead of readAsArrayBuffer, but I still get the same error. Can you please provide a solution?
img.src = URL.createObjectURL(file)
2
Answers
The reason it’s not working is because the
src
* attribute accepts a URL, which is aString
— but here you are inserting an array buffer**.You have to either…
Example 1: Using a Data URL
Friend, you’re using a FileReader to generate a blob when the file got from the
<input>
field is already blob like.See if this example works for you:
NOTE that Object URLs are usable only at the environment that sets them (like the client used). This means the generated URL by
URL.createObjectURL()
is not accessible in other clients (because the generator client does not turn into a server to serve the link). In other words, if the URL is generated in Chrome, you can’t retrieve the file at Firefox with that URL.