Content
Need Help regarding How to Upload (POST) attachment to particular work-package
Added by Harsh Oza 8 months ago
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
Replies (3)
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).
Matt User wrote:
Can you share code snippets and library that you have used
I am using Python's requests library (old v2.20 due to company requirements).
Code snippet: