Upload React-Native image with Xios and Multer, backend with nodejs

Asked

Viewed 86 times

-2

I need to upload an image pro backend and save it, but the api function does nothing

Function calling the Axios

  const teste = () =>{


console.log(picture)

Axios.post(apiPath+'/api/addPostagem', 
  

  {picture: picture}, // se botar apenas "picture" aki sem os {} não consegue chamar a api(da 
  //network error)
  {
    headers: {
    "Content-Type": `multipart/form-data; boundary=${picture._boundary}`,
    }
  }
  
  ).then((response)=> {
    console.log(response.data)

  });
}

Taking the picture with the expo-image-picker

 async function imagePickerCall() {
if (Constants.platform.ios) {
  const { status } = await 
 Permissions.askAsync(Permissions.CAMERA_ROLL);

  if (status !== "granted") {
    alert("Nós precisamos dessa permissão.");
    return;
  }
}
const data = await ImagePicker.launchImageLibraryAsync({
  mediaTypes: ImagePicker.MediaTypeOptions.Images,
  aspect: [4, 3],
  quality: 1,
});
//console.log(data);
if (data.cancelled) {
  return;
}

if (!data.uri) {
  return;
}

setPicturePreview(data.uri) // colocando a foto selecionada numa 
variável pra mostrar na tela atual

const newUpload = new FormData(); //adicionando informações da imagem em 
//um formData

newUpload.append("picture", data);

setPicture(newUpload);
}

in the console.log(picture) returns the object of the image I picked up with the image Picker and if I use this 'Uri' to show the image in the current page works normal

inserir a descrição da imagem aqui

In the backend

const upload = multer({ dest: 'img/'}) // é pra salvar a imagem numa pasta que esta no mesmo 
//nivel do codigo

app.post("/api/addPostagem",upload.single("picture"), (req, res) =>{
console.log(req.picture+'1') // retorna undefined
console.log(req.file+'2') // retorna undefined


res.send('123') // o front end recebe isso, porem a imagem n é salva
})

in the backend also I tried to use multer like this, but the same result:

const Storage = multer.diskStorage({
destination(req, file, callback) {
  callback(null, 'img/')
},
filename(req, file, callback) {
  callback(null, file.originalname + Date.now());
},
})
 const upload = multer({ 
  storage: Storage,
  
  limits:  2 * 1024 * 1024
})
app.post("/api/addPostagem",upload.single("picture"), (req, res) =>{
console.log(req.picture+'1') // retorna undefined
console.log(req.file+'2') // retorna undefined


res.send('123') // o front end recebe isso, porem a imagem n é salva
})
  • How is the object picture? He is a FormData?

  • Yeah, he’s that print there

  • Okay, but how did you mount this FormData? how is the append(...)

  • edited the post by putting the use of imagePicker/ as I did the picture

1 answer

0

I was able to solve, as I understood, pro multer recognize the image, has q have in formData 3 characteristics, name, type and Uri, as Piker q to using n provides the name and type, I create one when I create the formData

Creating the formData

...
setPicturePreview(data.uri) // 
let typeImg = (data.uri).slice(-3); // pegando as 3 ultimas letra pra pegar o tipo

const newUpload = new FormData(); //adicionando informações da imagem em um 
formData
newUpload.append("picture",
{
  name: 'postagemPicture',
  type: 'image/'+typeImg,
  uri: data.uri
}
...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.