<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" /> <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" />

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 another approach to solve this problem here.

8 thoughts on “Uploading attachment through Rest API Salesforce: Simple working solution

  1. How can we get these details in connected app

    define(“CLIENT_ID”, “<Replace with your Client Id");
    define("CLIENT_SECRET", "Replace with your Client Secret");
    define("REDIRECT_URI", "Replace with Redirect URI");

    1. Hi Kiran,

      After you have created the App, you can find the details by following the steps: Setup->Create->Apps->Click on App name in Connected Apps section. This is in classic version.
      In Lightning, Setup->Apps->App Manager-> Click View next to App Name.
      Note: Enable oAuth settings should be checked to view these details.
      Thanks.

  2. In this way, the file extension is not added and there is no preview available for the document in the account (Notes & Attachments). Instead it opens in a new link.

    Is there a solution?

    1. Hi Tom,

      I am not sure I understand. The code uploads the file to attachment and attaches it to record(as given in parent_id). The preview can be seen by clicking on the file name.

  3. Thank you for providing this ! Question when you say “you need to provide the parent id of the record to which the file should be attached.” how would the POST action get this information when a user submits info in a one-time web upload?

    1. Hi Joey,

      You will have to do this in two steps:
      1. Send information to Salesforce when the user submits the form. Create the record and get the Record-Id in response.
      2. Send the file along with Record-Id to Salesforce.

      Can be done by a PHP developer.

    1. Hi SR,

      URL is typically the one that a user’s browser is redirected to after successful authorization, depending on your use.
      The redirect URI you include in your API key setup, has to match that which you provide when making your requests during the Oauth 2.0 process.

Leave a Reply

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

Scroll to top