后端返回文件实现:
-
在 .NET 项目中添加一个 API 接口,用于生成文件并返回。
-
在接口中获取前端传递的相关数据生成文件。
-
返回对应文件流程
WPF实现下载:
-
在 WPF 窗口中添加一个按钮下载文件。
-
在按钮的 Click 事件中,调用生成文件并下载接口,并使用 RestSharp 发起 HTTP POST 请求。
-
在请求完成后,将文件保存到本地文件系统中。
-
在保存文件时,可以通过设置 RestSharp 的 ResponseWriter 属性来控制如何保存文件,例如直接将文件保存到指定路径或者将文件内容写入内存流中。
-
可以使用 MessageBox 来显示下载进度和下载结果。
后端实现下载:
-
在 .NET 项目中添加一个 API 接口,用于下载文件。
-
在接口中获取前端传递的下载文件的 URL。
-
使用 RestSharp 发起 HTTP GET 请求,并设置 ResponseWriter 属性将文件内容写入 Response 中。
-
在返回 Response 前需要设置 Response 的 Content-Type 和 Content-Disposition 属性,以便浏览器能够正确识别文件类型和文件名。
-
通过返回 Response 来将文件内容传递给前端。
WEB实现下载:
1.在 web页面中添加一个按钮下载文件。
2.在按钮的 Click 事件中,调用生成文件并下载接口,指定相关请求头及返回值发起 HTTP POST 请求。
3.创建a标签触发点击事件实现下载文件流
以下是后端返回文件流实现的示例代码:
/// <summary>
/// 导出生成文件
/// </summary>
/// <param name="exportFileInDto"></param>
[HttpPost]
public FileStreamResult Export([FromBody] ExportFileInDto exportFileInDto)
{
string filePath = ""; 生成的文件地址
FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
return new FileStreamResult(fileStream, "application/octet-stream") { FileDownloadName = exportFileInDto.FileName };
}
后端调用接口下载
//接口下载文件
[HttpGet("download")]
public IActionResult DownloadFile(string url)
{
var client = new RestClient(url);
var request = new RestRequest(Method.GET);
request.ResponseWriter = responseStream =>
{
// 设置 Content-Type 和 Content-Disposition 属性
HttpContext.Response.ContentType = "application/octet-stream";
HttpContext.Response.Headers.Add("Content-Disposition", $"attachment; filename=\"{Path.GetFileName(url)}\"");
// 将文件内容写入 Response 中
var reader = new BinaryReader(responseStream);
var buffer = new byte[8192];
int read;
while ((read = reader.Read(buffer, 0, buffer.Length)) > 0)
{
HttpContext.Response.Body.WriteAsync(buffer, 0, read);
}
};
try
{
client.Execute(request);
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
return new EmptyResult();
}
wpf端调用接口下载
private void DownloadButton_Click(object sender, RoutedEventArgs e)
{
var client = new RestClient(APIHelper.ApiUrl);
RestRequest request = new RestRequest(APIHelper.ApiUrl + ApiRoutes.ExportAVLFGData, Method.Post);
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Authorization", APIHelper.Token);
request.AddJsonBody(inDto);
var response = await client.ExecutePostAsync(request);
if (response.StatusCode == HttpStatusCode.OK)
{
Microsoft.Win32.SaveFileDialog dlg = new()
{
FileName = inDto.FileName,
Filter = "Excel files(*.xlsx)|*.xlsx",
RestoreDirectory = true,
DefaultExt = "xlsx",
OverwritePrompt = true
};
string filePath;
if (dlg.ShowDialog() == true)
{
filePath = dlg.FileName;
using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write))
{
fs.Write(response.RawBytes);
}
//下载成功提示
}
}
else
{
//下载异常提示
}
}
web前端下载
axios({
method: 'POST',
url: '/api/System/ExportFile/Export',
data: JSON.stringify(data),
headers: {
Authorization: getToken(),
'Content-Type': 'application/json',
},
responseType: 'blob',
})
.then(({ data }) => {
const blob = new Blob([data], { type: 'application/vnd.ms-excel;charset=utf-8' });
const elink = document.createElement('a'); // 创建a标签
elink.download = `NonKC_${invoiceNumberInput}_${new Date().getFullYear()}${new Date().getMonth() + 1}${new Date().getDate()}.xlsx`;
elink.style.display = 'none';
elink.href = URL.createObjectURL(blob);
document.body.appendChild(elink);
elink.click();
URL.revokeObjectURL(elink.href);
document.body.removeChild(elink);
})
.catch(function (error) {
console.log(error);
});