简体   繁体   English

使用 FileReader 将上传的图像转换为 URL

[英]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'.在这里我收到一个错误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.我不确定错误指的是什么参数或如何使其成为 Blob 类型。 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.我的目标是允许用户上传和图像我想将该图像转换为 URL 并在屏幕上显示图像的预览。

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.如果我没有显示足够的代码,请告诉我。

Assuming Input is a wrapper on input , the file isn't available on the value property ( value is always a string on input elements).假定Input是在一个包装input ,该文件是不可用的value属性( value始终是一个字符串input元件)。 it's available on its array-like list of files called files .它在名为files的类似数组的文件列表中可用。 So for the first one:所以对于第一个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM