【问题标题】:Unable to upload file on a folder on REACT, Express, multer, node.js无法在 REACT、Express、multer、node.js 上的文件夹上上传文件
【发布时间】: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


    【解决方案1】:

    我不知道反应,但我熟悉使用https://www.npmjs.com/package/multer。 当您上传文件时,您需要使用multipart/form-data 发送它,因为multer 不会处理任何非多部分的表单。

    编辑: 一些示例代码

    后端

    const storageLocal = multer.diskStorage({
      destination(req, file, cb) {
        cb(null, './src/uploads');
      },
      filename(req, file, cb) {
        cb(null, `${Date.now().toString()}_${file.originalname}`);
        
      }
    });
    const uploadLocal = multer({ storage: storageLocal });
    

    前端

    function inputDashboard(e){
         e.preventDefault();
         var formData = new FormData();
         var xhr = new XMLHttpRequest();
     
         let storage= e.target.storage.value;
         let file = e.target.file.files[0];
     
         formData.append('file', file);
         xhr.open('POST', `${uriApi}/${storage}`);
         xhr.onload = function(){
              var result = JSON.parse(xhr.responseText);
              if(xhr.readyState==4&&xhr.status=='200'){
                   alert('Done Update');
                   location.replace(uriDash);
              }
              else{
                   alert('Something is wrong');
              }
         };
         xhr.send(formData);       
     }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-01
      • 2022-08-19
      • 2016-03-06
      • 2017-02-10
      相关资源
      最近更新 更多