Upload the image file in the mongoDB database via React Native Client

67 Views Asked by At

I can get the image file in the mongoDB database via postman, but not via React Native Client. I suspect the problem to be in formData configuration. Thanks so much for feedback

You can find the code at:

Client: https://github.com/kjahandel/rn/compare/kjahandel-patch-1?expand=1

model: https://github.com/kjahandel/rn/compare/kjahandel-patch-3?expand=1

Server: https://github.com/kjahandel/rn/compare/kjahandel-patch-2?expand=1

I can get the image file in the mongoDB database via postman, but from React Native App:

const uploadImage = async (selectedImageUri) => {

        if(!selectedImageUri){
            console.error("Kein Bild zum Hochladen ausgewählt.");
            return;
        }

        // Extrahieren des Dateinamens aus der imageUri
        const fileName = extractFileName(selectedImageUri);
        const formData = new FormData();

        formData.append('image', {

            name: fileName,
            img: {
                data: selectedImageUri,
                type: 'image/jpg' || 'image/jpeg' || 'image/png' || 'image/gif',
            },

        });

        try {
            const response = await axios.post('https://4c5b-77-0-73-93.ngrok-free.app/uploadImage', formData, {
                headers: {
                    "Content-Type": "multipart/form-data",
                },
            });

            console.log("Bild wurde erfolgreich hochgeladen", response.data);
            alert('Bild wurde erfolgreich hochgeladen.');

        } catch (error) {
            console.error("Fehler beim Hochladen des Bildes: ", error);
            alert("Fehler beim Hochladen des Bildes.");
        }
    };

in mongoDB:

_id: 650df8d6dc19fef473035276
name: "1695414486229_F268D1D7-70B1-4878-9A87-44917DA1DCE8.jpg"

img: Object
   data: BinData(0, '').  <-- ???????????
   contentType: "image/jpg"
__v
1

There are 1 best solutions below

0
user18309290 On

A file object should have uri, name and type fields, something like this:

const formData = new FormData();
formData.append(
  'image',
  {
    uri: <uri>,
    name: <name>,
    type: <type>
  }
);
axios.post(<url>, formData);