我正在尝试使用apollo graphQL上传文件。使用Upload
标量和GraphQLUpload
,当前客户端失败
类型
export const typeDefs = gql`
scalar Upload
type File {
url: String!
}
突变和解析器
export const resolvers = {
Upload: GraphQLUpload
uploadFile(file: Upload!): File!
uploadFile: async (_, { file }) => {
const { createReadStream, filename } = await file;
const stream = createReadStream();
const { ext } = path.parse(filename)
const name = ext + v4()
const pathName = path.join(__dirname, `../public/images/${name}`)
await stream.pipe(fs.createWriteStream(pathName))
return {
url: `http://localhost:5000/images/${name}`
};
},
客户端
export const UPLOAD_FILE = gql`
mutation UploadFile($file: Upload!){
uploadFile(file: $file){
url
}
}
`
const handleUpload = async () => {
if (!image) return;
try {
const { data } = await uploadFile({
variables: { file: image }
})
if (data) {
console.log('res =>', data)
handleCreateNewPost(data.uploadFile.url)
}
}
catch (err) {
console.log(err)
}
当前我得到一个无效的输入错误:
{"errors":[{"message":"Variable \"$file\" got invalid value { path: \"Photo on 2021-09-07 at 1.34 PM.jpg\" }
image
console.logged显示文件对象
File {path: 'Photo on 2021-09-07 at 1.34 PM.jpg', name: 'Photo on 2021-09-07 at 1.34 PM.jpg', lastModified: 1631036079471, lastModifiedDate: Tue Sep 07 2021 13:34:39 GMT-0400 (Eastern Daylight Time), webkitRelativePath: '', …}
path: "Photo on 2021-09-07 at 1.34 PM.jpg"
lastModified: 1631036079471
lastModifiedDate: Tue Sep 07 2021 13:34:39 GMT-0400 (Eastern Daylight Time) {}
name: "Photo on 2021-09-07 at 1.34 PM.jpg"
size: 134828
type: "image/jpeg"
webkitRelativePath: ""
[[Prototype]]: File
1条答案
按热度按时间gijlo24d1#
遇到了同样的问题。
问题出在我们的apollo客户端的前端,我们没有在客户端中包含上传链接。
还要注意,根据documentation,只能有一个这样的终止链路
因此,如果您的客户端中有这两个链接,您仍然会得到相同的错误。