在 React Native 应用程序中上传相机拍摄的图像时"Request failed with status code 413"错误



我使用"React native image picker"将图像上传到我的服务器:

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);
}
});

当我从下载库中选择图像时,一切都很好,服务器会用uri发回响应。但是,当我从相机库中选择图像时,或者当我用手机的相机拍照并上传时,Axios会捕捉到这个错误。当我在谷歌上搜索这个错误时,它说当我的文件太大时会发生这种情况。有人能告诉我需要解决的问题在哪里吗,在我的前端代码或服务器代码中?

413错误代码表明您试图上传的图像太大413错误代码详细信息

因此,为了避免这种情况,一个选项是在上传到服务器之前压缩图像,你可以使用名为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);

});

相关内容

最新更新