CourtneyJ
CourtneyJ

Reputation: 508

Convert uploaded image to URL using FileReader

I am a new developer and sometimes I don't understand my errors. Here I am getting an error Uncaught TypeError: Failed to execute 'readAsDataURL' on 'FileReader': parameter 1 is not of type 'Blob'. . Im not sure what parameter the error is referring to or how to make it of Blob type. I was thinking it should be converted into an array but that did not work either. Can anyone help? My goal here is to allow the user to upload and image I want to convert that image to a URL and display a preview of the image on the screen.

This is the function that is handling my uploaded image

 const onFileSelect = (fieldName) => (event) => {
    console.log(event.target.value)
    
    const reader = new FileReader()
    const image = event.target.value
    
    reader.addEventListener("load", () => {
      console.log(image.results)

    }, false)
    reader.readAsDataURL(image)
    // const newImage = {...newOrg.logoURL, [fieldName]: event.target.value}
  }

This is my input field for allowing the user to upload the image

<FormGroup>
      <div>
          
       <Input 
       type="file"
       name="data.logoURL"
       onChange={onFileSelect("logoURL")}
       accept="image/*"
       />{" "}

        </div>
      </FormGroup>

if I am not showing enough code please let me know.

Upvotes: 1

Views: 331

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074495

Assuming Input is a wrapper on input, the file isn't available on the value property (value is always a string on input elements). it's available on its array-like list of files called files. So for the first one:

const image = event.target.files[0]
// −−−−−−−−−−−−−−−−−−−−−−−−^^^^^^^^

Upvotes: 2

Related Questions