-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
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 aFormData
?– Cmte Cardeal
Yeah, he’s that print there
– Zidane
Okay, but how did you mount this
FormData
? how is theappend(...)
– Cmte Cardeal
edited the post by putting the use of imagePicker/ as I did the picture
– Zidane