How to submit a multipart image - Error: Multipart: Boundary not found

How to submit a multipart image - Error: Multipart: Boundary not found

我有一个客户端 javascript sdk 将图像提交到服务器端 node.js api 使用 multer 库解析图像。

但是我注意到如果我将 header 设置为 content-type multipart-formdata multer 将抛出一个错误提示

Error: Multipart: Boundary not found

async submitDocument(id, side, image) {

        const url = this.API_URL + "/api/document";

        let formData = new FormData();
        formData.set("image", image, "front.jpg");
        formData.set("side", side);

        let headers = new Headers();
        headers.set("content-type", "multipart/form-data");
        headers.set("Authorization", "Bearer " + this.API_KEY);

        const request = {
            method: "POST",
            body: formData,
            headers: headers,
        };

        try {

            const response = await fetch(url, request);
            const data = await response.json();

            return data;

        } catch (err) {
            throw err;
        }

    }

npm 模块 connect-multiparty 可能对您有所帮助。来自服务器端节点应用程序。

server.js

const multipart = require('connect-multiparty');
const multipartMiddleware = multipart();  
router.post('/api/document', multipartMiddleware);
router.post('/api/document', (req, res) => {
  console.log(req.files)
})

post-man api 测试样本- https://i.stack.imgur.com/vxBpz.png

如错误消息所述,multipart/form-data 内容类型需要 boundary 参数。

不要自己设置 Content-Type。允许浏览器从 formData 对象生成它。