【问题标题】:How to upload images to MongoDB in MERN stack using react native?如何使用本机反应将图像上传到 MERN 堆栈中的 MongoDB?
【发布时间】:2021-05-24 05:36:15
【问题描述】:

我正在制作一个应用程序,并且在我的应用程序中我试图允许用户将图像上传到数据库。对于这个应用程序,我使用的是 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');
    }
  });

【问题讨论】:

    标签: node.js reactjs image react-native multer


    【解决方案1】:

    首先使用 API 将图像上传到 AWS S3 或 Firebase 存储等存储服务。一旦 API 返回上传图片的 URL,您就可以在 mongodb 文档中更新该 URL。

    【讨论】:

      猜你喜欢
      • 2021-10-10
      • 2020-11-06
      • 2022-12-14
      • 2022-11-25
      • 1970-01-01
      • 2021-02-24
      • 1970-01-01
      • 2021-12-26
      • 2022-07-18
      相关资源
      最近更新 更多