Sending Image from C# to Android via JSON - c#

I have images stored in SQL server, and I want to send them to Android app via JSON with other data. What's the best way to do this?
BTW my server side written in ASP Web API(C#).
In other way I want to make my image like this http://myserver/image.jpg
so I can included in my JSON and download it in Android app.

As its not where clear from your question, This Link is the best what I can find for you. In it he is accessing ASP.NET WebAPI and converting all the things to JSON when access or pass it through the Andriod studio
http://hintdesk.com/how-to-call-asp-net-web-api-service-from-android/
and here is a complete series that can help you more
http://www.tutecentral.com/restful-api-for-android-part-1/
Hope this helps

I finally figure it out
This is the code
public HttpResponseMessage getImage(String name)
{
name = name + ".png";
var result = new HttpResponseMessage(HttpStatusCode.OK);
String filePath = HostingEnvironment.MapPath("~/images/"+name);
FileStream fileStream = new FileStream(filePath, FileMode.Open);
Image image = Image.FromStream(fileStream);
MemoryStream memoryStream = new MemoryStream();
image.Save(memoryStream, ImageFormat.Jpeg);
result.Content = new ByteArrayContent(memoryStream.ToArray());
result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
fileStream.Dispose();
return result;
}

Related

Form Recognizer SDK, analyze with custom model, file stream issue

When I'm trying to analyze a pdf document using FileStream from a local file, everything works fine.
But when I use a IFormFile and use method OpenReadStream() and pass that stream to the Analyze method for form analyzer, i get an exception. I also tried creating a new stream out of the IFromFile stream and that did not work either.
Any help will be much appreciated. Thank you
Working code:
using var stream = new FileStream("D:\\somefile.pdf", FileMode.Open);
var result = await _formRecognizerClient.AnalyzeWithCustomModelAsync(modelId, fileStream, "application/pdf");
Code I am trying to make work:
using var stream = file.OpenReadStream(); // file is an IFormFile
var result = await _formRecognizerClient.AnalyzeWithCustomModelAsync(modelId, stream , file.ContentType);
I have a solution for now, its not elegant but it works. I am of course very much looking for something better if anyone can help.
For now, I am creating a file, saving it and creating a FileStream out of it. Also works in docker as I'm testing using docker-compose
var iFormFileStream = file.OpenReadStream();
var stream = File.Create(string.Format("tempfilename.pdf", File.));
stream.Seek(0, SeekOrigin.Begin);
stream.CopyTo(stream);
stream.Close();
using var fileStream = new FileStream("tempfilename.pdf", FileMode.Open);
var result = await _formRecognizerClient.AnalyzeWithCustomModelAsync(modelId, fileStream, "application/pdf");

Web API: Download Multiple Files Separately

I have a Web Api controller method that gets passed document IDs and it should return the document files individually for those requested Ids. I have tried the accepted answer from the following link to achieve this functionality, but it's not working. I don't know where I did go wrong.
What's the best way to serve up multiple binary files from a single WebApi method?
My Web Api Method,
public async Task<HttpResponseMessage> DownloadMultiDocumentAsync(
IClaimedUser user, string documentId)
{
List<long> docIds = documentId.Split(',').Select(long.Parse).ToList();
List<Document> documentList = coreDataContext.Documents.Where(d => docIds.Contains(d.DocumentId) && d.IsActive).ToList();
var content = new MultipartContent();
CloudBlockBlob blob = null;
var container = GetBlobClient(tenantInfo);
var directory = container.GetDirectoryReference(
string.Format(DirectoryNameConfigValue, tenantInfo.TenantId.ToString(), documentList[0].ProjectId));
for (int docId = 0; docId < documentList.Count; docId++)
{
blob = directory.GetBlockBlobReference(DocumentNameConfigValue + documentList[docId].DocumentId);
if (!blob.Exists()) continue;
MemoryStream memStream = new MemoryStream();
await blob.DownloadToStreamAsync(memStream);
memStream.Seek(0, SeekOrigin.Begin);
var streamContent = new StreamContent(memStream);
content.Add(streamContent);
}
HttpResponseMessage httpResponseMessage = new HttpResponseMessage();
httpResponseMessage.Content = content;
httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
httpResponseMessage.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
httpResponseMessage.StatusCode = HttpStatusCode.OK;
return httpResponseMessage;
}
I tried with 2 or more document Ids but only one file was downloaded and that also is not in the correct format (without extension).
Zipping is the only option that will have consistent result on all browsers. MIME/multipart content is for email messages (https://en.wikipedia.org/wiki/MIME#Multipart_messages) and it was never intended to be received and parsed on the client side of a HTTP transaction. Some browsers do implement it, some others don't.
Alternatively, you can change your API to take in a single docId and iterate over your API from your client for each docId.
I think only way is that you zip your all the files and then download one zip file. I guess you can use dotnetzip package because it is easy to use.
One way is that, you can first save your files on disk and then stream the zip to download. Another way is, you can zip them in memory and then download the file in stream
public ActionResult Download()
{
using (ZipFile zip = new ZipFile())
{
zip.AddDirectory(Server.MapPath("~/Directories/hello"));
MemoryStream output = new MemoryStream();
zip.Save(output);
return File(output, "application/zip", "sample.zip");
}
}

WebAPI to download PowerPoint file using memory stream

I'm having trouble downloading a file with content using a Powerpoint presentation library (Syncfusion). The docs only supply ASP examples, no Web API specifically.
I can save a file to the file system which has the context I add to the Powerpoint.
I can get the API to download a file to the users browser but this Powerpoint is empty.
Syncfusion has a function to save the Powerpoint to a memory stream so I guess my question is what is the correct way to save a file to the users browser with the content from the stream?
I'm using HTTPGet and hitting the link through the browser. Do I need to sent the context-type or anything like that?
Thanks for your help, I can provide what I have so far if that helps.
Kurtis
Edit:
[HttpGet, Route("")]
public HttpResponseMessage Get()
{
var presentation = Presentation.Create();
var firstSlide = presentation.Slides.Add(SlideLayoutType.Blank);
var textShape = firstSlide.AddTextBox(100, 75, 756, 200);
var paragraph = textShape.TextBody.AddParagraph();
paragraph.HorizontalAlignment = HorizontalAlignmentType.Center;
var textPart = paragraph.AddTextPart("Kurtis' Presentation");
textPart.Font.FontSize = 80;
var memoryStream = new MemoryStream();
presentation.Save(memoryStream);
var result = Request.CreateResponse(HttpStatusCode.OK);
result.Content = new StreamContent(memoryStream);
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "export.pptx"
};
return result;
}
This is what I have, the library saves the presentation to the memory stream, you can change the parameter to a string which writes this to a file and there is an option to pass a filename, format and HttpResponse for MVC but I couldn't get this working with my API controller. I kept getting a network error but didn't know why.
Thanks again
I found my problem with the help of others in the comments.
The code above work but I needed to reset the stream position to zero to actually write the data.
memoryStream.Position = 0;
Thanks for those who commented. :-)

How to get jpg file from CloudFiles on Rackspace using openstack.net

I'm running the below code in my controller in an asp.net mvc project. I want to enable the user to view or download the files that I store on Cloud Files on rackspace.
var identity =
new CloudIdentity()
{
Username = "username",
APIKey = "apikey"
};
var storage = new CloudFilesProvider(identity);
Stream jpgStream = new MemoryStream();
storage.GetObject("files.container", "1.jpg", jpgStream);
Stream pdfStream = new MemoryStream();
storage.GetObject("files.container", "2.pdf", pdfStream);
var jpgResult = File(jpgStream, "Image/jpg", "1.jpg");
var pdfResult = File(pdfStream, "Application/pdf", "2.pdf");
The above code works when I return pdfResult. I get the correct file. But when I return the jpgResult, the browser downloads 1.jpg as an empty 0KB file.
Am I doing this the right way? Any idea what the problem might be?
Problem solved after I added:
jpgStream.Position = 0;
pdfStream.Position = 0;
Before the File() call. As per the question: File is empty and I don't understand why. Asp.net mvc FileResult
I don't know why this wasn't an issue with the pdf file.
You can also use the GetObjectSaveToFile method.

ASP.NET Web API to return images

I've been spinning my tires trying to use ASP.NET Web API to return images. I've seen a number of examples, but I keep running into problems.
After searching for a solution, most examples suggest using HttpResponseMessage and setting the Content and Content-Type header correctly. For example in the following posts:
WebApi: How to handle Images ASP .Net Web API downloading images as binary
Here's what I am doing now:
[System.Web.Http.HttpGet]
[ActionName("ConvertHTMLToImage")]
public HttpResponseMessage ConvertHTMLToImage(string htmlString)
{
var path = #"C:\temp\mona-lisa.png";
var response = Request.CreateResponse(HttpStatusCode.OK);
var fileStream = new FileStream(path, FileMode.Open, FileAccess.Read);
response.Content = new StreamContent(fileStream);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
return response;
}
I'm getting mixed results. When I go the URL for that resource I have problems with Chrome (This webpage is not available), Firefox (The connection was reset), and Safari (Safari can’t open the page). Much to my surprise, it works fine in IE. I can also successfully view the image using the composer in Fiddler. If I keep Fiddler open and access the resource using Chrome/Firefox/Safari, I see 504 errors. Not sure what the means, I can't remember ever having seen that error type before.
I also noticed some strange behavior in the debugger with the browsers that aren't working. If I call ConvertHTMLToImage from IE and Fiddler, I see it stop at my break-point once and then the image is sucessfully returned to the client. On Chrome/Firefox/Safari there are multiple calls into the method. Sometimes twice sometimes 3 times. I have no explanation for this. I don't get any errors that I can detect other than the browser doesn't show the image.
I've done this same thing using aspx pages, HttpHhandlers, and other .NET methods so I know there are work-arounds, but I really would like to know what I'm doing wrong. This seems like something that should be easily accomplished using the Web API.
This solved the issue for me WebApi: How to handle Images
In short
[System.Web.Http.HttpGet]
[ActionName("ConvertHTMLToImage")]
public HttpResponseMessage ConvertHTMLToImage()
{
string filePath = #"C:\temp\mona-lisa.png";
var result = new HttpResponseMessage(HttpStatusCode.OK);
FileStream fileStream = new FileStream(filePath, FileMode.Open);
Image image = Image.FromStream(fileStream);
MemoryStream memoryStream = new MemoryStream();
image.Save(memoryStream, ImageFormat.Jpeg);
result.Content = new ByteArrayContent(memoryStream.ToArray());
result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
return result;
}
I used this recently in my project:
public HttpResponseMessage Get(int IRN)
{
try
{
Multimedia image = new Multimedia();
MemoryStream imageStream = image.GetMedia(IRN);
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new StreamContent(imageStream);
response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("image/jpeg");
return response;
}
catch (Exception ex)
{
return HandleError(ex);
}
}
GetMedia function:
.....
MemoryStream mediaStream = new MemoryStream();
...
FileStream temp = resource["file"] as FileStream;
mediaStream.SetLength(temp.Length);
temp.Read(mediaStream.GetBuffer(), 0, (int)temp.Length);
temp.Close();
....
return mediaStream;
resource["file"] is an array which contained a filestream object.
Hope this helps.
Try this(replace jpg with png as desired):
var result = new HttpResponseMessage(HttpStatusCode.OK);
String filePath = HostingEnvironment.MapPath("~/Images/123.jpg");
FileStream fileStream = new FileStream(filePath, FileMode.Open);
Image image = Image.FromStream(fileStream);
MemoryStream memoryStream = new MemoryStream();
image.Save(memoryStream, ImageFormat.Jpeg);
var byteArrayContent = new ByteArrayContent(memoryStream.ToArray());
byteArrayContent.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
result.Content = byteArrayContent;
return result;

Categories