Uploading attachment through Rest API Salesforce: Simple working solution

Uploading attachment through Rest API in Salesforce is quite easy, though the documentation is not that clear on this.

Uploading attachment through Rest API Salesforce: Simple working solution

Simple HTML Form

Let’s create a simple HTML form to upload the file.

<form action="FileuploadSalesforce.php" method="POST" enctype="multipart/form-data">

<input name="file" type="file" required="true" accept="application/pdf">

<input type="submit" name="submit">

</form>

The form takes a file as input and in this form I have disabled all other file types except pdf.

The form’s action is FileUploadSalesforce.php which uses Rest API to upload files to Attachments in Salesforce.

In the post data, you need to provide the parent id of the record to which the file should be attached.

PHP Code for FileUploadSalesforce.php

<?php
//Add the below credentials to a separate file and call here using include
/***************oAuth2 Connected App Credentials************************************/
define("CLIENT_ID", "<Replace with your Client Id");
define("CLIENT_SECRET", "Replace with your Client Secret");
define("REDIRECT_URI", "Replace with Redirect URI");
define("LOGIN_URI", "Replace with your Login URI");
define("USER_NAME", "Your Username to login to Salesforce");
define("PASSWORD", "Your Password to login to Salesforce");
define("SECURITY_TOKEN", "Your security token");

/***************oAuth2 Connected App Credentials************************************/

$token_url = LOGIN_URI . "/services/oauth2/token";
//Login to Salesforce
$params =  "&grant_type=password"
    . "&client_id=" . CLIENT_ID
    . "&client_secret=" . CLIENT_SECRET
    . "&username=".USER_NAME
	."&password=".PASSWORD
	."&security_token=".SECURITY_TOKEN;

$curl = curl_init($token_url);

//curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $params);

$json_response = curl_exec($curl);

$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);

if ( $status != 200 ) {
	$errstr="Error: call to token URL $token_url failed with status $status, response $json_response, curl_error " . curl_error($curl) . ", curl_errno " . curl_errno($curl).'<br>';
    //die("Error: call to token URL $token_url failed with status $status, response $json_response, curl_error " . curl_error($curl) . ", curl_errno " . curl_errno($curl));
}

curl_close($curl);

$response = json_decode($json_response, true);

$access_token = $response['access_token'];
$instance_url = $response['instance_url'];

if (!isset($access_token) || $access_token == "") {
	$errstr=$errstr." Error - access token missing from response!".'<br>';
   // die("Error - access token missing from response!");
}

if (!isset($instance_url) || $instance_url == "") {
	$errstr=$errstr." Error - instance URL missing from response!".'<br>';
   // die("Error - instance URL missing from response!");
}
//Get the user uploaded file
$file = $_FILES["file"]["tmp_name"];
$remote_file = $_FILES["file"]["name"];

$post_text=[
    "Name" => $remote_file,
	"body" => base64_encode(file_get_contents($file)),
	"parentId" => "replace with salesforce record id",
];
$json_test=json_encode($post_text);
//Upload the file to Documents

$url=$instance_url."/services/data/v45.0/sobjects/Attachment/";
 $curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
 curl_setopt($curl, CURLOPT_HTTPHEADER,array("Authorization: OAuth $access_token","Content-type: application/json;boundary:a7V4kRcFA8E79pivMuV2tukQ85cmNKeoEgJgq"));
curl_setopt($curl, CURLOPT_POST, true);				   
    curl_setopt($curl, CURLOPT_VERBOSE, 1);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $json_test);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLINFO_HEADER_OUT, true);
 $json_response = curl_exec($curl);

    $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);

    if ( $status != 201 ) {
        error_log("Error: call to URL $url failed with status $status, response $json_response, curl_error " . curl_error($curl) . ", curl_errno " . curl_errno($curl));
		//echo "error_message";
		exit;
    }
	else
	{
		echo($json_response);
	}
	
?>

The above code makes use of oAuth2 credentials. You need to first create a connected App in Salesforce. To find more details, follow the link: https://help.salesforce.com/articleView?id=connected_app_create.htm&type=5

Upload both the files to your web server and you should now be able to upload the files to your Salesforce instance using REST Api.

Also read: Upload files to Google Drive from Salesforce

Leave a Reply

Your email address will not be published. Required fields are marked *