0

I'm a beginner in Salesforce and I appreciate if anyone can help me. I just want to upload a .pdf file in Salesforce documnent using C# console application. Which works perfectly using this code:

var doc = new sfdcDocument();
doc.Name = "My Personal Documents";
doc.FolderId = "xxxxxxxxxxxxxxxx";          //FolderID of Salesforce folder in which document get uploaded.

string boundary = "----" + DateTime.Now.Ticks.ToString("x");

var uri = instanceURL + "/services/data/v24.0/sobjects/Document/";
var req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(uri);
req.Headers.Add("Authorization: OAuth " + accessToken);
req.ContentType = "multipart/form-data; boundary=" + boundary;
req.Method = "POST";
var os = req.GetRequestStream();

// Add header for JSON part
string body = "";
body += "\r\n--" + boundary + "\r\n";
body += "Content-Disposition: form-data; name='entity_document'\r\n";
body += "Content-Type: application/json\r\n\r\n";

// Add document object data in JSON
var ser = new JavaScriptSerializer();
body += ser.Serialize(doc);

// Add header for binary part 
body += "\r\n--" + boundary + "\r\n";
body += "Content-Disposition: form-data; name='Body'; filename='test.pdf'\r\n";
body += "Content-Type: binary/octet-stream\r\n\r\n";

// Add header data to request
byte[] data = System.Text.Encoding.ASCII.GetBytes(body);
os.Write(data, 0, data.Length);

// Add file to reqeust
FileStream fileStream = new FileStream(@"C:\test.pdf", FileMode.Open, FileAccess.Read);
byte[] buffer = new byte[4096];
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
     os.Write(buffer, 0, bytesRead);
}
fileStream.Close();

// Add trailer
byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
os.Write(trailer, 0, trailer.Length);
os.Close();

// Do the post and get the response.
WebResponse resp;

try
{
    resp = req.GetResponse();
}
catch (WebException ex)
{
    resp = ex.Response;
}

if (resp == null) { Console.WriteLine("error!!!!!"); }
var sr = new System.IO.StreamReader(resp.GetResponseStream());

but my Problem is Not getting file name and its extension after file uploaded in Salesforce document.

I followed this URL - http://danlb.blogspot.in/2012/06/salesforce-rest-api-file-upload.html

Image Description of Problem

Any suggestion, Thanks.

2
  • try this @utkarsh, Document doc = new Document(); Commented May 1, 2017 at 10:35
  • WebException ex line show this error - The remote server returned an error: (400) Bad Request.. After adding Document doc = new Document();. Commented May 1, 2017 at 10:44

1 Answer 1

1

After adding this line of code:

var doc = new sfdcDocument();
doc.Name = "test";
doc.FolderId = "xxxxxxxxxx";          //FolderID of Salesforce folder in which document get uploaded.
doc.Type = "pdf";

It works for me, Thanks.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .