how to get images with Multer and React-native

Viewed 228

so I build my app with MERN, and now I try to save photos to my backend and show them in gallery.

I installed Multer, and I can upload photos to my backend, now if I write in my explorer "http://localhost8080:/uploads/image_7076.jpg" I get the actual image like expected, and the image saved in directory called uploads.

the problem is when I try to get them from the front is not find them.

the important parts of the code for backend:

    const imageRoutes = require("./routes/image");

//middlewares
app.use(morgan("dev"));
app.use("/uploads", express.static("uploads"));
app.use(bodyParser.json());
app.use(cookieParser());
app.use(expressValidator());
app.use(cors());

app.use("/", imageRoutes);


const port = 8080;
app.listen(port, () => {
    console.log(`listening on port ${port}`);
});

route:

    const express = require("express");
const { getImages, uploadImage } = require("../controllers/image");
const multer = require("multer");

//configure the images
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, "./uploads");
    },
    filename: function (req, file, cb) {
        console.log("f", file);
        cb(null, file.originalname);
    },
});

const upload = multer({
    storage: storage,
    limits: {
        fileSize: 1024 * 1024 * 55,
    },
});

const router = express.Router();
router.get("/images", getImages);
router.post("/images/new", upload.single("image"), uploadImage);
module.exports = router;

contorollers:

    const Image = require("../models/image");
const _ = require("lodash");

exports.getImages = (req, res) => {
    Image.find()
        .select("_id image desc")
        .then(images => {
            res.json({ images });
        })
        .catch(err => console.log("get images errors", err));
};

//INSERT NEW IMAGE//
exports.uploadImage = (req, res) => {
    const image = new Image({
        image: req.file.path,
        desc: req.body.desc,
    });
    console.log("ss", image);
    image.save(err => {
        if (err) {
            return res.status(400).json({ error: "העלאת תמונה נכשלה" });
        }
        res.json({ message: "העלאת תמונה עברה בהצלחה" });
    });
};

now the question how can i get them correctly from the front ? frontend code :

const GalleryScreen = () => {
    const [s, ss] = useState({});
    const numColumns = 3;
    console.log("sssssss2", s.images);
    useEffect(() => {
        async function fetch() {
            try {
                const response = await indexApi.get(`/images`);
                console.log(response.data);
                ss(response.data);
            } catch (err) {
                console.log(err);
            }
        }
        fetch();
    }, []);

    return (
        <>

            <FlatList
                numColumns={numColumns}
                data={s.images}
                renderItem={({ item, index }) => (
                    <View style={styles.imagecontainer}>
                        <Text>{item.desc}</Text>
                        <Image style={styles.image} source={require("../../assets/images/backgroundImages/t2.jpg")} />
                    </View>
                )}
                keyExtractor={(item, index) => index.toString()}
            />
        </>
    );
};

I tried also to: get from the server:

<Image source={{ uri: "http://localhost:8080/" + item.image }} />////// console log->http://localhost:8080/uploads\IMG_7093.JPG

get from the directory:

<Image source={"../../server/uploads/img_7093.jpg"} />

(and also two of them with require.. but nothing)

note that i get from fetch array of images object like so:

"_id": "5fc3db9de77fa642007db6db",
"desc": "wahad",
"image": "uploads\\IMG_7093.JPG",
0 Answers
Related