当前位置: 首页 > 知识库问答 >
问题:

用React和Apollo(GraphQL)上传图像到Cloudinary

林亦
2023-03-14
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'}}/>
        )}
        </>
    )
}

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')
            }
            
        }

共有1个答案

韦寒
2023-03-14

下面是如何使用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请注意,您需要在正确的位置设置云名称和未签名上传预置。

另请注意,您可能需要考虑使用上传小部件,例如在React中:http://jsfiddle.net/raystra/gevc4ktm/

 类似资料:
  • 我已经为KeystoneJS的AdminUI编写了一个自定义字段,它使用了TinyMCE的编辑器。 KeystoneJS在下面运行Apollo GraphQL服务器,并根据CMS模式自动生成变化和查询。TinyMCE具有输入自定义挂钩以上载图像的功能。 我希望能够连接这两个——使用GraphQL将图像从TinyMCE上传到KeystoneJS的服务器。 例如,在我的设置中,我在CMS中有一个字段。

  • 我按照Apollo的文档在客户端和服务器上设置GraphQL订阅,虽然我已经完成了90%,但我不知道如何设置订阅通道以及如何将突变连接到这些通道,以便每当突变发生时,服务器都会将新数据推送到客户端。(对于内容,我正在制作一个Reddit克隆,人们可以在其中发布主题,其他人可以对其发表评论。所以当你看到“Topics”或“TopicList”时,把它们想象成帖子。) 到目前为止,我已经成功地为订阅设

  • A React + Apollo + GraphQL GitHub Client Features React 16 with create-react-app Responsive React Router 4 Apollo with GitHub GraphQL API Queries and Mutations with render props Optimistic Updates Pag

  • High performance Next + React + GraphQL starter kit The purpose of this starter kit is not to be complete solution, but introduction for creating high performance websites with Next.js, React and Grap

  • github-react-native-apollo-graphql Alpha version coming soon �� This project is under development...

  • 问题内容: 我正在上传base64字符串,但GraphQL挂起了。如果我将字符串切成少于50,000个字符,它将起作用。50,000个字符后,graphQL永远不会进入解析函数,但不会给出错误。在较小的字符串上,它可以正常工作。 问题答案: 此处的正确方法是使用AWS AppSync通过复杂类型执行实际的S3上传- 您在此处说明的内容看起来更像是您尝试将base64编码的图像作为字符串保存到字段中