如何使用multer将图像文件发送到服务器并做出反应

时间:2020-01-27 15:27:24

标签: reactjs image express upload multer

我正在尝试将图像文件发送到服务器,但未显示任何内容。 我曾尝试使用multer,但它也无法正常工作。 我也尝试显示req.body,但显示空白{}

帮助

Express.js

const bodyParser = require("body-parser");

const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
var multer = require("multer");
var upload = multer({ dest: "uploads/" });
app.post("/", upload.single("photo"), (req, res, next) => {

    console.log(req.file);

});
app.listen(8000, () => console.log("Server is running on 8080"));

反应JS

send_image = async () => {
let body = new FormData();
body.set("photo", {
  uri:
    "https://snaped.fns.usda.gov/sites/default/files/styles/crop_ratio_7_5/public/seasonal-produce/2018-05/watermelon.jpg",
  name: "photo",
  filename: "imageName.jpg",
  type: "image/jpeg"
});
//body.append("Content-Type", "image/jpeg");

await fetch("https://786fm.sse.codesandbox.io/", {
  method: "POST",
  headers: {
    "Content-Type": "image/jpeg"
  },
  body: body
})
  .then(res => res.json())
  .then(res => {
    console.log("response" + JSON.stringify(res));
  })
  .catch(e => console.log(e));
};
UNSAFE_componentWillMount() {
    this.send_image();
}

0 个答案:

没有答案