使用HTTP post上传Nodejs文件

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

我正在为 TestRail 扩展 Cypress 测试插件,将 Cypress 测试结果推送到 TestRail。该插件仅添加测试结果(通过/失败),我正在尝试上传测试期间拍摄的屏幕截图。我可以使用 API 通过 GET 和 POST 调用来读取和写入其他信息,但我无法让文件上传正常工作。

这里是我尝试实现的 API 调用的文档: TestRAil 文件上传

我让 API 使用 Python 工作:

resp = R.post('https://example.testrail.io/index.php?/api/v2/add_attachment_to_result/123456',auth=self.credentials, files={'attachment': open('/home/user/path/to/file.png', 'rb')})

当我在 Javascript (Nodejs) 中尝试这个时:

const got = require('got')
const fs = require('fs')

file = ‘/home/user/path/to/file.png’
const form = new FormData()

form.append('attachment', fs.createReadStream(file)) // Option A
form.append('attachment', fs.readFileSync(file)) // Option B

const response = await got('https://example.testrail.io/index.php?/api/v2/add_attachment_to_result/123456', {
  method: 'POST',
  headers: {
    'Content-Type': 'multipart/form-data',
    authorization,
  },
  body: form
})
 

选项 A 和 B 都出现相同的错误:

RequestError: The `body` option must be a stream.Readable, string or Buffer

准备上传文件的正确方法是什么?

node.js post file-upload multipartform-data
1个回答
0
投票

问题出在您的文件路径中,未正确导入使用nodejs给出的路径模块并在发布请求之前尝试控制台日志

    const path=require('path');
    file = path.join(__dirname,‘/home/user/path/to/file.png’);
    const form = new FormData()
    form.append('attachment', fs.createReadStream(file)) // Option A
    form.append('attachment', fs.readFileSync(file)) // Option B
    console.log("file is loaded",form);

我自己试过了,效果很好

    import got from "got";
    import fs from "fs";
    const filePath = "./icon.png";

    const fetchResponse = async () => {
    try {
        const form = new FormData();
        form.append("attachment", fs.createReadStream(filePath)); // Option A
        form.append("attachment", fs.readFileSync(filePath)); // Option B
        console.log(form);
        const response = await got(
        "https://webhook.site/8c554904-0716-4408-b48b-35fcc0bf65ce",
        {
            method: "POST",
            headers: {
            "Content-Type": "multipart/form-data",
            },
            body: form,
        },
        );
        console.log(response);
    } catch (err) {
        console.log("Errror in Fetch", err);
    }
    };

    fetchResponse();
© www.soinside.com 2019 - 2024. All rights reserved.