我正在使用React Native,我正在尝试将图像上传到strapi并将其连接到Entry。当用户完成那里的个人资料时,我还希望他们上传那里的个人资料图片。但是当我上传图片时,它上传到我的服务器存储,但它没有连接到我想要的用户条目。
我哪里做得不对?
async function uploadImage(imgUri: string, jwt: string, refId: string, ref: string, source: string, field: string) {
try {
const uploading = await
FileSystem.uploadAsync(
`https://myurl.cloud/api/upload/?refId=${refId}&ref=${ref}&source=${source}&field=${field}`,
`${imgUri}`,
{
headers: {
'Authorization': `Bearer ${jwt}`
},
uploadType: FileSystem.FileSystemUploadType.MULTIPART,
fieldName: "files",
});
return uploading
} catch (error) {
console.log(JSON.stringify(error, null,2))
return null
}
}
我建议您使用自定义 Strapi 路由/控制器来执行此操作。
您可以通过多部分数据的自定义路线发送图片:
// Front-end - Send the Profile Picture to the backend
const addProfileInfo = async ({ profilePictureUri }) => {
let data = new FormData();
const url = 'https://myurl.cloud';
data.append('profilePicture', {
uri: profilePictureUri,
name: 'user-pp.jpeg',
type: 'image/jpeg',
});
// Do request
const response = await fetch(url + '/api/profile', { // Assuming you will create a route for `/api/profile` for example
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data',
Authorization: `Bearer ${token}`, // Don't forget to add the user JWT token
},
body: data,
});
const body = await response.json();
return [response, body];
}
在控制器中,您现在可以使用上传服务来保存图像。
// Backend - Strapi Controller for POST '/api/profile' route
// Here you recover the picture sent in the request under the name 'profilePicture'
const picture = ctx.request.files.profilePicture;
if (!picture) {
return ctx.badRequest('Profile picture needed');
}
await strapi.plugin("upload").services.upload.upload({
data: {
ref: 'plugin::users-permissions',
refId: ctx.state.user.id,
field: 'profilePicture', // Here is the image field name created in Strapi to link the image to.
source: 'users-permissions',
fileInfo: {
caption: undefined,
alternativeText: undefined,
name: 'profilePictureImg',
folder: 1, // Folder ID 1 is the root Media library folder, but you can customize where the file can be stored in the Strapi media library by giving its id. Notice that it is a virtual folder, Strapi Media library only
},
},
files: {
path: picture.path,
name: picture.name,
type: picture.type,
size: picture.size,
},
});
正如我所说,您可以自定义文件在 Strapi 媒体库中所在的文件夹,但这是另一个主题,所以我没有开发它。
你也可以通过这个路由发送更多的数据来注册更多的用户信息,但这也是另一个话题了。请参阅
Send multipart data form Strapi
了解更多信息。
希望这有帮助!