Skip to main content
Answer

Rest API - File Creation from Code Level

  • May 17, 2024
  • 6 replies
  • 109 views

Forum|alt.badge.img

Hello Everyone,

I have requirement to pick the file from local path and attach a file using REST API from code level to the Sales Order. Can you please share the sample example for the same?

Best answer by Naveen Boga

@nsmith51  Here is the sample code for reference. Hope this helps!

 


RestClient client1 = new RestClient("http://localhost/23R2/entity/Default/23.200.001/");
RestRequest updateRequest = new RestRequest("StockItem/" + stock.InventoryID + "/files/" + stock.FileName, Method.Put);
updateRequest.AddHeader("Authorization", "Bearer " + authToken);
string filePath = @stock.Path;
//string filePath = @"D:\Test Key.txt";
byte[] fileData = File.ReadAllBytes(filePath);
updateRequest.AddParameter("image/png", fileData, ParameterType.RequestBody);
RestResponse updateResponse = await client1.ExecuteAsync(updateRequest);
if (updateResponse.IsSuccessful)
{
//logic here
}

 

6 replies

Forum|alt.badge.img+7
  • Captain II
  • May 17, 2024

This Acumatica Dev Blog post is commonly referenced:

https://asiablog.acumatica.com/2018/01/attach-files-with-rest-api.html

The body of the request will be the binary representation of the file. Then you PUT the request to the entity that you want to attach the file to.


Forum|alt.badge.img
  • Author
  • Jr Varsity III
  • May 17, 2024

@Django Do you have an example of code sample?


Forum|alt.badge.img+7
  • Captain II
  • May 17, 2024

I don’t have code to share, unfortunately. But from what I can see, there’s nothing specific to Acumatica’s framework that you need in this case.

Are you having trouble with how to turn the file into a binary representation? If so, I think you can just do something like this:

  byte[] byteArray = File.ReadAllBytes(@"Path to your local file");

Or are you looking for the code to write the put request?


  • Freshman II
  • May 17, 2024

@nsmith51 That’s going to vary depending on what language you’re using.


Naveen Boga
Captain II
Forum|alt.badge.img+19
  • Captain II
  • Answer
  • May 19, 2024

@nsmith51  Here is the sample code for reference. Hope this helps!

 


RestClient client1 = new RestClient("http://localhost/23R2/entity/Default/23.200.001/");
RestRequest updateRequest = new RestRequest("StockItem/" + stock.InventoryID + "/files/" + stock.FileName, Method.Put);
updateRequest.AddHeader("Authorization", "Bearer " + authToken);
string filePath = @stock.Path;
//string filePath = @"D:\Test Key.txt";
byte[] fileData = File.ReadAllBytes(filePath);
updateRequest.AddParameter("image/png", fileData, ParameterType.RequestBody);
RestResponse updateResponse = await client1.ExecuteAsync(updateRequest);
if (updateResponse.IsSuccessful)
{
//logic here
}

 


Forum|alt.badge.img
  • Author
  • Jr Varsity III
  • May 19, 2024

Thanks @Naveen Boga for sharing the sample code.