【发布时间】: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