How to upload files through the API?

I’m trying to figure out how to allow file uploads through the API. I’ve seen this helpful post: How to upload a file via API and get it's URL? - #3 by Daniil_Bazhenov,

but it doesn’t give the actual syntax–and that’s what I’m struggling with. Does anyone have the actual syntax for the ajax call?

This is what I’ve got:

 method: "post",
      url: [site]/uploads.json,
      contentType: "multipart/form-data",
      data: {
        type: "composer",
        file: '/path_to_file_from_users_machine'
      },
      headers: {
        "User-Api-Key": key
      },
      dataType: "json",
    }).then((result)=>{

But this gives a 422 response–something’s not quite right with this syntax. How can I make it work?

1 Like

Is there a message that goes with the response? That should give you more information.

As far as I can see, this is the only response:
Error: Request failed with status code 422

And I don’t see anything in the logs.

Here is a node example that someone got working that might help:

Thanks very much, @blake. That is a helpful post that I hadn’t seen before (despite searching for one like that). It will help me move forward for sure. One thing caught my eye, though. This line in the linked code:
const file = fs.readFileSync(filename);

This line implies that what you upload to discourse is not actually the file itself, but the contents of the file (in the above code, the file variable = the string returned from reading the file). That’s surprising to me, and I’m wondering what that means for uploading binary files (or media files–which upload fine to discourse directly (if size is ok), but not sure how reading them first will work).

But I’ll check it out.

1 Like