1

I am not receiving data on the server side. Sometimes I get data as an object. I have tried different ways but the image upload gets failed. Below is my code. I have tried different method but the result was the same image folder remain empty as am using multer middleware

Image is getting displayed using this snippet

<TouchableHighlight
  style={[
    styles.profileImgContainer,
    { borderColor: "#4632a1", borderWidth: 1 },
  ]}
  onPress={openImagePickerAsync}
>
  <Image source={{ uri: selectedImage.localUri }} style={styles.thumbnail} />
</TouchableHighlight>

This is the Image Picker Section

function PickImage() {
  let [selectedImage, setSelectedImage] = useState("");
  let openImagePickerAsync = async () => {
    let permissionResult =
      await ImagePicker.requestMediaLibraryPermissionsAsync();

    if (permissionResult.granted === false) {
      alert("Permission to access camera roll is required!");
      return;
    }

    let pickerResult = await ImagePicker.launchImageLibraryAsync();
    if (pickerResult.cancelled === true) {
      return;
    }

    setSelectedImage({ localUri: pickerResult.uri });
  };
}

Fetch API Call

async function upload() {
  const data = new FormData();
  data.append("image", {
    uri: selectedImage.uri,
    name: selectedImage.title,
    type: selectedImage.type,
  });

  const setting = {
    method: "POST",
    headers: {
      "Content-Type": "multipart/form-data;",
    },
    body: data,
  };
  try {
    const fetchResponse = await fetch(url, setting);
    const data = await fetchResponse.json();
    alert(data);
  } catch (e) {
    alert(e);
  }
}

Server-Side Code

app.post("/users", upload.single("image"), async (req, res) => {
  console.log(req.body.file);
  console.log(req.body);
  const img = req.body.image;
  if (!img) {
    console.log("no image");
  }

  res.send({ congrats: "data recieved" });
});

3 Answers 3

2

First of all, ImagePicker does not return the title and mimeType. Change the state updating logic to this

setSelectedImage({
  uri: result.uri,
  name: 'SomeImageName.jpg',
  type: 'image/jpg',
});

also change your uploading function to this, (My favorite way to write POST requests)

async function upload() {
  try {
    const data = new FormData();
    data.append("image", selectedImage);

    await fetch(URL_Endpoint, {
      method: "POST",
      body: data,
    });
  } catch (error) {
    console.log(error);
  }
}

Secondly, on the server-side, use it like this

You can manage files in two ways

1.) Disk Storage

Define multer configs like this

const express = require("express");
const app = express();
const multer = require("multer");

const storage = multer.diskStorage({
  destination: "./uploads/",
  filename: function (req, file, cb) {
    cb(null,  "SomeImage" + "." + file.originalname.split(".").pop());
  },
});

const diskStorage = multer({ storage: storage });

and then,

app.post("/users", diskStorage.single("image"), async (req, res) => {
  try {
    console.log(req.file); // File which is uploaded in /uploads folder.
    console.log(req.body); // Body
    res.send({ congrats: "data recieved" });
  } catch (error) {
    res.status(500).send("Error");
  }
});

2.) Memory Storage

Define multer configs like this

const express = require("express");
const app = express();
const fs = require("fs");
const multer = require("multer");

const memoryStorage = multer({
  storage: multer.memoryStorage(),
});

and then,

app.post("/users", memoryStorage.single("image"), async (req, res) => {
  try {
    console.log(req.file);
    console.log(req.body);

    // Here you will have to save it manually

    const DirName = `./uploads`;
    let URL = `./uploads/SomeImage.` + req.file.originalname.split(".").pop();

    fs.mkdir(DirName, { recursive: true }, async (err) => {
      if (err) {
        return res.status(500).send("Some Error");
      } else {
        fs.writeFile(URL, req.file.buffer, "ascii", function (err) {
          if (err) {
            return res.status(500).send("Some Error");
          } else {
            res.send({ congrats: "data recieved" });
          }
        });
      }
    });
  } catch (error) {
    res.status(500).send("Error");
  }
});
Sign up to request clarification or add additional context in comments.

1 Comment

am receiving object and not able destructor it
0

I have tried different methods to send my file through fetch and axios API but multer wasnt able to find my image uri as it accept file so instead of going into that stuff you can simply stringfy your uri of image and send it to your nodejs server

axios Api

const formData=new FormData()
  var imageJSON = {
    imageName:new Date().getTime()+"_profile",
    avatar:selectedImage,
    name:name,
    email:email,
    SocietyCode:sCOde,
    password:Password
  }

  formData.append('image', JSON.stringify(imageJSON))

  axios.post('http://localhost:3000/users',formData,{
    headers:{
      Accept: 'application/json',
      'Content-Type':'multipart/form-data'
    }
  }).then((responseData) => {
    console.log("before",responseData.data)
      
    })
    .catch((error) => {
      alert(error)
      console.log("ERROR " + error.message)
    });

Node ServerSide Code

router.post('/users', upload.single('avatar'), async (req,res)=>{
      
        formData =await req.body;
        var userJSON =await JSON.parse(formData.image);
    
  const avatar =await Buffer.from(userJSON.avatar, "utf-8");

  delete userJSON.avatar
userJSON.avatar=avatar
console.log(userJSON)


 const user= new Users(userJSON)
        try{

          
            await user.save()
            res.send({'message':'Registeration Successfull'})

        }
        catch(e){
            res.send({'response':'registeration failed'})
            console.log(e)
        }
          
      })

Comments

-1

Copy pasting my code from this answer incase anyone needs it for future reference:

App.js

import { useState } from "react";
import { Button, Image, ScrollView, View } from "react-native";
import { launchImageLibrary } from 'react-native-image-picker';
import RNFetchBlob from "rn-fetch-blob";


async function add_images(setImages) {

  const images = await launchImageLibrary({ mediaType: 'photo', selectionLimit: 0 });

  if (images.didCancel)
    return

  setImages(val => {
    let copy_val = [...val]

    images.assets.forEach((item) => {
      copy_val.push({ uri: item.uri, filename: item.fileName })
    })

    return copy_val
  });

}

async function upload_images(images) {

  let data = []
  images.forEach((item, index) => {
    data.push({ name: 'images_data', filename: item.filename, data: RNFetchBlob.wrap(item.uri) })
  })

  // you may have to use another route instead of localhost
  RNFetchBlob.fetch('POST', 'localhost:3000/upload_images', { 'Content-Type': 'multipart/form-data' }, data);
}

export default function App() {

  const [images, setImages] = useState([]) // array of URIs
  
  return (<>

    <View style={{ flexDirection: 'row', justifyContent: 'space-evenly', marginVertical: 50 }}>
      <Button title="Add Images" onPress={() => { add_images(setImages) }} />
      <Button title="Clear Images" onPress={() => { setImages([]) }} />
      <Button title="Upload Images" onPress={() => { upload_images(images) }} />
    </View>

    <ScrollView horizontal={true}>
      {
        images.map((item, index) => {
          return (<Image key={index} style={{ height: 400, width: 400 }} source={{ uri: item.uri }} />)
        })
      }
    </ScrollView>

  </>)
}

node.js

// import fs from 'fs';
import multer from "multer";
import express from 'express';
const server = express();

var upload = multer({ dest: 'uploads/' });

server.post('/upload_images', upload.array('images_data'), (req, res) => {
    console.log(req.files);
    
    // req.files.forEach(item => {
    //     fs.renameSync(item.path, item.destination + item.originalname)
    // })
});

const PORT = 3000
server.listen(PORT, () => {
    console.log(`listening at ${PORT} ...`);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.