Open link in a new tab

Content

Expand project menu

Need Help regarding How to Upload (POST) attachment to particular work-package

For this API :

Create work package attachment

POST     /api/v3/work_packages/{id}/attachments

To add an attachment to a work package, a client needs to issue a request of type multipart/form-data with exactly two parts.

The first part must be called metadata. Its content type is expected to be application/json, the body must be a single JSON object, containing at least the fileName and optionally the attachments description.

The second part must be called file, its content type should match the mime type of the file. The body must be the raw content of the file. Note that a filename must be indicated in the Content-Disposition of this part, however it will be ignored. Instead the fileName inside the JSON of the metadata part will be used.

This is my file variable that got through input field from frontend code

File {
  size: 5132,
  type: 'image/png',
  name: 'Screenshot from 2024-03-22 17-05-14.png',
  lastModified: 1711445527966
}

This is my code to call api

import { EntityManager } from 'op-client'

const OPManager = new EntityManager({
  baseUrl: process.env.OP_BASE_URL as string,
  oauthOptions: {
    clientId: process.env.OP_CLIENT_ID,
    clientSecret: process.env.OP_CLIENT_SECRET
  },
  createLogger: () => console
})

	const newForm = new FormData()
    newForm.append('metadata',{'fileName':`${file?.name}`,'contentType':`${file?.type}`,'fileSize':`${file?.size}`})
    newForm.append('file',file)
    const res = await OPManager.fetch('/api/v3/work_packages/3784/attachments',{
      headers: {
        'Content-Type': 'multipart/form-data',
        'Content-Disposition': `form-data; filename=${file?.name};`
      },
      method:'POST',
      body:newForm,
    })

Error I got in my console is :

An error occured while api call Error: 422 [urn:openproject-org:api:v3:errors:MultipleErrors] Multiple field constraints have been violated. contentType: The content type of the file cannot be blank. filename: File can't be blank.
   at EntityManager.fetch (webpack-internal:///(rsc)/./node_modules/op-client/dist/src/EntityManager/EntityManager.js:85:31)
   at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
   at async POST (webpack-internal:///(rsc)/./src/app/api/AddTicket/route.ts:22:21)
   at async /home/harshoza/WORK/15MARCH/customer-facing-app/node_modules/next/dist/compiled/next-server/app-route.runtime.dev.js:6:62499

Message actions

Hey! I just spent A LOT of time on this yesterday (using Python requests library). I got different error codes with different request structures. What solved things for me in the end was to not set any headers (not sure what requests library does under the hood, but this is what finally got my requests through).

Message actions

Matt User wrote:

Hey! I just spent A LOT of time on this yesterday (using Python requests library). I got different error codes with different request structures. What solved things for me in the end was to not set any headers (not sure what requests library does under the hood, but this is what finally got my requests through).

Can you share code snippets and library that you have used

Message actions

I am using Python's requests library (old v2.20 due to company requirements).

Code snippet:

import json
import requests

# this is distributed across several modules

local_path = <path to file on local disc>

metadata = {
    "fileName": self.file_name
}

files = [
    ("file", (self.file_name, open(local_path, 'rb'))),
    ("metadata", (None, json.dumps(metadata), "application/json"))
]

[...]
headers = {}
params = {'notify': 'false'}
[...]
response = self.session.post(
  	# this is the /api/v3/work_packages/{id}/attachments endpoint
    full_endpoint,
    headers=headers,
  	# auth is set to the API key
    auth=auth,
    params=params,
    files=files
)
[...]