React Native使用Express和multer将提取的多个图像上传到Node JS服务器

时间:2020-06-20 05:47:46

标签: node.js image react-native fetch multer

我正在尝试将多张图片上传到我的Nodejs服务器,在这里我使用multer解析表单数据, 但是问题是,当我尝试通过邮递员上传图像时,它可以成功上传,但是使用react native fetch api却无法正常工作。

这是我的代码:

反应原生:

import React from "react";
import { View, Text, Button } from "react-native";

export default function imageUpload(props) {



 function upload() {
    const photo1 = {
      uri: "https://html5box.com/html5gallery/images/Swan_1024.jpg",
      type: "image/jpeg",
      name: "photo1.jpg",
    };
    const photo2 = {
      uri:
        "https://www.canva.com/wp-content/themes/canvaabout/img/colorPalette/image4.jpg",
      type: "image/jpeg",
      name: "photo2.jpg",
    };

    const photos = [photo1, photo2];
    const form = new FormData();

    for (let photo in photos) {
      form.append("image", photos[photo]);
    }

    console.log(form);

    fetch("http://192.168.31.208:3000/uploads", {
      body: form,
      method: "POST",
      headers: {
        "Content-Type": "multipart/form-data",
        // Accept: "application/x-www-form-urlencoded",
      },
    })
      .then((response) => response.json())
      .then((responseData) => {
        console.log("Response:" + responseData);
      })
      .catch((error) => {
        console.log(error);
      });
  }
  return (
    <View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
      <Text>Image Upload</Text>
      <Button title="Test" onPress={upload} />
    </View>
  );
}

服务器代码:

const express = require("express");
const http = require("http");
const multer = require("multer");
const path = require("path");

const storage = multer.diskStorage({
  destination: "./uploads",
  filename: function (req, file, cb) {
    cb(
      null,
      file.fieldname + "-" + Date.now() + path.extname(file.originalname)
    );
  },
});

const upload = multer({
  storage: storage,
  limits: { fileSize: 52428800 },
  fileFilter: function (req, file, cb) {
    checkFileType(file, cb);
  },
}).array("image");

function checkFileType(file, cb) {
  const fileType = /jpeg|jpg|png|gif/;
  const extname = fileType.test(path.extname(file.originalname).toLowerCase());
  const mimeType = fileType.test(file.mimetype);

  if (extname && mimeType) {
    return cb(null, true);
  } else {
    cb("Error: FILE_SHOULD_BE_TYPE_IMAGE");
  }
}

// Initialise app
const app = express();
app.use(express.static("./uploads"));

app.post("/uploads", (req, res) => {
  upload(req, res, (err) => {
    if (err) {
      res.status(400).json({
        error: err,
      });
    } else {
      console.log(req);
      res.status(200).json({
        // name: req.body.name,
        // image: req.file,
        message: "Testing",
      });
    }
  });
});
app.get("/upload", (req, res, next) => {
  res.status(200).json({
    message: "TestComplete",
  });
});
const port = 3000;

app.listen(port, () => {
  console.log(`Server started on port number: ${port}`);
});

控制台输出前端:

    FormData {
  "_parts": Array [
    Array [
      "image",
      Object {
        "name": "photo1.jpg",
        "type": "image/jpeg",
        "uri": "https://html5box.com/html5gallery/images/Swan_1024.jpg",
      },
    ],
    Array [
      "image",
      Object {
        "name": "photo2.jpg",
        "type": "image/jpeg",
        "uri": "https://www.canva.com/wp-content/themes/canvaabout/img/colorPalette/image4.jpg",
      },
    ],
  ],
}

Network request failed
- node_modules\whatwg-fetch\dist\fetch.umd.js:473:29 in xhr.onerror
- node_modules\event-target-shim\dist\event-target-shim.js:818:39 in EventTarget.prototype.dispatchEvent
- node_modules\react-native\Libraries\Network\XMLHttpRequest.js:574:29 in setReadyState
- node_modules\react-native\Libraries\Network\XMLHttpRequest.js:388:25 in __didCompleteResponse
- node_modules\react-native\Libraries\vendor\emitter\EventEmitter.js:190:12 in emit
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:436:47 in __callFunction
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:111:26 in __guard$argument_0
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:384:10 in __guard
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:110:17 in __guard$argument_0
* [native code]:null in callFunctionReturnFlushedQueue

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

如果您尝试从移动设备(Android / iOS)上传图片,则无法将其作为URL传递。您应该发送本地文件路径/ uri