When I send an image to my node/express server that uses multer I am able to save an image to my "uploads" folder with this server side code and request from Postman:
server.js
const express = require("express");
const app = express();
const cors = require("cors");
app.use(cors());
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
const multer = require("multer");
const upload = multer({ dest: "uploads/" });
app.post("/upload", upload.single("image"), (req, res) => {
console.log("file ==>", req.file);
res.json(req.file);
});
app.listen(5000, () => console.log("listening at http://localhost:5000"));
But when I try to send this from the RN client, it makes it past the middleware with no error, sends back the success message, but doesn't save the image and req.file is undefined.
Client side code and response:
import React, { useState, useEffect } from "react";
import { Button, Image, View, Platform } from "react-native";
import * as ImagePicker from "expo-image-picker";
import axios from "axios";
export default function ImagePickerExample() {
const [image, setImage] = useState(null);
const pickImage = async () => {
let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.All,
allowsEditing: true,
aspect: [4, 3],
quality: 1,
});
if (!result.cancelled) setImage(result.uri);
};
const uploadImage = () => {
const formData = new FormData();
formData.append("image", {
uri: image,
name: new Date() + "_profile",
type: "image/png",
});
axios
.post("http://localhost:5000/upload", formData, {
headers: {
Accept: "application/json",
"Content-Type": "multipart/form-data",
},
})
.then((res) => console.log("result =>", res))
.catch((err) => console.log(err));
};
return (
<View style={{ flex: 1, alignItems: "center", justifyContent: "center" }}>
<Button title="Pick an image from camera roll" onPress={pickImage} />
{image && (
<Image source={{ uri: image }} style={{ width: 200, height: 200 }} />
)}
{image && <Button title="Send to DB" onPress={uploadImage} />}
</View>
);
}
I can see that URI is saved to state image
. I think my problem is with FormData and how I'm putting it together, but I can't spot the error when I look through docs / articles / tuts.
1条答案
按热度按时间6ioyuze21#
我认为在使用FormData时,必须使用
var
或let
而不是const
。原因是,由于要向变量追加数据,因此需要能够更改变量内存的内容。