Expo ImagePicker 没有在 ReactNative 中上传图片
Expo ImagePicker not uploading Image in ReactNative
我正在从 FileManager 中选择一个图像并得到一个结果,添加在下面以供参考。我将该数据传递给 nodejs,但以数组格式获取数据。我在 FormData 中传递带有数据的图像。我已成功将数据发送到 nodejs,但在将图像上传到目标文件夹时遇到问题。我是 React Native 的新手。谁能帮帮我呀
Logged Data on Image Seleting :
Object {
"cancelled": false,
"height": 960,
"type": "image",
"uri": "file:///data/user/0/host.exp.exponent/cache/ExperienceData/%2540anonymous%252FLevelNextClient-d47662dc-9f84-4299-a322-f00845340c43/ImagePicker/1f5613bd-72ee-4ba3-8b9b-1456fe05bfb3.jpg",
"width": 960,
}
Logged Data when getting in req.body :
[["name","Anujw5rc"],["email","anuj@edulab.ined"],["phone","333333"],["image",{"uri":"file:///data/user/0/host.exp.exponent/cache/ExperienceData/%2540anonymous%252FLevelNextClient-d47662dc-9f84-4299-a322-f00845340c43/ImagePicker/55c1a503-da15-47bb-adcb-2005cfc66b82.jpg","name":"UserProfile.jpg","type":"image/jpg"}]]
const handleUpdate = async ({ name, email, phone }) => {
const data = new FormData();
let str=image.replace('///','//')
data.append('name', name)
data.append('email', email)
data.append('phone', phone)
data.append('image',
{
uri:image,
name: "UserProfile.jpg",
type:'image/jpg'
});
const response = await axios.post(`${ConfigData.SERVER_URL}/auth/updateProfile`,
data,
);
if (response.status !== 200) throw Error('Something went wrong')
if (response.data.status === false) throw Error(response.data.message)
}
const pickImage = async () => {
// No permissions request is necessary for launching the image library
let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.All,
allowsEditing: true,
aspect: [3, 3],
quality: 1,
// base64: true,
});
console.log(result);
if (!result.cancelled) {
setImage(result.uri);
}
};
router.post("/updateProfile", fileUpload.array("file"), async (req, res) => {
console.log(JSON.stringify(req.body._parts));
console.log(req.file);
const user_id = req.body.id;
try {
const updateData=await userModel.findByIdAndUpdate(user_id,
{ name: req.body.name, email: req.body.email ,number: req.body.number,ProfileImageDestination : req.body.image},
);
res.status(200).json({ status: true ,updateData});
} catch (e) {
console.log(e);
res.status(500).json({ status: false, message: "Something Went Wrong" });
}
});
在react native部分,你不需要使用
替换image uri
let str=image.replace('///','//')
在 handleUpdate 方法中。可以直接传入Formdata给后台API like
data.append('file',
{
uri:image,
name: "UserProfile.jpg",
type:'image/jpg'
});
其中 image 是您的状态变量,它存储了 Picked 图像的 image.uri。
然后,在后端 API 你可能有两种选择,要么是 busboy 要么是 multer 用于文件上传。
使用服务生,
var Busboy = require('busboy'),
path = require('path'),
fs = require('fs');
router.post("/updateProfile", async (req, res) => {
var busboy = new Busboy({ headers: req.headers });
var saveLocation = '';
busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
saveLocation = path.join(__dirname, 'uploads/' + filename);
file.pipe(fs.createWriteStream(saveTo));
});
busboy.on('finish', function() {
(async ()=>{
const user_id = req.body.id;
try {
const updateData=await userModel.findByIdAndUpdate(user_id,
{ name: req.body.name, email: req.body.email ,number: req.body.number,ProfileImageDestination : req.body.image},
);
res.writeHead(200, { 'Connection': 'close' });
res.end({ status: true ,updateData});
} catch (e) {
console.log(e);
res.writeHead(200, { 'Connection': 'close' });
res.end({ status: false, message: "Something Went Wrong" });
}
})()
});
return req.pipe(busboy);
});
以上代码仅用于演示目的,您可以在库 https://www.npmjs.com/package/busboy.
上找到更多使用 busboy 的详细信息
另一种选择是 multer,您可以探索将文件上传到服务器端的特定目录或位置。
我正在从 FileManager 中选择一个图像并得到一个结果,添加在下面以供参考。我将该数据传递给 nodejs,但以数组格式获取数据。我在 FormData 中传递带有数据的图像。我已成功将数据发送到 nodejs,但在将图像上传到目标文件夹时遇到问题。我是 React Native 的新手。谁能帮帮我呀
Logged Data on Image Seleting :
Object {
"cancelled": false,
"height": 960,
"type": "image",
"uri": "file:///data/user/0/host.exp.exponent/cache/ExperienceData/%2540anonymous%252FLevelNextClient-d47662dc-9f84-4299-a322-f00845340c43/ImagePicker/1f5613bd-72ee-4ba3-8b9b-1456fe05bfb3.jpg",
"width": 960,
}
Logged Data when getting in req.body :
[["name","Anujw5rc"],["email","anuj@edulab.ined"],["phone","333333"],["image",{"uri":"file:///data/user/0/host.exp.exponent/cache/ExperienceData/%2540anonymous%252FLevelNextClient-d47662dc-9f84-4299-a322-f00845340c43/ImagePicker/55c1a503-da15-47bb-adcb-2005cfc66b82.jpg","name":"UserProfile.jpg","type":"image/jpg"}]]
const handleUpdate = async ({ name, email, phone }) => {
const data = new FormData();
let str=image.replace('///','//')
data.append('name', name)
data.append('email', email)
data.append('phone', phone)
data.append('image',
{
uri:image,
name: "UserProfile.jpg",
type:'image/jpg'
});
const response = await axios.post(`${ConfigData.SERVER_URL}/auth/updateProfile`,
data,
);
if (response.status !== 200) throw Error('Something went wrong')
if (response.data.status === false) throw Error(response.data.message)
}
const pickImage = async () => {
// No permissions request is necessary for launching the image library
let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.All,
allowsEditing: true,
aspect: [3, 3],
quality: 1,
// base64: true,
});
console.log(result);
if (!result.cancelled) {
setImage(result.uri);
}
};
router.post("/updateProfile", fileUpload.array("file"), async (req, res) => {
console.log(JSON.stringify(req.body._parts));
console.log(req.file);
const user_id = req.body.id;
try {
const updateData=await userModel.findByIdAndUpdate(user_id,
{ name: req.body.name, email: req.body.email ,number: req.body.number,ProfileImageDestination : req.body.image},
);
res.status(200).json({ status: true ,updateData});
} catch (e) {
console.log(e);
res.status(500).json({ status: false, message: "Something Went Wrong" });
}
});
在react native部分,你不需要使用
替换image urilet str=image.replace('///','//')
在 handleUpdate 方法中。可以直接传入Formdata给后台API like
data.append('file',
{
uri:image,
name: "UserProfile.jpg",
type:'image/jpg'
});
其中 image 是您的状态变量,它存储了 Picked 图像的 image.uri。
然后,在后端 API 你可能有两种选择,要么是 busboy 要么是 multer 用于文件上传。
使用服务生,
var Busboy = require('busboy'),
path = require('path'),
fs = require('fs');
router.post("/updateProfile", async (req, res) => {
var busboy = new Busboy({ headers: req.headers });
var saveLocation = '';
busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
saveLocation = path.join(__dirname, 'uploads/' + filename);
file.pipe(fs.createWriteStream(saveTo));
});
busboy.on('finish', function() {
(async ()=>{
const user_id = req.body.id;
try {
const updateData=await userModel.findByIdAndUpdate(user_id,
{ name: req.body.name, email: req.body.email ,number: req.body.number,ProfileImageDestination : req.body.image},
);
res.writeHead(200, { 'Connection': 'close' });
res.end({ status: true ,updateData});
} catch (e) {
console.log(e);
res.writeHead(200, { 'Connection': 'close' });
res.end({ status: false, message: "Something Went Wrong" });
}
})()
});
return req.pipe(busboy);
});
以上代码仅用于演示目的,您可以在库 https://www.npmjs.com/package/busboy.
上找到更多使用 busboy 的详细信息
另一种选择是 multer,您可以探索将文件上传到服务器端的特定目录或位置。