如何使用 React Native 上传图片?
How to upload image with react native?
我像这样用 React js 上传图片 :
const onSubmit = (e) => {
console.log(e.img);
form.append("file", e.img.originFileObj);
Axios.post("url", form, {
headers: {
Authorization: `bearer ${localStorage.getItem("token")}`,
},
})
};
e.img 的控制台日志是:
现在在本机反应中我使用包 react-native-image-crop-picker
.
在我设置图像文件后,它给出了一个 object 像这样:
{"cropRect": {"height": 960, "width": 960, "x": 0, "y": 160}, "height": 400, "mime": "image/jpeg", "modificationDate": "1636923018000", "path": "file:///storage/emulated/0/Android/data/com.myapp/files/Pictures/33fc6a3f-3673-4756-8343-6f6bcb3c1a7b.jpg", "size": 89454, "width": 400}
现在,当我尝试上传图片时,出现有关 img 文件的错误。
后端是 node js,我用 multer 处理图像文件是这样的:
const multer = require('multer');
const uuid = require('uuid');
const MIME_TYPE_MAP = {
'image/png': 'png',
'image/jpeg': 'jpeg',
'image/jpg': 'jpg'
};
const fileUpload = multer({
limits: 20000000000,
storage: multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'upload/img');
},
filename: (req, file, cb) => {
const ext = MIME_TYPE_MAP[file.mimetype];
cb(null, uuid.v4() + '.' + ext);
}
}),
fileFilter: (req, file, cb) => {
const isValid = !!MIME_TYPE_MAP[file.mimetype];
let error = isValid ? null : new Error('Invalid mime type!');
cb(error, isValid);
}
});
module.exports = fileUpload;
我如何post像在 React js 中那样在 React Native 中处理图像文件?
解决方案 1
像reactjs一样,在这里你可以像这样使用FormData并追加文件:
asycn function uploadImage() {
const formData = new FormData();
const imageData = {
uri: cropImageData.path, // file uri/path
name: 'MyImage.jpg', //file name
type: cropImageData.mime, //file type
}
formData.append("file", imageData);
await fetch(url, {
method: "POST",
headers: {
'Content-Type': 'multipart/form-data',
Authorization: token,
},
data: formData,
}).then((response), {
console.log(response)
}).catch((error) => console.log(response));
}
解决方案 2
或者您可以从数据发送 base64 字符串,(您可以从 crop-image picker 获取 base64)
asycn function uploadImage() {
await fetch(url, {
method: "POST",
headers: {
'Content-Type': 'application/json',
Authorization: token,
},
data: JSON.stringify({
file: imageBase64String,
}),
}).then((response), {
console.log(response)
}).catch((error) => console.log(response));
}
在这里你也可以使用 axios 而不是 fetch。
我这样解决了问题
ImagePicker.openPicker({
width: 400,
height: 400,
cropping: true,
includeBase64: true,
})
.then(image => {
setImg(image);
})
.then(() => setModalVisible(prev => !prev));
const nn = JSON.stringify(img.path).substring(
JSON.stringify(img.path).lastIndexOf('/') + 1,
);
const image = {
name: nn,
uri: img.path,
type: img.mime,
size: img.size,
lastModifiedDate: JSON.parse(img.modificationDate),
uid: img.modificationDate,
};
const form = new FormData();
form.append('file', image);
axios
.post('url', form, {
headers: {
Authorization: `bearer ${JSON.parse(token)}`,
},
})
我像这样用 React js 上传图片 :
const onSubmit = (e) => {
console.log(e.img);
form.append("file", e.img.originFileObj);
Axios.post("url", form, {
headers: {
Authorization: `bearer ${localStorage.getItem("token")}`,
},
})
};
e.img 的控制台日志是:
现在在本机反应中我使用包 react-native-image-crop-picker
.
在我设置图像文件后,它给出了一个 object 像这样:
{"cropRect": {"height": 960, "width": 960, "x": 0, "y": 160}, "height": 400, "mime": "image/jpeg", "modificationDate": "1636923018000", "path": "file:///storage/emulated/0/Android/data/com.myapp/files/Pictures/33fc6a3f-3673-4756-8343-6f6bcb3c1a7b.jpg", "size": 89454, "width": 400}
现在,当我尝试上传图片时,出现有关 img 文件的错误。
后端是 node js,我用 multer 处理图像文件是这样的:
const multer = require('multer');
const uuid = require('uuid');
const MIME_TYPE_MAP = {
'image/png': 'png',
'image/jpeg': 'jpeg',
'image/jpg': 'jpg'
};
const fileUpload = multer({
limits: 20000000000,
storage: multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'upload/img');
},
filename: (req, file, cb) => {
const ext = MIME_TYPE_MAP[file.mimetype];
cb(null, uuid.v4() + '.' + ext);
}
}),
fileFilter: (req, file, cb) => {
const isValid = !!MIME_TYPE_MAP[file.mimetype];
let error = isValid ? null : new Error('Invalid mime type!');
cb(error, isValid);
}
});
module.exports = fileUpload;
我如何post像在 React js 中那样在 React Native 中处理图像文件?
解决方案 1
像reactjs一样,在这里你可以像这样使用FormData并追加文件:
asycn function uploadImage() {
const formData = new FormData();
const imageData = {
uri: cropImageData.path, // file uri/path
name: 'MyImage.jpg', //file name
type: cropImageData.mime, //file type
}
formData.append("file", imageData);
await fetch(url, {
method: "POST",
headers: {
'Content-Type': 'multipart/form-data',
Authorization: token,
},
data: formData,
}).then((response), {
console.log(response)
}).catch((error) => console.log(response));
}
解决方案 2
或者您可以从数据发送 base64 字符串,(您可以从 crop-image picker 获取 base64)
asycn function uploadImage() {
await fetch(url, {
method: "POST",
headers: {
'Content-Type': 'application/json',
Authorization: token,
},
data: JSON.stringify({
file: imageBase64String,
}),
}).then((response), {
console.log(response)
}).catch((error) => console.log(response));
}
在这里你也可以使用 axios 而不是 fetch。
我这样解决了问题
ImagePicker.openPicker({
width: 400,
height: 400,
cropping: true,
includeBase64: true,
})
.then(image => {
setImg(image);
})
.then(() => setModalVisible(prev => !prev));
const nn = JSON.stringify(img.path).substring(
JSON.stringify(img.path).lastIndexOf('/') + 1,
);
const image = {
name: nn,
uri: img.path,
type: img.mime,
size: img.size,
lastModifiedDate: JSON.parse(img.modificationDate),
uid: img.modificationDate,
};
const form = new FormData();
form.append('file', image);
axios
.post('url', form, {
headers: {
Authorization: `bearer ${JSON.parse(token)}`,
},
})