我想将本机中的图像文件上传到服务器,该怎么办? 这是我的代码:
在我的index.js
(这是我的切入点)中,我设置了axios默认配置:
axios.defaults.baseURL = BaseUrl;
axios.defaults.headers.common['Content-Type'] = 'application/json';
axios.defaults.headers.common['Accept'] = 'application/json';
现在在我的profileEdit.js
中,我需要在其中上传个人资料图片
let data = new FormData();
data.append('profile_picture',
{uri: imageResponse.uri, name: imageResponse.fileName, type: 'image/jpg'});
// imageResponse is a response object that I m getting from React native ImagePicker
axios.post('profile/picture/', data,
{
headers: {
"Authorization": "JWT " + this.state.token,
'content-type': 'multipart/form-data',
}
}).then(response => {
console.log('Profile picture uploaded successfully', response);
}).catch(error => {
console.log('Failed to upload profile image', error);
console.log('Error response',error.response);
});
但是这给了我网络错误,而其他API却可以正常工作。
我按照此处给出的解决方法How to upload image to server using axios in react native?
这是我得到的错误响应。
我不想使用任何其他软件包,例如react native fetch blob
我关注的更多链接:
任何人都可以告诉我我在哪里做错了,或者我该如何解决这个问题。 ty
答案 0 :(得分:2)
我认为您的Axios POST请求标头可能不正确,因为您使用的是FormData()
构造函数来存储图像数据:
您可能想尝试以下方法:
let data = new FormData();
data.append('profile_picture',{
uri: imageResponse.uri,
name: imageResponse.fileName,
type: 'image/jpg'}
);
axios.post('profile/picture/', data,
{
headers: {
'content-type': `multipart/form-data; boundary=${data._boundary}`,
...data.getHeaders()
}
}
)
答案 1 :(得分:0)
对我来说只是工作
const oFormData = new FormData();
oFormData.append("image", {
uri: images.uri,
type: images.type,
name: images.fileName
});
axios.post(servicesUrl.imageupload, oFormData);