我環顧四周,很多人似乎都有同樣的問題,被下載的文件已損壞。我在前端使用web api 2和angular。使用AngularJS從Asp.net Web API 2下載Excel
服務器端
[Route("api/export/{id}")]
public async Task<IHttpActionResult> GetFileAsync(Guid id)
{
var originalFile = System.Web.Hosting.HostingEnvironment.MapPath("~/App_Data/template.xls");
var stream = _exportService.Export(id, originalFile);
return new FileActionResult(stream);
}
public class FileActionResult : IHttpActionResult
{
private Stream Data { get; }
public FileActionResult(Stream data)
{
Data = data;
}
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
HttpResponseMessage response = new HttpResponseMessage
{
Content = new StreamContent(Data)
};
//response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
//response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.ms-excel");
//response.Content.Headers.ContentDisposition.FileName = "ExportedCOBie.xls";
response.Content.Headers.ContentLength = Data.Length;
return Task.FromResult(response);
}
}
角客戶
function(Restangular, FileSaver, Blob) {
this.exportToCobie = function(projectId) {
toastr.info('Exporting data', 'Info');
Restangular.one("export/" + projectId)
.get({ responseType: "arraybuffer" })
.then(function (data) {
var file = new Blob([data], { type: 'application/vnd.ms-excel' });
FileSaver.saveAs(file, 'export.xls');
})
}
}
任何幫助將非常感激,感謝。
public MemoryStream Export(Guid projectId, string file)
{
try
{
var fileStream = new FileStream(file, FileMode.Open);
_workbook = new HSSFWorkbook(fileStream);
fileStream.Close();
var contacts = _uow.ContactRepository.FindAllBy(c => c.ProjectId == projectId);
//var fileOutputStream = new FileStream(file, FileMode.Create);
var memoryStream = new MemoryStream();
_workbook.Write(memoryStream);
memoryStream.Position = 0;
return memoryStream;
}
catch (Exception exception)
{
_logger.Error(exception.Message);
}
return null;
}
您下載的文件是否有內容,但它只是損壞,或者它是0字節? –
@RonBrogan它有內容但已損壞,怪異的字符。 –
您可以發佈這裏發生了什麼:'_exportService.Export' –