我正在使用MVC 5网络Api控制器,我想返回一个文件:
[Route("")]
public HttpResponseMessage GetFile()
{
var statusCode = HttpStatusCode.OK;
FileStream file = XLGeneration.XLGeneration.getXLFileExigence();
return Request.CreateResponse(statusCode, file);
}
它不起作用。
邮递员的例外是:
“ExceptionMessage”:“'ObjectContent`1'类型无法序列化内容类型'application / json; charset = utf-8'的响应正文。”
答案 0 :(得分:5)
我发布了对我有用的东西,以防其他人遇到麻烦。
[ActionName("File")]
[HttpGet]
public HttpResponseMessage File()
{
var response = new HttpResponseMessage(HttpStatusCode.OK);
var stream = new System.IO.FileStream(yourFilePath, System.IO.FileMode.Open);
response.Content = new StreamContent(stream);
response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
return response;
}
答案 1 :(得分:3)
我从WebAPI控制器返回了byte []并成功下载了PDF。 我正在使用iTextSharp(LGPL)4.1.6免费PDF转换器。 要安装iTextSharp(LGPL / MPL),请在程序包管理器控制台中运行以下命令。
安装包装iTextSharp-LGPL -Version 4.1.6
服务器端代码
[Route("Export/ExportToPdf")]
public byte[] ExportToPdf(string html)
{
MemoryStream msOutput = new MemoryStream();
TextReader reader = new StringReader(html);
Document document = new Document(new Rectangle(842, 595));
PdfWriter writer = PdfWriter.GetInstance(document, msOutput);
document.Open();
document.HtmlStyleClass = @"<style>*{ font-size: 8pt; font-family:arial;}</style>";
var parsedHtmlElements = HTMLWorker.ParseToList(new StringReader(html), null);
foreach (var htmlElement in parsedHtmlElements)
{
document.Add(htmlElement as IElement);
}
document.Close();
return msOutput.ToArray();
}
客户端代码。
//Call this function inside of AJAX success.
function ExportToPDF(data) {
//base64 To ArrayBuffer
var binaryString = window.atob(data);
var binaryLen = binaryString.length;
var bytes = new Uint8Array(binaryLen);
for (var i = 0; i < binaryLen; i++) {
var ascii = binaryString.charCodeAt(i);
bytes[i] = ascii;
}
//-------
var link = document.createElement('a');
link.href = window.URL.createObjectURL(new Blob([bytes], { type: 'application/pdf' }));
link.download = "Report.pdf";
link.click();
}
答案 2 :(得分:2)
试试这个......
{{1}}
这实际上应该将其作为文件传回。
答案 3 :(得分:0)
只是想法:
public HttpResponseMessage GetFile()
{
FileStream file = XLGeneration.XLGeneration.getXLFileExigence();
using(var sr = new StreamReader(file))
{
content = sr.ReadToEnd();
return new HttpResponseMessage
{
Content = new StringContent(content, Encoding.UTF8, "application/json")
};
}
}