I am trying to upload a document to this AdobeSign API endpoint
While I have found a way to do it succesfully with the RestSharp RestClient with my below code:
var client = new RestClient("https://api.na2.echosign.com/api/rest/v6/transientDocuments");
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Bearer MyIntegratorKey");
var bytes = Convert.FromBase64String(base64Document);
var contents = new MemoryStream(bytes);
request.Files.Add(new FileParameter
{
Name = "File",
Writer = (s) =>
{
var stream = contents;
stream.CopyTo(s);
stream.Dispose();
},
FileName = "Test2.pdf",
ContentType = null,
ContentLength = bytes.Length
});
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
I am having issues when I try to use the .NET HttpClient. My below code successfully upload the document (HTTP 201 returned by Adobe) but the document is completely messed up when the signers open it.
Doesn't the .NET HttpClient support file uploads ? is there something wrong with my stream ?
Thank you in advance
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = AuthenticationHeaderValue.Parse("Bearer IntegratorKey");
using (var content = new MultipartFormDataContent())
{
content.Add(new StreamContent(new MemoryStream(Convert.FromBase64String(document.EmbeddedContent))), "File", "Test2.pdf");
using (
var message =
await client.PostAsync("https://api.na2.echosign.com/api/rest/v6/transientDocuments", content))
{
var input = await message.Content.ReadAsStringAsync();
Console.WriteLine(input);
}
}
}
Related
I'm fairly new to use HTTPClient and sending REST requests to APIs, I'm currently practicing multipart upload using this Google Drive API endpoint:
POST https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart
There's an instruction that states there to split the request body into two parts, I tried to recreate this but was unable to do so.
https://developers.google.com/drive/api/guides/manage-uploads#multipart
Here's my current code:
async void UploadFile(StorageFile fileName)
{
using (HttpClient client = new HttpClient())
{
// Opens files and convert it to stream
var resultStream = await fileName.OpenReadAsync();
var fileStreamContent = new StreamContent(resultStream.AsStream());
// Create file MetaData
var fileMetaData = JsonConvert.SerializeObject(
new { name = fileName.Name, mimetype = fileName.ContentType });
// Create POST request
var requestMessage = new HttpRequestMessage(HttpMethod.Post, uploadFileEndpoint);
requestMessage.Headers.Authorization = new AuthenticationHeaderValue(tokenType, accessToken);
// Add request body
requestMessage.Content = new StringContent(fileMetaData, Encoding.UTF8, "application/json");
requestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("multipart/related");
var response = await client.SendAsync(requestMessage);
string responseString = await response.Content.ReadAsStringAsync();
output(responseString);
}
}
Any help would be greatly appreciated, thank you!
According to the documentation on Perform a multipart upload (HTTP tab), you need the MultipartFormDataContent as suggested by #Jeremy.
There are a few things needed to perform/migrate:
Add AuthenticationHeaderValue into client.DefaultRequestHeaders.Authorization.
Create a StreamContent instance, fileStreamContent (which you have done) and specify its Headers.ContentType.
Create a StringContent instance, stringContent (which you have done).
Append both StreamContent and StringContent into the MultipartFormDataContent instance, formData.
Specify the formData's Headers.ContentType as requested in API docs.
Post the formData with await client.PostAsync(/* API Url */, formData);
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(tokenType, accessToken);
// Opens files and convert it to stream
var resultStream = await fileName.OpenReadAsync();
var fileStreamContent = new StreamContent(resultStream.AsStream());
fileStreamContent.Headers.ContentType = new MediaTypeHeaderValue(fileName.ContentType);
// Create file MetaData
var fileMetaData = JsonConvert.SerializeObject(new { name = fileName.Name, mimetype = fileName.ContentType });
var stringContent = new StringContent(fileMetaData, Encoding.UTF8, "application/json");
// Create POST request
MultipartFormDataContent formData = new MultipartFormDataContent();
formData.Add(stringContent, "metadata");
formData.Add(fileStreamContent, "media");
formData.Headers.ContentType = new MediaTypeHeaderValue("multipart/related");
var response = await client.PostAsync(uploadFileEndpoint, formData);
string responseString = await response.Content.ReadAsStringAsync();
}
I am working on an angular and .NET Core application. I have to pass the file uploaded from angular to WEB API. My code is:
public async Task ImportDataScienceAnalytics(string authToken, IFormFile file)
{
var baseUrl = Import.GetBaseURL();
var client = new RestClientExtended(baseUrl + "algorithm/import");
var request = new RestRequest(Method.POST);
request.AddHeader("authorization", authToken);
string jsonBody = JsonConvert.SerializeObject(file);
request.AddJsonBody(jsonBody);
var response = await client.ExecutePostTaskAsync(request);
var result = response.Content;
}
Issue is that i get "No Attachment Found". I think the issue is because of IFormFile. How can i resolve this issue so that i can upload the file to web api.
It seems that you'd like to post uploaded file to an external API from your API action using RestClient, you can refer to the following code snippet.
var client = new RestClient(baseUrl + "algorithm/import");
var request = new RestRequest(Method.POST);
request.AddHeader("authorization", authToken);
using (var ms = new MemoryStream())
{
file.CopyTo(ms);
var fileBytes = ms.ToArray();
request.AddFile("file", fileBytes, file.FileName, "application/octet-stream");
}
//...
Testing code of Import action
public IActionResult Import(IFormFile file)
{
//...
//code logic here
You need to make following changes to the code.
var baseUrl = Import.GetBaseURL();
var client = new RestClientExtended(baseUrl + "algorithm/import");
var request = new RestRequest(Method.POST);
byte[] data;
using (var br = new BinaryReader(file.OpenReadStream()))
data = br.ReadBytes((int)file.OpenReadStream().Length);
ByteArrayContent bytes = new ByteArrayContent(data);
MultipartFormDataContent multiContent = new MultipartFormDataContent
{
{ bytes, "file", file.FileName }
};
//request.AddHeader("authorization", authToken);
//string jsonBody = JsonConvert.SerializeObject(file);
//request.AddJsonBody(jsonBody);
/// Pass the multiContent into below post
var response = await client.ExecutePostTaskAsync(request);
var result = response.Content;
Do not forget to pass the variable multiContent into the post call.
I need to post a file from asp application to an API
the file will be uploaded through <asp:FileUpload />
in the back end, i will receive the file and send it to Web API method
the web API method will contain the code
var root = HttpContext.Current.Server.MapPath("~/App_Data/Uploadfiles");
var provider = new MultipartFormDataStreamProvider(root);
var result = await Request.Content.ReadAsMultipartAsync(provider);
the asp page will has the code
using (System.IO.Stream fs = fuID.PostedFile.InputStream)
{
System.IO.BinaryReader br = new System.IO.BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);
string base64String = Convert.ToBase64String(bytes, 0, bytes.Length);
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("POST"), "http://localhost:5000/path"))
{
request.Headers.TryAddWithoutValidation("Accept", "application/json, text/plain, */*");
request.Headers.TryAddWithoutValidation("Authorization", "Bearer " + AppUserContext.Token);
request.Headers.TryAddWithoutValidation("x-language", "ar");
// Iam Not Sure of this line
request.Content = new StringContent("Content-Disposition:" + base64String, Encoding.UTF8, "multipart/form-data");
var response = httpClient.SendAsync(request).Result;
}
}
}
i need to know how i can send the file in the body of the request what to write in this line
request.Content = new StringContent("Content-Disposition:" + base64String, Encoding.UTF8, "multipart/form-data");
pf is the posted file
then use
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AppUserContext.Token);
client.DefaultRequestHeaders.Add("x-language", "ar");
using (var stream = pf.InputStream)
{
var content = new MultipartFormDataContent();
var file_content = new ByteArrayContent(new StreamContent(stream).ReadAsByteArrayAsync().Result);
file_content.Headers.ContentType = new MediaTypeHeaderValue(pf.ContentType);
file_content.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
FileName = JsonConvert.SerializeObject(pf.FileName),
};
content.Add(file_content);
var url = "URL Here";
var response = client.PostAsync(url, content).Result;
response.EnsureSuccessStatusCode();
}
}
I was Uploaded Text file or image file or Zip File to Azure Data Lake Store. it' was Uploaded Successfully. But, before added some content in file.
I was Uploaded a File using Rest API. (Uploaded file using HttpClient in C#)
this Type of Content Added in
---b8b2dfc6-6128-43b5-8fb8-022820aedf02
Content-Disposition: form-data;
name=file1; filename=tick.txt; filename*=utf-8''tick.txt
If the Content Added So, The Image file and zip files are Not Open in Viewer/Explore.
How To Remove this type of header added in file From Upload.Here I shared my file uploaded code.
public object UploadFile(string srcfile, string destFilePath, bool force = true)
{
var uploadurl = string.Format(UploadUrl, _datalakeAccountName, destFilePath);
var stream = File.OpenRead(srcfile);
HttpContent fileStreamContent = new StreamContent(stream);
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _accesstoken.access_token);
using (var formData = new MultipartFormDataContent())
{
formData.Add(fileStreamContent, "file1", Path.GetFileName(srcfile));
var response = client.PutAsync(uploadurl, formData).Result;
return new { Status = response.StatusCode, Message = response.ReasonPhrase, details = response.ToString() };
}
}
}
Thanks in Advance.
Please have try to use the following code, it works correcly on my side.
public object UploadFile(string srcfile, string destFilePath, bool force = true)
{
var uploadurl = string.Format(UploadUrl, _datalakeAccountName, destFilePath);
var stream = File.OpenRead(srcfile);
HttpContent fileStreamContent = new StreamContent(stream);
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new
AuthenticationHeaderValue("Bearer", _accesstoken.access_token);
client.DefaultRequestHeaders
.Accept
.Add(new MediaTypeWithQualityHeaderValue("application/octet-stream"));
var response = client.PutAsync(uploadurl, fileStreamContent).Result;
return new { Status = response.StatusCode, Message = response.ReasonPhrase, details = response.ToString() };
}
}
I am struggling to use the Gfytcat API to upload an mp4 from my machine. Maybe it's just me but the API docs don't seem very well fleshed out.
The following code successfully requests a new gfy, but fails the upload with the following error: 204: No Content.
using (var client = new HttpClient())
{
var response = await client.PostAsync(#"https://api.gfycat.com/v1/gfycats", null);
var responseString = await response.Content.ReadAsStringAsync();
var newGfycatResponse = Newtonsoft.Json.JsonConvert.DeserializeObject<NewGfycatResponse>(responseString);
Console.WriteLine("gfyname: " + newGfycatResponse.gfyname);
Console.WriteLine("secret: " + newGfycatResponse.secret);
var filePath = #"C:\Users\Julien\Videos\black cat jumping.mp4";
var file = File.ReadAllBytes(filePath);
using (var content = new MultipartFormDataContent())
{
content.Add(new StringContent(newGfycatResponse.gfyname), "key");
content.Add(new ByteArrayContent(file), "file", newGfycatResponse.gfyname);
using (var message = await client.PostAsync("https://filedrop.gfycat.com", content))
{
var input = await message.Content.ReadAsStringAsync();
Console.WriteLine(input);
}
}
}
Looks like the below line is incorrect. You have to name the field "file", you are naming it as the name of the file.
content.Add(new StreamContent(new MemoryStream(file)), "file", newGfycatResponse.gfyname);
**** edits
You may want to modify the headers on that file content as below.
below is taken from: ASP.NET WebApi: how to perform a multipart post with file upload using WebApi HttpClient
var fileContent = new ByteArrayContent(System.IO.File.ReadAllBytes(fileName));
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "Foo.txt"
};
content.Add(fileContent);