Unable to upload file on a folder on REACT, Express, multer, node.js

122
April 04, 2021, at 1:30 PM

I'm new to react native. I'm unable to upload a photo on my a folder. though node-mon and react-native server doesn't show any error. but still unable to get a response from the database. i want to upload the photo on to the folder, and save rest of the information to my postgres data base.

Front end code

const choosePhotoFromLibrary = () => {
    ImagePicker.openPicker({
    width: 300,
    height: 400,
    cropping: true
    }).then(image => {
    console.log(image.path);
    setImage(image.path);
  });
  }

Function to call 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)
      }
  }

backend 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)
    }    
});
Answer 1

I don't know react, but i do familiar with using https://www.npmjs.com/package/multer. When you upload a file, you need to sent it using multipart/form-data cause multer will not process any form which is not multipart.

edit : Some sample code

Back end

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 });

Front end

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);       
 }
READ ALSO
how to add data attribute to a specific <li> element in wordpress nav menu

how to add data attribute to a specific <li> element in wordpress nav menu

I'm using wordpress and trying to add a data-attribute to just 1 main menu itemSpecifically to a < li> element

114
BeautifulSoup4: Fail to find &#39;a&#39; tag with specific href value by find()

BeautifulSoup4: Fail to find 'a' tag with specific href value by find()

I am trying to crawl the realtime Bitcoin-HKD Currency from https://wwwcoinbase

51
ValueError: could not broadcast input array from shape (16,7,7,512) into shape (7,7,512)

ValueError: could not broadcast input array from shape (16,7,7,512) into shape (7,7,512)

I am building a neural network using videos as the data and I'm getting the error ValueError: could not broadcast input array from shape (7,7,3) into shape (7,7,512) when I run start training the modelI have tried different ways by changing the "X"...

148
How can I fetch and fill the resulting presigned URL for each member of each array nested two objects deep?

How can I fetch and fill the resulting presigned URL for each member of each array nested two objects deep?

really needing some help here because I am completely failing to figure this out with many hours of tryingI'm hoping I can draw on the power of stackoverflow to help me out

106