Export Excel File from Web API c# - c#

Here's what I have tried so far:
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
try
{
StringBuilder strBuilder = GenerateExcelFormat(modelPaymentDetails);
//byte[] array = Encoding.ASCII.GetBytes(strBuilder.ToString());
response.Content = new StringContent(strBuilder.ToString());
//response.Content = new ByteArrayContent(array);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/ms-excel");
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment"); //attachment will force download
response.Content.Headers.ContentDisposition.FileName = "PaymentSummary.xls";
return response;
}
catch (Exception ex)
{
return response;
}
but didn't download an excel file. Where I'm going wrong?

Related

How can I show image in HttpResponseMessage.Content.Headers.ContentType

I have a method to return an image. As below:
string fullName = dt.Rows[0]["FileName"].ToString();
string directoryPath = MyFileMultipartFormDataStreamProvider.GetMyFileDirectory();
var myFilePath = Path.Combine(directoryPath, fullName);
using (FileStream fileStream = new FileStream(myFilePath, FileMode.Open))
{
using (var memoryStream = new MemoryStream())
{
fileStream.CopyTo(memoryStream);
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
result.Content = new ByteArrayContent(memoryStream.ToArray());
result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
return result;
}
}
How can I show the image in asp.net mvc cshtml page?
Postman is ok (image).
I solved it as follows
byte[] mybytearray = null;
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(URI);
client.DefaultRequestHeaders
.Accept
.Add(new MediaTypeWithQualityHeaderValue("image/png"));
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "");
try
{
Task<HttpResponseMessage> getResponse = client.SendAsync(request);
HttpResponseMessage response = new HttpResponseMessage();
response = await getResponse;
if (response.IsSuccessStatusCode)
{
mybytearray = response.Content.ReadAsByteArrayAsync().Result;
}
var responseJsonString = await response.Content.ReadAsStringAsync();
System.Diagnostics.Debug.WriteLine(responseJsonString);
System.Diagnostics.Debug.WriteLine("GetReportImage ReponseCode: " + response.StatusCode);
}
catch (Exception ex)
{
}
}

Web API returns description of HttpResponseMessage to browser

This code is supposed to result in a file download...
public HttpResponseMessage Export()
{
var byteArray = Encoding.UTF8.GetBytes("Hello World!");
var stream = new MemoryStream(byteArray);
var result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StreamContent(stream),
};
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "myFile.csv"
};
result.Content.Headers.ContentType = new MediaTypeHeaderValue("text/csv");
return result;
}
Instead I get this message...
{"version":{"major":1,"minor":1,"build":-1,"revision":-1,"majorRevision":-1,"minorRevision":-1},"content":{"headers":[]},"statusCode":200,"reasonPhrase":"OK","headers":[],"requestMessage":null,"isSuccessStatusCode":true}
What am I doing wrong?
public IActionResult Export()
{
var byteArray = Encoding.UTF8.GetBytes("Hello World!");
var stream = new MemoryStream(byteArray);
return File(stream, "myFile.csv", "text/csv");
}

Downloading PDF across 2 APIs using GET request

Im trying to download a PDF file crossing over two API's with a GET Request.
If I go direct to API2 the PDF downloads fine with the below code:
Stream fileStream = File.Open(fileLocation, FileMode.Open);
result.Content = new StreamContent(fileStream);
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "test.pdf"
};
return result;
However when I throw API1 into the mix things get a little wonky!!
using (System.Net.Http.HttpClient client = new System.Net.Http.HttpClient())
{
var httpRequestMessage = new HttpRequestMessage();
httpRequestMessage.Method = HttpMethod.Get;
httpRequestMessage.RequestUri = new Uri(requestUrl);
HttpResponseMessage response = await client.SendAsync(httpRequestMessage);
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
var content = await response.Content.ReadAsStringAsync();
response.Content = new StringContent(content);
response.EnsureSuccessStatusCode();
response.Content.Headers.ContentEncoding.Add("UTF8");
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "test.pdf"
};
return response;
Going direct to API2 produces: %PDF-1.6%âãÏÓ
Going via API2 produces:%PDF-1.6%����
Ive tried changing ContentType and ContentEncoding on API1 with no joy.
Does anything jump out to anyone?
Calling .ReadAsStringAsync on a binary document wont work - you have to call .ReadAsByteArrayAsync.
You also have to use ByteArrayContent instead of StringContent.
not tested

Image blank when handling image from web api

I have 2 web api´s. One that connects to the DB and get the data (webapi 2). And another that just handle this data and send to the Client side (webapi 1).
The problem is that when is a string, the handle Works. But with the image is not working. I am getting the general internal server error 500.
If i call just the WebApi 2, I get the image. If I call the WebApi 1 that calls the webapi 2, the image is blank.
My Web Api Handler:
[HttpGet]
[Route("Foto")]
public async Task<HttpResponseMessage> GetFoto(string suspid, string pk)
{
HttpClientHandler handler = new HttpClientHandler()
{
UseDefaultCredentials = true,
};
using (var client = new HttpClient(handler))
{
//QUANDO TESTAR NO SERVIDOR
client.BaseAddress = new Uri("http://192.111.56.1:1762/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("image/jpeg"));
HttpResponseMessage response = await client.GetAsync("api/Nomes/Foto?suspid="+suspid+"&pk="+pk+"");
if (response.IsSuccessStatusCode)
{
var data = response.Content.ReadAsByteArrayAsync().Result;
var stream = new MemoryStream(data);
response.Content = new StreamContent(stream);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
return response;
}
else
{
Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
return null;
}
}
}
The Web Api that connects to the DB:
I am hiding the connect string and other stuff that doesn't matter.
cmd.InitialLONGFetchSize = -1;
var reader = cmd.ExecuteReader();
byte[] imgBytes = null;
if (reader.Read())
{
// Fetch the LONG RAW
OracleBinary imgBinary = reader.GetOracleBinary(0);
// Get the bytes from the binary obj
imgBytes = imgBinary.IsNull ? null : imgBinary.Value;
}
connection.Close();
connection.Dispose();
try
{
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
var stream = new MemoryStream(imgBytes);
result.Content = new StreamContent(stream);
result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
return result;
}
catch (Exception ex)
{
return Request.CreateResponse(HttpStatusCode.Gone);
}

WebApi file download has frozen the browser for the first time

I am using WebAPI for downloading a .pdf file like this:
[HttpGet]
public async Task<HttpResponseMessage> DownloadFile(string id, bool attachment = true)
{
HttpResponseMessage result = null;
try
{
MyService service = new MyService();
var bytes = await service.DownloadFileAsync(id);
if (bytes != null)
{
result = GetBinaryFile(personalDocument, string.Format("{0}.pdf", id), attachment);
}
else
{
result = new HttpResponseMessage(HttpStatusCode.NotFound);
}
}
catch (Exception ex)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.BadRequest) { ReasonPhrase = "ServerError" });
}
return result;
}
private HttpResponseMessage GetBinaryFile(byte[] bytes, string fileName, bool attachment)
{
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
// result.Content = new ByteArrayContent(bytes);
result.Content = new StreamContent(new System.IO.MemoryStream(bytes));
//result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("inline");
if (attachment)
{
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
}
result.Content.Headers.ContentDisposition.FileName = fileName;
result.Content.Headers.ContentLength = bytes.Length;
return result;
}
The issue is: when I download file for the first time it freezes the browser, and cannot perform anything. But after a refresh of the page, every time the file download is successful.
I tried to use ByteArrayContent or StreamContent but same thing happens. I also tried to use MediaTypeHeaderValue("application/octet-stream") or MediaTypeHeaderValue("application/pdf"), but again - the same issue occurred.
So I find that the problem is
if (attachment)
{
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
}
If I set attachment to be true it set ContentDisposition to be ContentDispositionHeaderValue("attachment") (it is for download only)
If I set attachment to be false it open the file immediately and doesn't freeze the browser..
Any idea? Thanks!

Categories