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

Hi all, after some struggling and trial & error, I thought I’d share a PHP sample that works for uploading files to Discourse! Here ya go. Also, I’ve been creating an updated library originally from communiteq/discourse-api-php: PHP API client for Discourse (github.com):

<?php
	
	$curl = curl_init();
	
	curl_setopt_array($curl, array(
		CURLOPT_URL => 'https://example.com/uploads.json',
		CURLOPT_RETURNTRANSFER => true,
		CURLOPT_ENCODING => '',
		CURLOPT_MAXREDIRS => 10,
		CURLOPT_TIMEOUT => 0,
		CURLOPT_FOLLOWLOCATION => true,
		CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
		CURLOPT_CUSTOMREQUEST => 'POST',
		CURLOPT_POSTFIELDS => array(
			'type' => 'composer',
			'synchronous' => 'true',
			'file'=> new CURLFILE('/directory/filename.txt')),
		CURLOPT_HTTPHEADER => array(
			'Content-Type: multipart/form-data',
			'Accept: application/json',
			'Api-Key: <your api key>',
			'Api-Username: <your api user id>'
		),
	));
	
	$response = curl_exec($curl);
	$info = curl_getinfo($curl);
	curl_close($curl);
	print_r(json_decode($response,1));
	print_r($info);
?>

Sample Output:

Array
(
    [id] => 627
    [url] => https://example.com/uploads/default/original/1X/4661e3a873857e04440bcc3e4290e241eb6c08d7.txt
    [original_filename] => filename.txt
    [filesize] => 461
    [width] => 
    [height] => 
    [thumbnail_width] => 
    [thumbnail_height] => 
    [extension] => txt
    [short_url] => upload://a2D9hHsjwsdrVWkzlu5Go4c1VvV.txt
    [short_path] => /uploads/short-url/a2D9hHsjwsdrVWkzlu5Go4c1VvV.txt
    [retain_hours] => 
    [human_filesize] => 461 Bytes
    [dominant_color] => 
    [thumbnail] => 
)
Array
(
    [url] => https://example.com/uploads.json
    [content_type] => application/json; charset=utf-8
    [http_code] => 200
    [header_size] => 422
    [request_size] => 1244
    [filetime] => -1
    [ssl_verify_result] => 0
    [redirect_count] => 0
    [total_time] => 0.029617
    [namelookup_time] => 0.00046
    [connect_time] => 0.003265
    [pretransfer_time] => 0.003592
    [size_upload] => 911
    [size_download] => 460
    [speed_download] => 15531
    [speed_upload] => 30759
    [download_content_length] => 460
    [upload_content_length] => 911
    [starttransfer_time] => 0.029604
    [redirect_time] => 0
    [redirect_url] => 
    [primary_ip] => 192.168.192.40
    [certinfo] => Array
        (
        )

    [primary_port] => 80
    [local_ip] => 192.168.192.18
    [local_port] => 61613
    [http_version] => 2
    [protocol] => 1
    [ssl_verifyresult] => 0
    [scheme] => http
    [appconnect_time_us] => 0
    [connect_time_us] => 3265
    [namelookup_time_us] => 460
    [pretransfer_time_us] => 3592
    [redirect_time_us] => 0
    [starttransfer_time_us] => 29604
    [total_time_us] => 29617
    [effective_method] => POST
    [capath] => 
    [cainfo] => 
)

Also definitely got a HUGE help with the examples from the Postman samples here: Creates an upload | Discourse | Postman API Network

Cheers

4 Likes