【发布时间】:2021-04-03 01:02:52
【问题描述】:
我是原生反应的新手。我无法在我的文件夹中上传照片。虽然 node-mon 和 react-native 服务器没有显示任何错误。但仍然无法从数据库中获得响应。我想将照片上传到文件夹中,并将其余信息保存到我的 postgres 数据库中。
前端代码
const choosePhotoFromLibrary = () => {
ImagePicker.openPicker({
width: 300,
height: 400,
cropping: true
}).then(image => {
console.log(image.path);
setImage(image.path);
});
}
调用 API 的函数
const submit = async () => {
let FirstName = '';
let LastName = '';
let Age = '';
let Gender = '';
let Town = '';
let Area = '';
let Last_Time = '';
let Image_path = image;
let Description = Appearance;
FirstName = await AsyncStorage.getItem('FirstName') || 'none';
LastName = await AsyncStorage.getItem('LastName') || 'none';
Age = await AsyncStorage.getItem('Age') || 'none';
Gender = await AsyncStorage.getItem('Gender') || 'none';
Town = await AsyncStorage.getItem('Town') || 'none';
Area = await AsyncStorage.getItem('Area') || 'none';
Last_Time = await AsyncStorage.getItem('Last_Time') || 'none';
console.log(FirstName,LastName,Age,Gender,Town,Area,Last_Time,Description, Image_path);
url = 'http://192.168.1.104:3005/api/Users/AddReport/5';
try {
await fetch(url,Image_path{
method: 'post',
headers: {
'Content-Type' : 'application/json',
},
body: JSON.stringify({
user_id : 5,
firstname : FirstName,
lastname : LastName,
age : Age,
sex : Gender,
town : Town,
area : Area,
last_seen_time : Last_Time,
last_seen_appearance : Description,
image_path : Image_path,
})
});
/*await AsyncStorage.removeItem('FirstName');
await AsyncStorage.removeItem('LastName');
await AsyncStorage.removeItem('Age');
await AsyncStorage.removeItem('Gender');
await AsyncStorage.removeItem('Town');
await AsyncStorage.removeItem('Area');
await AsyncStorage.removeItem('Last_Time');*/
} catch(e) {
console.log(e)
}
}
后端 API
const storage = multer.diskStorage({
destination: './reports/images',
filename: (req, file, cb) => {
return cb(null, `${file.fieldname}_${Date.now()}${path.extname(file.originalname)}`)
}
})
const upload = multer({
storage: storage,
})
//Add Report
app.post("/api/Users/AddReport/:user_id", upload.single('report_image'),async(req, res) => {
console.log(req.file);
try {
const results = await db.query("INSERT INTO REPORT (user_id,firstname,lastname,age,sex,town,area,last_seen_time,last_seen_appearance,image_path) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)",
[req.params.user_id,req.body.firstname,req.body.lastname,req.body.age,req.body.sex,req.body.town,req.body.area,req.body.last_seen_time,req.body.last_seen_appearance,req.file.path]);
console.log(results);
res.status(201).json({
status: "success",
data: {
name: ["Fahad"],
email: ["fahad@gmail.com"],
password: ["1111"],
},
});
}catch (err) {
console.log(err)
}
});
【问题讨论】:
标签: node.js postgresql react-native express multer