elbywan / wretch

A tiny wrapper built around fetch with an intuitive syntax. :candy:
MIT License
4.79k stars 96 forks source link

Right way to upload files (post) #71

Closed AHorak closed 4 years ago

AHorak commented 4 years ago

Specialy when mixing other data from the form. i have tried;

static async postGetJson<T>(url: string, body?: any): Promise<T> { var client = (await this.baseApi()).url(url); if (body) client = client.formData(body); return await client.post().json<T>(); }

with

' let filedata = new FormData(); if(file) { filedata.append("files", file, file.name); }'

AHorak commented 4 years ago

it works only, when adding FomData as body. But i need both. formdata and body

elbywan commented 4 years ago

Hi @AHorak,

it works only, when adding FomData as body. But i need both. formdata and body

I'm not sure I understand your question, FormData objects are typically used to serialize the body for request having the multipart/form-data content-type.

If you need to post data alongside the file, you can just append more stuff to the FormData using the .append method.

I would advise reading this guide as this question is really not related to this library.

AHorak commented 4 years ago

I solved this problem by creating my own FormData Object and converting my Object to it (like convertFormData in wretcher.js) then after that i appeded my file. I was just looking for an elegant way to do this with Wretch.

It would be nice to have a simple way to do this. Something like a way to access the internal FormData object which was assigned to body after using the formData Property of Wretch.

elbywan commented 4 years ago

@AHorak Sorry for the late reply,

It would be nice to have a simple way to do this. Something like a way to access the internal FormData object which was assigned to body after using the formData Property of Wretch.

It is already possible to append File objects with other values using the .formData helper:

 const file = new File(["foo"], "foo.txt", {
  type: "text/plain",
})
wretch("url")
  .formData({
    file,
    param: "param"
  })
  .post()
  .res(console.log)
  .catch(console.error)
Capture d’écran 2020-03-22 à 10 31 04