Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

351
Visualizações
FormData object is empty even though it is being set when trying to send a pdf file as a multipart FormData POST request in Cypress

I want to send the pdf file as a POST request.

The API accepts @RequestPart and @RequestParam:

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

I tried to do it that way:

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)
        });
    });
});

And when I run this I get:

Status: 400 - Bad Request

In Cypress I see that body in request sent is empty: Body: {}

enter image description here

When I tried to debug the code, I see that data is being sent empty as you see on the attached screenshot:

enter image description here

And I wonder why because I try to set the data by doing these steps in lines 154 and 155 on the above screenshot:

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

What am I missing here?

Cypress version: 9.0.0

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

you have to append formData, code below is just an example:

    const formData = new FormData()
    formData.append('file', files[0])
    formData.append('name', files[0].name)
about 4 years ago · Juan Pablo Isaza Relatório

0

It's not empty, you have to make use of data.entries() to view the content.

It seems like the cy.request() function tries to convert the FormData Object to a JSON object which is wrong.

From the documentation of cypress you should also make also use of the form: true setting.

References:

  • https://developer.mozilla.org/en-US/docs/Web/API/FormData
  • https://xhr.spec.whatwg.org/#interface-formdata
about 4 years ago · Juan Pablo Isaza Relatório

0

As @Christopher mentioned in the answer,data was not empty. I had to use data.entries() or simply data.get() to view the content.

But anyways I was not able to make that code working.

Instead, I followed the approach presented in this youtube video and it worked.

it.only('test', () => {
    function form_request(method, url, formData, done) {
        const xhr = new XMLHttpRequest();
        xhr.open(method, url);
        xhr.setRequestHeader(
            "Authorization",
            "Basic YWRtaW46YWRtaW4="
        );
        xhr.onload = function () {
            done(xhr);
        };

        xhr.onerror = function () {
            done(xhr);
        };

        xhr.send(formData);
    }

    const fileName = "PdfFileName.pdf";
    const method = "POST";
    const url = '/api/v4/documents';
    const fileType = "application/pdf"

    cy.fixture(pdfFilePath, "binary")
        .then((txtBin) => Cypress.Blob.binaryStringToBlob(txtBin))
        .then((blob) => {
            const formData = new FormData();
            formData.append("file", blob, fileName);
            formData.append("document-types", "New Type");
            form_request(method, url, formData, function (response) {
                expect(response.status).to.eq(200);
            })
    });
})
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda