如何解决在React Native应用中由相机拍摄的上传图像时出现错误“请求失败,状态代码为413”
我使用“ React-native-image-picker”将图像上传到服务器:
{
name: '2010',data: [{
name: 'Republican',y: 5,drilldown: 'republican-2010'
},{
name: 'Democrats',y: 2,drilldown: 'democrats-2010'
},{
name: 'Other',y: 4,drilldown: 'other-2010'
}]
},{
name: '2014',drilldown: 'republican-2014'
},drilldown: 'democrats-2014'
},drilldown: 'other-2014'
}]
}
当我从下载库中选择图像时,一切都很好,服务器将响应发送给uri。但是,当我从相机图库中选择图像或用手机的相机拍照并上传时, const options = {
title: 'Chọn ảnh đại diện ',takePhotoButtonTitle: 'Chụp ảnh',chooseFromLibraryButtonTitle: 'Chọn từ thư viện',cancelButtonTitle: 'Thoát',noData: true
};
ImagePicker.showImagePicker(options,(response) => {
if (response.didCancel) {
console.log('User cancelled image picker');
} else if (response.error) {
console.log('ImagePicker Error: ',response.error);
} else if (response.customButton) {
console.log('User tapped custom button: ',response.customButton);
} else {
var FormData = require('form-data');
const data = new FormData();
data.append('file',{
uri: `file://${response.path}`,type: response.type,name: response.fileName
});
Axios.post('https://api.hoc68.com/api/v1/upload_files',data,{
headers: {
'Authorization': `Bearer ${stateTree.user.token_key}`,'Content-type': 'multipart/form-data',}
}).then(res => console.log(res.data)).catch(e => console.log(JSON.stringify(e)))
console.log(response.path + ' ' + response.uri + ' ' + response.type);
}
});
会捕获此错误。当我在Google中搜索此错误时,它表示当我的文件太大时会发生这种情况。有人可以在前端代码或服务器代码中告诉我需要解决的问题吗?
解决方法
413错误代码表示您尝试上传的图片太大(如此处所述) 413 Error Code details
因此,要避免此一种选择,请先压缩图像,然后再将其上传到服务器,您可以使用名为ImageResizer的软件包
这是一个代码示例,如何将其与axios一起使用:
ImageResizer.createResizedImage(uri,height,width,"JPEG",60,0).then(
(response) => {
let cleanUri =
Platform.OS === "ios"
? response.uri.replace("file:/","")
: response.uri;
data.append("image",{
uri: cleanUri,name: "userImage.jpeg",type: "image/jpeg",});
axios
.post(PROFILE_PHOTOS_UPLOAD,data,config)
.then((response) => {
if (response.data.success === true) {
if (key === PROFILE_IMAGE) {
image = response.data.data.image;
} else if (key === COVER_IMAGE) {
image = response.data.data.cover_image;
}
dispatch({
type: inAppActionTypes.CHANGE_PROFILE_IMAGE,key: key,url: image,});
} else {
//bad response
}
})
.catch((err) => {
// Oops,something went wrong. Check that the filename is correct and
console.log("error while compressing the image");
console.log(err);
});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。