Uploading .mp4 via HTTPS - c#

I'm trying to upload an .mp4 file to Giphy.com's API. It says to send the file over as 'Binary' and I think I'm confused as what exactly they mean by that. Here's the docs if you scroll to the bottom at "Upload Endpoint". https://developers.giphy.com/docs/
Here's what I have right now.
I've tried multiple versions of this (using StringContent, MultipartFormDataContent, ByteArrayContent, HttpMessages... etc) and always get a '400 - Bad Request - No Source Url' (which the docs say isn't required if you upload you're own) which makes me believe the content isn't being recognized.
public async Task<HttpResponseMessage> UploadVideoAsync(StorageFile file)
{
using (var stream = await file.OpenStreamForReadAsync())
{
byte[] bytes = new byte[stream.Length];
await stream.ReadAsync(bytes, 0, (int)stream.Length);
Dictionary<string, string> dic = new Dictionary<string, string>
{
{ "file", Encoding.ASCII.GetString(bytes) },
{ "api_key", api_key }
};
MultipartFormDataContent multipartContent = new MultipartFormDataContent();
multipartContent.Add(new ByteArrayContent(bytes));
var response = await httpClient.PostAsync($"v1/gifs?api_key={api_key}", multipartContent);
var stringResponse = await response.Content.ReadAsStringAsync();
return response;
}
}

It seems that your code doesn't match {api_key} properly. You don't use the "dic" variable anywhere. You can try with v1/gifs?api_key=YOUR_API_KEY&file= instead. Where YOUR_API_KEY should be replaced by your API key obtained from giphy.

always get a '400 - Bad Request - No Source Url' (which the docs say isn't required if you upload you're own) which makes me believe the content isn't being recognized.
You need to apply a name for the ByteArrayContent. The document has shown that Request Parameters contains 'file: string (binary) required if no source_image_url supplied'.
The code should like the following:
MultipartFormDataContent multipartContent = new MultipartFormDataContent();
multipartContent.Add(new ByteArrayContent(bytes),"file");

Related

How to send File Object to Web api using POST call in Xamarin forms.?

I need to make a POST call from my Xamarin forms app where I need to upload a file object as it is to API using POST Call. Is there any way to make it possible?
if you send file object using Base64 or Byte[] then it will allowed only limited may be upto 2-4 Mb but if you have a larger image than that it will not support.
So, Solution is Post Stream Content Like,
var file = await CrossMedia.Current.PickPhotoAsync(new PickMediaOptions
{
PhotoSize = PhotoSize.Full,
CompressionQuality = 100
});
Create Object of MediaFile like, public MediaFile AttachedImage; and Store file into it so Memory stream will not lost. Like,AttachedImage = file
Post Code on API,
HttpClient httpClient = new HttpClient();
MultipartFormDataContent mt = new MultipartFormDataContent();
AttachedImage.GetStream().Position = 0;
StreamContent imagePart = new StreamContent(AttachedImage.GetStream());
imagePart.Headers.Add("Content-Type", ImageType);
mt.Add(imagePart, String.Format("file"), String.Format("bk.jpeg"));
requestMessage.Content = mt;
var response = await httpClient.PostAsync("Your URL", mt);
if (response.IsSuccessStatusCode)
{
var responseString = await response.Content.ReadAsStringAsync();
var objRootObjectuploadImage = JsonConvert.DeserializeObject<RootObjectuploadImage>(responseString);
if (objRootObjectuploadImage != null)
{
}
else
{
}
}
else
{
Loading(ActIndicator, false);
await DisplayAlert(res.LAlert, "webserver not responding.", res.LOk);
}
NO, it is not possible to send file object. You can send as a json by converting the file in the Base64 string. This is the advised proven solution. This link has code for converting back and forth from Base64.

Microsoft Cognitive Services Vision API: Sending multipart data

I am trying to call the Microsoft Cognitive API by passing multiple images as per documentation and using the multipart/form-data, but I am getting an error that says "Unsupported Media Type". I have tried to use both ByteArray and StreamContent.
Api documentation.
private static byte[] GetImageAsByteArray(Stream fileStream)
{
using (var binaryReader = new BinaryReader(fileStream))
{
return binaryReader.ReadBytes((int)fileStream.Length);
}
}
static void Main(string[] args)
{
var uriBase = "https://westus.api.cognitive.microsoft.com/vision/v1.0/recognizeText";
var subscriptionKey = "<subscriptionKey>";
var client = new HttpClient();
var uri = string.Concat(uriBase, "?", "language=en&detectOrientation=true");
var images = new List<Stream>();
var img = Image.FromStream(File.Open("<imageName>", FileMode.Open));
var stream = new MemoryStream();
img.Save(stream, ImageFormat.Bmp);
stream.Position = 0;
images.Add(stream);
using (var content = new MultipartFormDataContent())
{
foreach (var image in images)
{
//content.Add(new StreamContent(stream));
content.Add(new ByteArrayContent(GetImageAsByteArray(image)));
}
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", subscriptionKey);
content.Headers.ContentType = new MediaTypeHeaderValue("multipart/form-data");
var response = client.PostAsync(uri, content).Result;
}
}
I am trying to call the Microsoft Cognitive API by passing multiple images as per documentation and using the multipart/form-data, but I am getting an error that says "Unsupported Media Type".
It is not possible to send multiple images, regardless of header.
Please refer to the documentation Step 2, it mentions:
The basic way to perform the Computer Vision API call is by uploading an image directly. This is done by sending a "POST" request with application/octet-stream content type together with the data read from the image.
Example code can be found here
Test environment here.
Notice regardless of header, it is still sending 1 image.
The limits also mention a single image.

Upload Reference File to Content ID

Has anyone attempted to do this? From what I understand Google doesn't provide a .NET client library for this (the only examples I found were in Python and PHP). The difficulty I'm having is that it seems to want a file upload and a JSON request body in the same request. Any info would be appreciated.
I was able to figure it out. In .NET (using HttpClient), you can use
using (MultipartFormDataContent content = new MultipartFormDataContent("----------" + DateTime.Now.ToString(CultureInfo.InvariantCulture)))
{
content.Add(new StringContent(JsonConvert.SerializeObject(uploadReferenceRequest), Encoding.UTF8, "application/json"));
StreamContent audioContent = new StreamContent(new MemoryStream(buffer));
audioContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
content.Add(audioContent);
using (HttpResponseMessage response = await this.Client.PostAsync(url, content))
{
string responseContent = await response.Content.ReadAsStringAsync();
}
}
The key is to set the content type on each section of data, on the first is the "application/json" and the actual sound data is "application/octet-stream". Hope someone else finds this useful.

.NET Core 1.0 read form-data posted file and put it in MultipartFormDataContent

I'm trying to fetch form-data sent to .NET Core API. The aim is to redirect the post request to another API.
I don't want the file to be stored locally but only "transmitted" again in a request.
Here is the code I'm trying.
MultipartFormDataContent multipartContent = new MultipartFormDataContent();
multipartContent.Add(new StringContent(Request.Form["id"]), "id");
var file = Request.Form.Files[0];
if (file.Length > 0)
{
var fileStreamContent = new StreamContent(Request.Form.Files[0].OpenReadStream());
multipartContent.Add(fileStreamContent, Request.Form.Files[0].FileName);
client.BaseAddress = new Uri("http://example.com:8000");
client.DefaultRequestHeaders.Accept.Clear();
HttpResponseMessage response = await client.PostAsync("/document/upload", multipartContent);
if (response.IsSuccessStatusCode)
{
retValue = await response.Content.ReadAsAsync<DocumentUploadResult>();
}
}
It seems Request.Form.Files[0].OpenReadStream() doesn't work, as the request received by remote api is empty. The openReadStream was suggested by VS2015 as the former .FileStream i used before .NET Core seems not to be present anymore.
Is my idea to try to create a StreamContent from the file actually a good idea? Is there any better type I could use to transmit my file accepted by MultripartFormDataContent?
In order to read a file from a form post, have your Action accept an IFormFile parameter:
public async Task<IActionResult> UploadFile(IFormFile file){
byte[] bytes = new byte[file.Length];
using (var reader = file.OpenReadStream())
{
await reader.ReadAsync(bytes, 0, (int)file.Length);
}
}

Posting multiple binary files in a single POST with httpclient?

How would one post multiple binaries in a single http POST operation using C# httpclient? I can't seem to find information on how to deal with httpcontent in this way - just doing a postASync with stream data twice?
Dug around a bit more and experimented, and finally found what seems like a working solution. I tried this on a test server with some images on HD - both sent, both worked. With two stream examples.
var client = new HttpClient();
var stream3 = new FileStream("saved.jpg", FileMode.Open);
var stream2 = new FileStream("saved2.jpg", FileMode.Open);
var dic = new Dictionary<string, string>();
dic.Add("Test1", "This was the first test.");
var addy = "http://posttestserver.com/post.php";
using (var content = new MultipartFormDataContent())
{
content.Add(new StreamContent(stream2), "s1", "Saved1.jpg");
content.Add(new StreamContent(stream3), "s2", "Saved2.jpg");
var response = await client.PostAsync(addy, content);
response.EnsureSuccessStatusCode();
string finalresults = await response.Content.ReadAsStringAsync();
}
It will depend on the implementation of the API that you are sending your files to but typically if multiple files are sent in a single POST request then it is sent as multipart/form-data. Have a look at this post for sending multipart/form-data through HttpClient.

Categories