Can not upload file, getting "'file' is a required property" error

Hey there, I try to upload file using REST API but I get the same error over and over.

async function uploadFile() {
  const config = {
    method: 'POST',
    headers: { 
      'Authorization': `Bearer ${apiKey}`, 
      'Content-Type': 'multipart/form-data'
    },
    body : JSON.stringify({
      file: fs.createReadStream('content.txt'),
      purpose: 'assistants'
    })
  };

  let response = await fetch('https://api.openai.com/v1/files', config);
  let result = await response.json();
  console.log(result);
}

uploadFile();

Error below

{
  error: {
    message: "'file' is a required property",
    type: 'invalid_request_error',
    param: null,
    code: null
  }
}

According to the documentation request body should has two parameters: file and purpose and that is exactly what I do.

Could someone please point me what I do wrong or give me hint how I can solve it?

The issue you’re encountering is related to how the file data is being included in the request body. When using multipart/form-data for file uploads, the body of the request should not be a JSON string. Instead, it should be a FormData object that contains the file stream and other fields.

In your current code, you’re using JSON.stringify which is not suitable for multipart/form-data. This is likely why the server is not recognizing the ‘file’ field in your request.

Here’s how you can modify your function to correctly upload the file:

async function uploadFile() {
  const formData = new FormData();
  formData.append('file', fs.createReadStream('content.txt'));
  formData.append('purpose', 'assistants');

  const config = {
    method: 'POST',
    headers: { 
      'Authorization': `Bearer ${apiKey}`
      // Do not set 'Content-Type' here. Let the browser set it.
    },
    body : formData
  };

  let response = await fetch('https://api.openai.com/v1/files', config);
  let result = await response.json();
  console.log(result);
}

uploadFile();

Key Changes:

  1. Removed 'Content-Type': 'multipart/form-data' from headers. When using FormData, the browser will automatically set the correct Content-Type header including the boundary.
  2. Replaced JSON.stringify with FormData. This correctly formats the request body for file uploads.

This should resolve the error you are facing.

3 Likes

@PaulBellow yeah, it works for me now, you made my day. Thanks a lot.

1 Like

@pazhukhjob

Is it OK if a moderator closes this topic?

@EricGT Yes please, thanks.

1 Like