首页 > 解决方案 > 即使在 Cypress 中尝试将 pdf 文件作为多部分 FormData POST 请求发送时,FormData 对象仍为空

问题描述

我想将 pdf 文件作为 POST 请求发送。

API 接受@RequestPart@RequestParam

@RequestPart("file") MultipartFile file;
@RequestParam(value = "document-types", required = false) Set<String> documentTypes;

我试图这样做:

it('test', () => {
    cy.fixture(pdfFilePath, "binary").then(file => {
        const data = new FormData();
        data.set('file', file);
        data.set('document-types', 'New Type');
        cy.request({
            method: "POST",
            url: '/api/v4/documents',
            headers: {
            accepts: "multipart/form-data",
            authorization: authString
            },
            body: data
        }).then((response) => {
            expect(response.status).to.eq(200)
        });
    });
});

当我运行它时,我得到:

Status: 400 - Bad Request

在赛普拉斯,我看到发送的请求中的正文是空的: Body: {}

在此处输入图像描述

当我尝试调试代码时,我看到data发送的是空的,正如您在所附屏幕截图中看到的那样:

在此处输入图像描述

我想知道为什么,因为我尝试data通过在上面屏幕截图的第 154 行和第 155 行中执行这些步骤来设置:

data.set('file', file);
data.set('document-types', 'New Type');

我在这里想念什么?

柏树版本:9.0.0

标签: javascripttypescriptautomated-testscypress

解决方案


你必须附加formData,下面的代码只是一个例子:

    const formData = new FormData()
    formData.append('file', files[0])
    formData.append('name', files[0].name)

推荐阅读