C# 点击按钮下载文件
我有一个应用程序,点击按钮需要下载一个文本日志文件。我编写了后端API,但无法通过前端按钮单击来连接它。在角度2和C#上工作。我需要对component.ts文件进行哪些更改 按钮代码:C# 点击按钮下载文件,c#,.net,angular,C#,.net,Angular,我有一个应用程序,点击按钮需要下载一个文本日志文件。我编写了后端API,但无法通过前端按钮单击来连接它。在角度2和C#上工作。我需要对component.ts文件进行哪些更改 按钮代码: <div class="col-lg-4"> <button type="button" class="btn btn-info pull-right" [hidden]="!dbtn" (click)="GetMigrationLog()" id="downloadLog" translat
<div class="col-lg-4"> <button type="button" class="btn btn-info pull-right" [hidden]="!dbtn" (click)="GetMigrationLog()" id="downloadLog" translate>Download Log</button> </div>
下载日志
以下是我的后端api代码:
[Route("GetMigrationLog")]
public IHttpActionResult GetMigrationLog()
{
try
{
IDBMigrationDataBo data = _serviceLocator.Resolve<IDBMigrationDataBo>();
var result = data.GetMigrationLog();
string logFileName = string.Format("Migration_{0}.txt", DateTime.Now.ToString("dd-MM-yyyy"));
return StreamResponse(result, logFileName);
}
catch (Exception ex)
{
logger.Error(ex.Message);
return this.HandleError(ex);
}
}
[路由(“GetMigrationLog”)]
公共IHttpActionResult GetMigrationLog()
{
尝试
{
IDBMigrationDataBo数据=_serviceLocator.Resolve();
var result=data.GetMigrationLog();
string logFileName=string.Format(“Migration_{0}.txt”,DateTime.Now.ToString(“dd-MM-yyyy”);
返回StreamResponse(结果、日志文件名);
}
捕获(例外情况除外)
{
记录器错误(例如消息);
返回此。HandleError(ex);
}
}
我也做过类似的事情。。这有点难。。我将与您分享我的经验和代码。。希望它能帮助你
在html中
下载日志
在您的ts中:
saveFile(id: string, name: string) {
this._orderService.DownloadRicetta(id, name).then((result) => {
this._toaster.pop('success', 'Download', 'Ricetta Scaricata con Successo');
}).catch((err) => {
this._toaster.pop('error', 'Download', 'Errore nel Download della Ricetta!')
console.log(err);
});
}
在您的服务文件中:
首先导入一个软件包(与npm i一起安装--save file saver@types/file saver
)
然后像这样写你的方法:
public async DownloadRicetta(id: string, name: string): Promise<Blob> {
return new Promise<Blob>((resolve, reject) => {
const headers = new HttpHeaders();
headers.append('Accept', 'text/plain'); //just check the type you need
this._http.get(environment.API_URL + `Order/${id}/Download/Ricetta`, { headers: headers, responseType: "blob", observe: 'response' })
.subscribe(response => {
try {
let blob = this.saveToFileSystem(response, name);
resolve(blob);
} catch (error) {
reject(error);
}
});
});
}
private saveToFileSystem(response, name: string): Blob {
const contentDispositionHeader: string = response.headers.get('Content-Disposition');
//for get original filename
const parts: string[] = contentDispositionHeader.split(';');
const filename = parts[1].trim().split('=')[1].trim();
//get extension of the file
const parts2: string[] = contentDispositionHeader.split('.');
let ext = parts2[1];
ext = ext.replace('"', '')
//set mimetype
let mimeType = Utils.extToMimeType(ext);
const blob = new Blob([response.body], { type: mimeType });
FileSaver.saveAs(blob, name + '_ricetta.' + ext);
return blob;
}
以及后端(ASP.NET WEBAPI 2):
[HttpGet]
[路由(“api/Order/{id}/Download/Ricetta”)]
公共异步任务GetBookForHRM([FromUri]字符串id)
{
尝试
{
if(string.IsNullOrEmpty(id))返回新的HttpResponseMessage{StatusCode=HttpStatusCode.BadRequest};
var order=await\u orderService.FindAsync(xx=>xx.Id==Id);
if(order==null)返回新的HttpResponseMessage{StatusCode=HttpStatusCode.BadRequest};
if(string.IsNullOrEmpty(order.ricetaurl))返回新的HttpResponseMessage{StatusCode=HttpStatusCode.BadRequest};
var user=await\u aspNetService.FindAsync(xx=>xx.Id==order.IdUser);
if(user==null)返回新的HttpResponseMessage{StatusCode=HttpStatusCode.BadRequest};
var fileWithPath=$@“{user.GetUserRicettaDirectory()}/{order.RicettaUrl}”;
//将Pdf文件转换为字节数组
var-dataBytes=File.ReadAllBytes(fileWithPath);
//向内存流添加字节
var数据流=新的内存流(数据字节);
HttpResponseMessage HttpResponseMessage=Request.CreateResponse(HttpStatusCode.OK);
httpResponseMessage.Content=新的StreamContent(数据流);
httpResponseMessage.Content.Headers.Add(“访问控制公开标题”、“内容处置”);
httpResponseMessage.Content.Headers.ContentDisposition=新系统.Net.Http.Headers.ContentDispositionHeaderValue(“附件”)
{
FileName=order.ricetaurl.Trim()
};
httpResponseMessage.Content.Headers.ContentType=新系统.Net.Http.Headers.MediaTypeHeaderValue(“应用程序/八位字节流”);
返回httpResponseMessage;
}
捕获(例外情况除外)
{
_logger.LogException(ex);
投掷;
}
}
谢谢,伙计,你的代码帮助我理解了我需要做的事情。它帮助了你。。如果你愿意,给它打分。。所以人们知道这是正确的。。很高兴它帮助了你!!;-)
public async DownloadRicetta(id: string, name: string): Promise<Blob> {
return new Promise<Blob>((resolve, reject) => {
const headers = new HttpHeaders();
headers.append('Accept', 'text/plain'); //just check the type you need
this._http.get(environment.API_URL + `Order/${id}/Download/Ricetta`, { headers: headers, responseType: "blob", observe: 'response' })
.subscribe(response => {
try {
let blob = this.saveToFileSystem(response, name);
resolve(blob);
} catch (error) {
reject(error);
}
});
});
}
private saveToFileSystem(response, name: string): Blob {
const contentDispositionHeader: string = response.headers.get('Content-Disposition');
//for get original filename
const parts: string[] = contentDispositionHeader.split(';');
const filename = parts[1].trim().split('=')[1].trim();
//get extension of the file
const parts2: string[] = contentDispositionHeader.split('.');
let ext = parts2[1];
ext = ext.replace('"', '')
//set mimetype
let mimeType = Utils.extToMimeType(ext);
const blob = new Blob([response.body], { type: mimeType });
FileSaver.saveAs(blob, name + '_ricetta.' + ext);
return blob;
}
export default class Utils {
static extToMimeType(ext: string) {
switch (ext) {
case "pdf":
return "application/pdf";
case "jpg":
return "image/jpg";
case "png":
return "image/png";
case "txt":
return "text/plain";
default:
return "";
}
}
}
[HttpGet]
[Route("api/Order/{id}/Download/Ricetta")]
public async Task<HttpResponseMessage> GetBookForHRM([FromUri] string id)
{
try
{
if (string.IsNullOrEmpty(id)) return new HttpResponseMessage { StatusCode = HttpStatusCode.BadRequest };
var order = await _orderService.FindAsync(xx => xx.Id == id);
if (order == null) return new HttpResponseMessage { StatusCode = HttpStatusCode.BadRequest };
if (string.IsNullOrEmpty(order.RicettaUrl)) return new HttpResponseMessage { StatusCode = HttpStatusCode.BadRequest };
var user = await _aspNetService.FindAsync(xx => xx.Id == order.IdUser);
if (user == null) return new HttpResponseMessage { StatusCode = HttpStatusCode.BadRequest };
var fileWithPath = $@"{user.GetUserRicettaDirectory()}/{order.RicettaUrl}";
//converting Pdf file into bytes array
var dataBytes = File.ReadAllBytes(fileWithPath);
//adding bytes to memory stream
var dataStream = new MemoryStream(dataBytes);
HttpResponseMessage httpResponseMessage = Request.CreateResponse(HttpStatusCode.OK);
httpResponseMessage.Content = new StreamContent(dataStream);
httpResponseMessage.Content.Headers.Add("Access-Control-Expose-Headers", "Content-Disposition");
httpResponseMessage.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
{
FileName = order.RicettaUrl.Trim()
};
httpResponseMessage.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
return httpResponseMessage;
}
catch (Exception ex)
{
_logger.LogException(ex);
throw;
}
}