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);
Related
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);
}
}
}
Am uploading a document to HTTP Trigger Azure function(Version 2). On receiving the request in my function I see the Files section empty and stream is moved to formdata dictionary. Below is the code how am uploading the document, could someone help me why its not populating the stream in IFormFileCollection.
using (var _httpClient = new HttpClient())
{
MultipartFormDataContent form = new MultipartFormDataContent();
String headerValue = "form-data; name=\"file\"; filename=\"" + fileName + "\"";
byte[] bytes = Encoding.UTF8.GetBytes(headerValue);
headerValue = Encoding.UTF8.GetString(bytes, 0, bytes.Length);
fileContent.Headers.Add("Content-Disposition", headerValue);
fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
form.Add(fileContent);
form.Add(new StringContent(metadataValue), metadataKey);
_httpClient.Timeout = TimeSpan.FromMinutes(15);
_httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + bearerToken);
logger.LogInformation($"HttpUtils: UploadFileByMultipart() url:{url}, request param: {metadataValue} reference: {traceLogId}");
var response = await _httpClient.PostAsync(url, form).Result.Content.ReadAsStringAsync();
logger.LogInformation("HttpUtils: UploadFileByMultipart() end");
return response;
}
Content received in Function
Other note how do take the stream from the Formdata dictionary which is in string format and convert to stream which I can play around. I tried below and the resultant is a blank doc, corrupting all the stream
requestHandler.stream = new MemoryStream();
var Content = formdata["file"].ToString();
var fileContent = new MemoryStream(Encoding.ASCII.GetBytes(Content));
If we want to send Multipart Data with HttpClient, you can use MultipartFormDataContent to create data.
For example
The code I send request
MultipartFormDataContent form = new MultipartFormDataContent();
form.Add(new StringContent("jack"), "userName");
var fileContent = new ByteArrayContent(File.ReadAllBytes(#"D:\my.csv"));
// I use package MimeMapping : https://www.nuget.org/packages/MimeMapping/ to get file mine type
fileContent.Headers.ContentType = new MediaTypeHeaderValue(MimeUtility.GetMimeMapping("my.csv"));
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = "file",
FileName = "my.csv"
};
form.Add(fileContent);
using (var client = new HttpClient())
{
var res = await client.PostAsync("<function app url>", form);
if (res.IsSuccessStatusCode)
{
var content = await res.Content.ReadAsStringAsync();
Console.WriteLine(content);
}
}
My function app code
using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;
public static async Task<IActionResult> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
log.LogInformation("-------------------read file----------------------");
// read file
var files = req.Form.Files;
if (files.Count != 0) {
var file = files[0];
log.LogInformation(file.ContentType);
log.LogInformation(file.FileName);
log.LogInformation(file.ContentDisposition);
// use file.OpenReadStream to get a stream then use stream to rread file content
}
// read key
log.LogInformation("-------------------read key----------------------");
log.LogInformation($"The userName is {req.Form["userName"]}");
return new OkObjectResult("OK");
}
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.
We have a requirement of sending the jpeg files of a given directory to a Xamarin App.
Following is the code in the Web API.
public HttpResponseMessage DownloadMutipleFiles()
{
name = "DirectoryName";
var content = new MultipartContent();
var ids = new List<int> { 1,2};
var objectContent = new ObjectContent<List<int>>(ids, new System.Net.Http.Formatting.JsonMediaTypeFormatter());
content.Add(objectContent);
var file1Content = new StreamContent(new FileStream(#"D:\Photos\" + name+"\\"+ "BL1408037_20191031124058_0.jpg", FileMode.Open));
file1Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("image/jpeg");
content.Add(file1Content);
var file2Content = new StreamContent(new FileStream(#"D:\Photos\" + name + "\\" + "BL1408037_20191031124058_1.jpg", FileMode.Open));
file2Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("image/jpeg");
content.Add(file2Content);
var response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = content;
return response;
}
Can some one help out with how to read from Xamarin app? Thanks in advance
This is the function I was able to use to send an image as a multi part data file! I just took the byte array given to me by the Xamarin Essentials image picker and passed it into this function:
public async Task SubmitImage(byte[] image, string imageName)
{
using (var client = new HttpClient())
{
string url = $"..."; // URL goes here
var token = Preferences.Get("AccessToken", "");
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
var stream = new MemoryStream(image);
var content = new StreamContent(stream);
//Without a name we can't actually put the file in IFormFile. We need the equivalent
//"name" value to be "file" (used if you upload via an <input> tag). We could call it
//anything but file is simple
content.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
FileName = imageName,
Name = "file"
};
content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
var multipartContent = new MultipartFormDataContent();
multipartContent.Add(content);
var result = await client.PostAsync(url, multipartContent);
}
}
You can test this using a console application as well and just send over a picture from your computer, instead of doing this through the app
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() };
}
}