Sending byte array in asp .net web api - asp.net-web-api

I am creating a web api to allow download files through POST. There is no need for UI. I am sending Byte array along with the Filename in a JSON as follows.
{
"FileName": "xxxyyyzzz.pdf",
"FileType": "Pricing",
"FileID": 12457,
"ContentInByteArray":
"JVBERi0xLjMNCiXi48QoNCnN0YXJ0eHJlZg0KMjcxNA0KJSVFT0YNCg==",
"ExceptionMessage": ""
}
The File content is actually converted into Byte array and set to "ContentInByteArray". Is this a good approach. Or Do I need any improvisation.
Please suggest.

You use send byte[] array when you need post file or image content or may be token content and handle them at API.
var request = new SomePostRequest
{
Id = 1,
Content = File.ReadAllBytes(filename); // read content file to byte[]
};
jsonSerializer.Serialize(bson, request);
var client = new HttpClient
{
BaseAddress = new Uri("http://www.server.com")
};
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/bson"));
var byteArrayContent = new ByteArrayContent(stream.ToArray());
byteArrayContent.Headers.ContentType = new MediaTypeHeaderValue("application/bson");
var result = await client.PostAsync(
"api/upload", byteArrayContent);

Related

Attaching zip file is not working in WEB API, but works via POSTMAN

I have an .net core WEB API method that needs to call another external API (java) which expects .zip file. When try to access the external API via Postman by attaching the file, it is working fine (getting expected response). However when i pass the same parameters via my WEB API code, it is throwing 403-Forbidden error.
Please let me know if i am missing anything....
Thanks in advance!!!
request-header
request-body-file-attached
response-403-error
API code: for connecting to api:
Dictionary<string, string> parameters = new Dictionary<string, string>();
parameters.Add("pane", "forward");
parameters.Add("forward_path", "/store/execute");
parameters.Add("csrf", "1996fe6b2d0c97a8a0db725a10432d83");
parameters.Add("data_format", "binary");
newContent = new FormUrlEncodedContent(parameters);
MultipartFormDataContent form = new MultipartFormDataContent();
HttpContent con;// = new StringContent("file_name");
//form.Add(con, "file_name");
form.Add(newContent);
var str = new FileStream("D:\\dummy\\xmlstore.zip", FileMode.Open);
con = new StreamContent(str);
con.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = "file_name",
FileName = "xmlstore.zip"
};
con.Headers.ContentType = new MediaTypeHeaderValue("application/zip");
form.Add(con);
client.DefaultRequestHeaders.Add("Cookie", "JSESSIONID=05DEB277E294CBF73288F2E24682C7EE;");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/html"));
client.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip"));
client.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("deflate"));
client.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("br"));
client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("user-agent", "1"));
var resp = client.PostAsync("java-api", con).Result;

How do I send a base64 encoded PDF file?

I want my bot to send a PDF file to the user. I have the PDF as a base64 string and tried to send it through an attachment:
Attachment attachment1 = new Attachment();
attachment1.Name = "name.pdf";
attachment1.ContentType = "application/pdf";
attachment1.ContentUrl = "data:application/pdf;base64," + base64String;
var m = context.MakeMessage();
m.Attachments.Add(attachment1);
m.Text = "File";
await context.PostAsync(m);
Within the emulator, it just doesn't work but in the channels Telegram and Facebook (which I need), the bot just outputs an error...
Has someone already succeed in it?
Note: Using an HTTP address works fine, but I need to use the base64 string
As this method in botframework call sendDocument method of Telegram, and this method in its document property get http url or a file_id, so you can't pass base64String to this method as a valid document type.
You can follow the valid type of the document passing into the telegram in this link (also, see the following image).
The pdf file must be embedded resource. Hope it help.
if (this.channelid == "telegram")
{
var url = string.Format("https://api.telegram.org/bot{0}/sendDocument", Settings.tokentelegram);
Assembly _assembly;
Stream file;
using (var form = new MultipartFormDataContent())
{
form.Add(new StringContent(this.chat_id, Encoding.UTF8), "chat_id");
_assembly = Assembly.GetExecutingAssembly();
file = _assembly.GetManifestResourceStream("Namespace.FolderResourses.name.pdf");
form.Add(new StreamContent(file), "document", "name.pdf");
using (var client = new HttpClient())
{
await client.PostAsync(url, form);
}
}
}

Web API - Setting Response.Content with byte[] / MemoryStream Contents not working properly

My requirement is to use Web API to send across the network, a zip file (consisting a bunch of files in turn) which should not be written anywhere locally (not written anywhere on the server/client disk). For zipping, I am using DotNetZip - Ionic.Zip.dll
Code at Server:
public async Task<IHttpActionResult> GenerateZip(Dictionary<string, StringBuilder> fileList)
{
// fileList is actually a dictionary of “FileName”,”FileContent”
byte[] data;
using (ZipFile zip = new ZipFile())
{
foreach (var item in filelist.ToArray())
{
zip.AddEntry(item.Key, item.Value.ToString());
}
using (MemoryStream ms = new MemoryStream())
{
zip.Save(ms);
data = ms.ToArray();
}
}
var result = new HttpResponseMessage(HttpStatusCode.OK);
MemoryStream streams = new MemoryStream(data);
//, 0, data.Length-1, true, false);
streams.Position = 0;
//Encoding UTFEncode = new UTF8Encoding();
//string res = UTFEncode.GetString(data);
//result.Content = new StringContent(res, Encoding.UTF8, "application/zip");
<result.Content = new StreamContent(streams);
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/zip");
//result.Content.Headers.ContentLength = data.Length;
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
result.Content.Headers.ContentDisposition.FileName = "test.zip";
return this.Ok(result);
}
The issue I am facing is that after the zip file downloaded at client end when modified as a test.bin has its stream contents (byte[] data in this example’s contents) missing. (I am getting back a test.zip file. When I change the file locally from test.zip to test.bin, I am seeing that the File’s contents as shown below. It does not contain the Response.Content values. P.S. I have also tried the MIME type “application/octet-stream” as well. No luck!)
Test.zip aka test.bin’s contents:
{"version":{"major":1,"minor":1,"build":-1,"revision":-1,"majorRevision":-1,"minorRevision":-1},
"content":{"headers":[{"key":"Content-Type","value":["application/zip"]},
{"key":"Content-Disposition","value":["attachment; filename=test.zip"]}]},
"statusCode":200,"reasonPhrase":"OK","headers":[],"isSuccessStatusCode":true}
Can someone please help me on how we can set result.Content with a MemoryStream object (I have seen example of “FileStream” at other places on google to set “result.Content” but I want to use MemoryStream object only!). I am highlighting this because I think the problem lies with setting the MemoryStream object to the result.Content (in order to properly save the streams content into the result.Content object)
P.S. I have also gone thru Uploading/Downloading Byte Arrays with AngularJS and ASP.NET Web API (and a bunch of other links) but it did not help me much… :(
Any help is greatly appreciated. Thanks a lot in advance :)
I got my issue solved!!
All I did was to change the Response Type to HttpResponseMessage and use "return result" in the last line rather than Ok(result) { i.e. HttpResponseMessage Type rather than OKNegiotatedContentResult Type)

image upload to server in windows phone8 app

I want to upload an image from the gallery or live pic (camera capture task) with some params; x = "some string", y = "some string", z = "some integer" and uploadimage = name of file tag in form.
Can anyone please help me?
Uploading image for WP8 was pain to setup. Many of the examples I follow was outdated and this took me days to research and finally got one to work. There are a few ways to upload:
1) Convert the image to a string and then you can send the image converted string via HTTP request. I've used this approach for Android, but haven't tried it for WP.
2) Upload the image via FTP and the text data via HTTP.
You have 3 choices to upload any File to server.
Convert file into Stream - recommend way
Convert file into ByteArray
Convert file into String
After that you can use HttpClient package make a POST request to server. Here is the code to demonstrate FileUpload by converting it into Stream.
Code:
public async void methodToUploadFile()
{
StorageFile file = await StorageFile.GetFileFromPathAsync("Assets/MyImage.png");
// var fileBytes = await GetBytesAsync(file);
HttpClient client = new HttpClient();
// give the server URI here
Uri requestUri = new Uri("Full Server URI", UriKind.Absolute);
MultipartFormDataContent formdata = new MultipartFormDataContent();
formdata.Add(new StringContent("some string"), "x");
formdata.Add(new StringContent("some string"), "y");
formdata.Add(new StringContent("some integer"), "z");
formdata.Add(new StreamContent(await file.OpenStreamForReadAsync()), "file", "MyImage.png");
// formdata.Add(new ByteArrayContent(fileBytes), "file", "MyImage.png");
// Make a POST request here
var res = await client.PostAsync(requestUri, formdata);
}
Hope this helps..!

wp7 - twitter photo upload

We are trying to upload image to Twitter via silverlight code in WP7. We are able to post the message but not the image.
We tried all including download of their library but not getting the hint.
In following link,
https://dev.twitter.com/docs/api/1/post/statuses/update_with_media
there is one point which we are not able to set.
"Unlike POST statuses/update, this method expects raw multipart data. Your POST request's Content-Type should be set to multipart/form-data with the media[] parameter "
I am not getting it how to put it.
Can anyone please guide me or provide sample for image upload?
If your photo is called LoadedPhoto, you could create a memory stream from it
MemoryStream ms = new MemoryStream();
LoadedPhoto.SaveJpeg(ms, LoadedPhoto.PixelWidth, LoadedPhoto.PixelHeight, 0, 100);
Create OAuthCredentials object according to the authentication details you have acquired
var credentials = new OAuthCredentials
{
Type = OAuthType.ProtectedResource,
SignatureMethod = OAuthSignatureMethod.HmacSha1,
ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
ConsumerKey = Common.TwitterSettings.ConsumerKey,
ConsumerSecret = Common.TwitterSettings.ConsumerKeySecret,
Token = file.AccessToken,
TokenSecret = file.AccessTokenSecret,
Version = "1.0"
};
Create a RestClient and a RestRequest
var restClient = new RestClient
{
Authority = "https://upload.twitter.com"
};
var restRequest = new RestRequest
{
Credentials = credentials,
Path = "/1/statuses/update_with_media.xml",
Method = Hammock.Web.WebMethod.Post
};
Set the stream position to 0
ms.Position = 0;
Add fields to RestRequest
restRequest.AddField("status", message);
restRequest.AddFile("media[]", "ScreenShot.png", ms, "image/jpeg");
And then begin request
restClient.BeginRequest(restRequest, callback);
callback is a callback method for the request.
Taken from my blog post, see there for more details if you're interested.

Resources