如何将图像从expo-image-picker上传到使用multer的Express.js

问题描述 投票:0回答:1

如标题所示,我正在尝试使用 expo-image-picker 和express.js 后端上传图片

展会代码:

const pickImage = async () => {
    let result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.All,
      allowsEditing: true,
      aspect: [4, 4],
      quality: 1,
    });

    console.log(result);

    if (!result.canceled) {
      setImage(result.assets[0].fileName);
      console.log(result.assets[0].fileName);

      const formData = new FormData();
      formData.append("file", {
        filename: result.fileName,
        mimetype: result.mimeType,
        size: result.fileSize, 
      });

      axios
        .post(`http://${apiURL}:8000/api/upload`, formData, {
          headers: {
            "Content-Type": "multipart/form-data",
          },
        })
        .then(() => {
          console.log("archivo enviado");
        })
        .catch((err) => {
          console.log("Archivo no enviado", err);
        });
    }
  };

快递代码

const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, "./storage/imgs");
  },
  filename: (req, file, cb) => {
    const uniqueSuffix = Date.now() + "-" + Math.round(Math.random() * 1e9);
    cb(null, file.originalname);
    console.log(file);
  },
});
const upload = multer({ storage });

app.post("/upload", upload.single("archivo"), (req, res) => {
  if (req.file) {
    res.json({
      message: "Imagen subida con éxito",
      file: req.file,
    });
    console.log(req.file);
  } else {
    const message = "No se ha seleccionado ningún archivo";
    res.status(400).json({ message });
  }
});

当我测试仅使用 Postman 后端上传图像时,一切正常。

错误为 [AxiosError: 请求失败,状态码 400]

react-native express expo multer
1个回答
0
投票

我没有与 axios 一起使用过,但这确实可以与 fetch 一起使用,

首先需要添加base64选项到launchImageLibraryAsync

let result = await ImagePicker.launchImageLibraryAsync({
    mediaTypes: ImagePicker.MediaTypeOptions.All,
    allowsEditing: true,
    aspect: [4, 4],
    quality: 1,
    base64:true
});

我们需要一个包含图像数据的 blob

import { Buffer } from "buffer";

const imageBuffer = Buffer.from(result.base64,"base64");
const imageBlob = new Blob([imageBuffer],{type}); // type is your image format eg: image/png
const formData = new FormData();
formData.append("file",imageBlob,"imageName."+imageExtention);

看看this以获得更多帮助,并可能有一个优雅的解决方案。

© www.soinside.com 2019 - 2024. All rights reserved.