我现在正在试用 Prisma 和 React Native。目前我正在尝试使用包 _apollo-upload-client (https://github.com/jaydenseric/apollo-upload-client)将图像上传到我的数据库。但这并不顺利。
ImagePicker
目前我可以从 Expo中选择一张图片。然后我试图用 Apollo Client 做我的突变:
await this.props.mutate({
variables: {
name,
description,
price,
image,
},
});
但我收到以下错误:
Network error: JSON Parse error: Unexpected identifier "POST"
- node_modules/apollo-client/bundle.umd.js:76:32 in ApolloError
- node_modules/apollo-client/bundle.umd.js:797:43 in error
我相信它来自这些代码行:
const image = new ReactNativeFile({
uri: imageUrl,
type: 'image/png',
name: 'i-am-a-name',
});
这与他们的示例几乎相同,https://github.com/jaydenseric/apollo-upload-client#react-native。
imageUrl
来自我的州。当我 console.logimage
我得到以下信息:
ReactNativeFile {
"name": "i-am-a-name",
"type": "image/png",
"uri": "file:///Users/martinnord/Library/Developer/CoreSimulator/Devices/4C297288-A876-4159-9CD7-41D75303D07F/data/Containers/Data/Application/8E899238-DE52-47BF-99E2-583717740E40/Library/Caches/ExponentExperienceData/%2540anonymous%252Fecommerce-app-e5eacce4-b22c-4ab9-9151-55cd82ba58bf/ImagePicker/771798A4-84F1-4130-AB37-9F382546AE47.png",
}
所以有些东西突然出现了。但我不能再进一步了,我希望我能从某人那里得到一些提示。
我也没有包含来自后端的任何代码,因为我相信问题出在前端。但是,如果有人想查看后端,我可以更新问题,或者您可以在这里查看:https ://github.com/Martinnord/Ecommerce-server/tree/image_uploads 。
非常感谢阅读!干杯。
更新
在有人询问服务器中的逻辑后,我决定在下面通过它:
产品.ts
// import shortid from 'shortid'
import { createWriteStream } from 'fs'
import { getUserId, Context } from '../../utils'
const storeUpload = async ({ stream, filename }): Promise<any> => {
// const path = `images/${shortid.generate()}`
const path = `images/test`
return new Promise((resolve, reject) =>
stream
.pipe(createWriteStream(path))
.on('finish', () => resolve({ path }))
.on('error', reject),
)
}
const processUpload = async upload => {
const { stream, filename, mimetype, encoding } = await upload
const { path } = await storeUpload({ stream, filename })
return path
}
export const product = {
async createProduct(parent, { name, description, price, image }, ctx: Context, info) {
// const userId = getUserId(ctx)
const userId = 1;
console.log(image);
const imageUrl = await processUpload(image);
console.log(imageUrl);
return ctx.db.mutation.createProduct(
{
data: {
name,
description,
price,
imageUrl,
seller: {
connect: { id: userId },
},
},
},
info
)
},
}