In ähnlichen Fragen funktioniert dieser Code, um ein PDF herunterzuladen:
Ich teste mit lokalen Dateien (.xlsx, .pdf, .Zip) im Controller-Ordner.
[HttpGet("downloadPDF")]
public FileResult TestDownloadPCF()
{
HttpContext.Response.ContentType = "application/pdf";
FileContentResult result = new FileContentResult
(System.IO.File.ReadAllBytes("Controllers/test.pdf"), "application/pdf")
{
FileDownloadName = "test.pdf"
};
return result;
}
Bei einer anderen Datei, z. B. einer Excel-Datei (.xlsx) oder einer Zip-Datei (.Zip), funktioniert das Testen nicht ordnungsgemäß.
Code:
[HttpGet("downloadOtherFile")]
public FileResult TestDownloadOtherFile()
{
HttpContext.Response.ContentType =
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
FileContentResult result = new FileContentResult(System.IO.File.ReadAllBytes("Controllers/test.xlsx"),
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
{
FileDownloadName = "otherfile"
};
return result;
}
Ich habe auch Tests mit dem folgenden Inhaltstyp durchgeführt:
Das gleiche Ergebnis erzielen.
Welches ist der richtige Weg, um einen Dateityp zurückzugeben?
Danke für deine Antworten
Meine (Arbeits-) Lösung:
FileInfo
für den Pfad der erzeugten Datei zurück.Folgendes befindet sich in meinem Controller:
[HttpGet("test")]
public async Task<FileResult> Get()
{
var contentRootPath = _hostingEnvironment.ContentRootPath;
// "items" is a List<T> of DataObjects
var items = await _mediator.Send(new GetExcelRequest());
var fileInfo = new ExcelFileCreator(contentRootPath).Execute(items);
var bytes = System.IO.File.ReadAllBytes(fileInfo.FullName);
const string contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
HttpContext.Response.ContentType = contentType;
HttpContext.Response.Headers.Add("Access-Control-Expose-Headers", "Content-Disposition");
var fileContentResult = new FileContentResult(bytes, contentType)
{
FileDownloadName = fileInfo.Name
};
return fileContentResult;
}
Und hier ist was ich in Angular2 habe:
downloadFile() {
debugger;
var headers = new Headers();
headers.append('responseType', 'arraybuffer');
let url = new URL('api/excelFile/test', environment.apiUrl);
return this.http
.get(url.href, {
withCredentials: true,
responseType: ResponseContentType.ArrayBuffer
})
.subscribe((response) => {
let file = new Blob([response.blob()], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
let fileName = response.headers.get('Content-Disposition').split(';')[1].trim().split('=')[1];
saveAs(file, fileName);
},
err => this.errorHandler.onError(err)
);
}
Ich hatte das gleiche Problem. Mein Problem wurde durch die Clientanforderung verursacht, nicht die Serverantwort. Ich habe das Problem gelöst, indem ich den Header-Optionen meiner Get-Anfrage einen Antwort-Inhaltstyp hinzugefügt habe. Hier ist mein Beispiel in Angular 2.
Anforderung vom Client (Angular 2) ** erfordert die Bibliothek filesaver.js
this._body = '';
let rt: ResponseContentType = 2; // This is what I had to add ResponseContentType (2 = ArrayBuffer , Blob = 3)
options.responseType = rt;
if (url.substring(0, 4) !== 'http') {
url = config.getApiUrl(url);
}
this.http.get(url, options).subscribe(
(response: any) => {
let mediaType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
let blob = new Blob([response._body], { type: mediaType });
let filename = 'test.xlsx';
fileSaver.saveAs(blob, filename);
});
Serverseitiger Code. (.net Kern)
[HttpGet("{dataViewId}")]
public IActionResult GetData(string dataViewId)
{
var fileName = $"test.xlsx";
var filepath = $"controllers/test/{fileName}";
var mimeType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
byte[] fileBytes = System.IO.File.ReadAllBytes(filepath);
return File(fileBytes, mimeType, fileName);
}
hier sind die Referenzen, wenn Sie sehen wollen.
Das folgende Beispiel zeigt, wie Sie eine Datei herunterladen können. Sie können das Szenario des Herunterladens einer Excel-Datei danach modellieren:
public IActionResult Index([FromServices] IHostingEnvironment hostingEnvironment)
{
var path = Path.Combine(hostingEnvironment.ContentRootPath, "Controllers", "TextFile.txt");
return File(System.IO.File.OpenRead(path), contentType: "text/plain; charset=utf-8", fileDownloadName: "Readme.txt");
}
Wenn sich die Datei im Ordner wwwroot
befindet, können Sie stattdessen wie folgt vorgehen:
public IActionResult Index()
{
return File(virtualPath: "~/TextFile.txt", contentType: "text/plain; charset=utf-8", fileDownloadName: "Readme.txt");
}