[英]How to upload images to MongoDB in MERN stack using react native?
我正在制作一個應用程序,在我的應用程序中,我試圖允許用戶將圖像上傳到數據庫。 對於這個應用程序,我使用的是 MERN(使用本機反應,而不是反應)。 我有一條將圖像上傳到數據庫的路線,以及調用該路線的 redux 操作。 下面我已經包含了我的兩個代碼。 我想知道如何在動作中調用路由,然后將圖像數據傳遞到路由中? 任何幫助或方向將不勝感激。 謝謝!
Redux 動作:
// Add Images to profile
export const addImages = (userImages) => async dispatch => {
let formData = new FormData();
formData.append("userImages", userImages);
//console.log(userImages);
//const body = userImages;
try {
const res = await axios.post('http://localhost:5000/api/users/images', formData);
dispatch({
type: ADD_IMAGES,
payload: res.data
});
//dispatch(loadUser());
//dispatch(NavigationActions.navigate({ routeName: 'CreateProfile' }));
} catch (err) {
//console.log('this is the error you are looking for', err);
const errors = err.response.data.errors;
if (errors) {
errors.forEach(error => dispatch(setAlert(error.msg, 'danger')));
}
dispatch({
type: PROFILE_ERROR,
payload: res.data
});
}
}
添加圖片路線:
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './uploads/');
},
filename: function (req, file, cb) {
cb(null, Date.now() + file.originalname);
}
});
//const upload = multer({ storage: storage, });
const fileFilter = (req, file, cb) => {
// reject a file
if (file.mimetype === 'image/jpeg' || file.mimetype === 'image/png') {
cb(null, true);
} else {
cb(null, false);
}
};
const upload = multer({
storage: storage, limits: {
fileSize: 1024 * 1024 * 5
},
fileFilter: fileFilter
});
//@route POST api/users/images
//@desc Store user images
//@access Private
router.post("/images", auth, upload.array('userImages', 5),
async (req, res) => {
//console.log(req.files);
const files = req.files;
//console.log(files);
if (!files) {
return res.status(400).json({ errors: [{ msg: 'Please add photos' }] });
}
console.log("here");
try {
console.log("files: " + files);
let desiredUser = await User.findById(req.user.id);
if (desiredUser) {
//desiredUser.bio = bio;
for (let i = 0; i < 5; i++) {
console.log("files[i]: " + files[i])
//console.log(files[i].filename.toString());
desiredUser.userImages.push(files[i].filename.toString());
}
//desiredUser.userImage = files
await desiredUser.save();
return res.json(desiredUser);
} else {
return res.status(400).json({ errors: [{ msg: 'Please add photo' }] });
}
} catch (err) {
console.error(err.message);
return res.status(500).send('Server error');
}
});
首先使用它們的 API 將圖像上傳到 AWS S3 或 Firebase 存儲等存儲服務。 一旦 API 將上傳圖像的 URL 返回給您,您就可以在 Z6805A5F7CC703B4FC 文檔中更新 URL66E
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.