【问题标题】:Upload Image to Cloudinary with React and Apollo(GraphQL)使用 React 和 Apollo(GraphQL) 将图像上传到 Cloudinary
【发布时间】:2021-03-04 01:28:41
【问题描述】:

目标

我想将用户从反应前端上传的图像上传到 Cloudinary。 下面这个程序给出了错误ENAMETOOLONG 可能是因为图像被转换为​​ BASE64 类型。

React 上传组件代码

const UploadImageComponent = () => {
    const { user } = useContext(AuthContext)
    const [fileInput, setFileInput] = useState('')
    const [selectedFile, setSelectedFile] = useState('')
    const [previewSource, setPreviewSource] = useState();

    function handleSubmit(e){
        const file = e.target.files[0]
        previewFile(file);
    }

    const previewFile = (file) => {
        const reader = new FileReader();
        reader.readAsDataURL(file)
        reader.onloadend = () => {
            setPreviewSource(reader.result)
        }
    }

    const handleSubmitFile = (e) => {
        e.preventDefault()
        if(!previewSource) return;
        uploadImage()
    }
    const [addImage] = useMutation(ADD_IMAGE, {
        variables: {
            userID: user.id,
            photo: JSON.stringify(previewSource)
        }
    })
    const uploadImage = () => {
       addImage();
    }

    return (
        <>
        <Form onSubmit={handleSubmitFile}>
            <Form.Input 
                type="file"
                name="image"
                onChange={handleSubmit}
                value= {fileInput}
            />
            <Button type="submit">
                Submit
            </Button>
        </Form>
        {previewSource && (
            <img src={previewSource} alt="coolest-ever" style={{height: '300px', width: '300px'}}/>
        )}
        </>
    )
}

MUTATION 响应发送


const ADD_IMAGE = gql`
    mutation($userID: ID!, $photo: String!){
        addImage(userID: $userID, photo: $photo){
            id 
        }
    }
`

变异解析器

 async addImage(_, { userID, photo }, context){  //photo is given as type: String!
            const user = checkAuth(context);

            if(!user) throw new AuthenticationError('Not Logged In')

            const imgUpload = await cloudinary.uploader.upload(photo)
            
            let userProfile = await User.findById(userID)
                
            if(user){

                await User.updateOne({_id: userID}),{
                    $set: {
                        photo: imgUpload.url
                    }
                }

                const newUserProfile = await User.findById(userID)

                return newUserProfile
            }else{
                throw new Error('Unknown Error')
            }
            
        }

需要什么

我想让它在用户上传图像时被推送到我的 Cloudinary 空间,并且来自 Cloudinary 的图像 URL 存储在我的 MongoDb 集合中,这样当我在我的程序中使用它们时,我可以放置 URL在一个简单的img src={user.photo} 中,它就会显示出来。

注意

这是我的第一个 React 项目,所以这是我想到的第一个想法,我相信也有更好的想法,如果有更好的方法,请回答!

【问题讨论】:

    标签: reactjs graphql apollo react-apollo cloudinary


    【解决方案1】:

    这是一个关于如何使用 React 上传的示例代码:

      formdata.append("file", file);
        formdata.append("cloud_name", "<cloud name>");
        formdata.append("upload_preset", "<upload preset>");
    
        let res = await fetch(
          "https://api.cloudinary.com/v1_1/shirly/auto/upload",
          {
            method: "post",
            mode: "cors",
            body: formdata
          }
        );
    
        let json = await res.json();
        console.log(JSON.stringify(json.secure_url));
      };
    
      render() {
        return (
          <div>
            <h3>Upload</h3>
            <input type="file" onChange={this.processFile} />
          </div>
        );
      }
    }
    ReactDOM.render(<Upload />, document.getElementById("container"));
    
    

    https://codesandbox.io/s/jq4wl1xjv?from-embed=&file=/src/index.js 请注意,您需要在正确的位置设置您的云名称和未签名的上传预设。

    作为旁注,您可能需要考虑使用upload widget 例如在 React 中:http://jsfiddle.net/RayStra/gevc4ktm/

    【讨论】:

      猜你喜欢
      • 2021-03-20
      • 2019-04-17
      • 2017-06-03
      • 2015-02-21
      • 2017-07-12
      • 2014-11-25
      • 2020-12-25
      • 2021-09-03
      • 2020-05-02
      相关资源
      最近更新 更多