要从ASP.NET MVC5传递参数下载文件,你需要使用AngularJS来发起HTTP请求并将参数传递给后端控制器。下面是一个解决方法的示例代码:
首先,在AngularJS控制器中定义一个函数来发起下载文件的请求,并将参数传递给后端控制器:
app.controller('DownloadController', function($scope, $http) {
$scope.downloadFile = function(param) {
$http({
url: '/Download/DownloadFile',
method: 'GET',
params: { param: param },
responseType: 'arraybuffer'
}).then(function(response) {
var data = new Blob([response.data], { type: response.headers('Content-Type') });
var fileName = response.headers('Content-Disposition').split('filename=')[1];
saveAs(data, fileName);
});
};
});
接下来,在后端控制器中处理下载文件的请求,并根据传递的参数生成文件:
public ActionResult DownloadFile(string param)
{
// 根据参数生成文件
byte[] fileData = GenerateFileData(param);
string fileName = "example.pdf"; // 设置文件名
// 返回文件流
Response.Clear();
Response.ContentType = "application/pdf";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
Response.BinaryWrite(fileData);
Response.End();
return new EmptyResult();
}
请注意,上述示例中的GenerateFileData
方法用于根据传递的参数生成文件的字节数组。你需要根据自己的业务逻辑来实现此方法。
最后,你可以在前端HTML页面中调用downloadFile
函数,并传递参数:
当点击按钮时,将会发起HTTP请求并下载生成的文件。