payload-rest-client icon indicating copy to clipboard operation
payload-rest-client copied to clipboard

attaching files / multipart/form-data

Open genox opened this issue 9 months ago • 2 comments

Hi,

I am currently rewriting large swathes of an existing app to use your client, so things pop up now and then ;)

Something that's missing or undocumented currently are file uploads via REST. Since this requires sending multipart/formdata to the API, I am not sure if there is an easy way to implement this into this library.

The standard way of doing this with payload is:

	async postMedia(data: { file: File; title: string; description: string; }) {
		const { file, title, description } = data
		const formData = new FormData()
		formData.append('file', file)
		formData.append('_payload', JSON.stringify({ title, description }))
		return await this.client.post<CreatedDoc<Media>>(`/api/media`, formData, {
			headers: { 'Content-Type': 'multipart/form-data' },
		})
	}

(this is my current own implementation of a client using axios)

So the document title and description are merged into the formData object, file is just File. Not sure how one would conditionally offer a file: property for collections that allow uploads, or a method instead of create(), createUpload() that accepts doc and file, to keep it consistent.

genox avatar Feb 18 '25 23:02 genox

Hey, file uploads or multipart/form-data requests aren't implemented and to keep the library simple, it hasn't been planned so far. I think that file uploads are a rare use case, so I would write these requests manually. Sorry.

But I will keep it in mind. Maybe I could add separate uploads proxy like client.uploads.media.create(...) and client.uploads.media.updateById(...).

dkirchhof avatar Feb 19 '25 07:02 dkirchhof

That's fair. I agree it's not that common, but it would be part of aspiring to be a feature complete client for payload.

genox avatar Feb 19 '25 11:02 genox