如何解决在c#MVC5中使用DotNetZip下载zip文件
场景:
- 根据需要过滤jquery数据表。
- 使用页面长度下拉菜单之外的下载按钮(它是一个简单的按钮,而不是提交按钮)。下载用于过滤数据的图像。
- 从表中获取记录ID,建立其数组并将其发送给控制器。
- 在控制器中,从数据库中获取与从服务器发送的记录ID相关联的文件路径。 阿贾克斯要求。
- 获取文件,压缩并发送回(作为响应)到视图(下载)。
正如我提到的情况,我希望将zip下载到计算机上。 但是该文件未下载。
--------------------------编辑[解决方案]:------------- --------------
尝试了许多解决方案后,我终于找到了解决方案。
所以首先,我将Controller Code用作:
[HttpPost]
public ActionResult Ajax_DownloadImages(int[] records)
{
#region Variable Declaration
List<tbl_image_Details> obj_records = new List<tbl_image_Details>();
tbl_image_Details singleRecord = new tbl_image_Details();
var memorystream = new MemoryStream();
int temp = 0;
#endregion
using (Symphony_webServer_DBEntities db = new Symphony_webServer_DBEntities())
{
#region Get File paths from the database.
for (int i = 0; i < records.Count(); i++)
{
temp = records[i];
singleRecord = db.tbl_image_Details.Where(x => x.record_id == temp).FirstOrDefault<tbl_image_Details>();
obj_records.Add(singleRecord);
}
#endregion
#region Zipping and sending the data to download.
using (ZipFile obj_Zip = new ZipFile())
{
obj_Zip.AlternateEncodingUsage = ZipOption.AsNecessary;
obj_Zip.AddDirectoryByName("Images");
foreach (var file in obj_records)
{
obj_Zip.AddFile(file.image_path,"Images");
}
Response.ClearContent();
Response.ClearHeaders();
Response.AppendHeader("content-disposition","attachment; filename=Myzip.zip");
obj_Zip.Save(memorystream);
}
memorystream.Position = 0;
return new FileStreamResult(memorystream,"application/octet-stream");
#endregion
}
}
视图: 创建一个简单的按钮,并在其click事件上调用下载功能,如下所示。 从服务器请求压缩数据的功能是-
注意::我使用XMLHttpRequest对象进行请求调用,因为, jQuery ajax调用无法有效地处理Blob响应内容。
funtion DownloadImages(){
// selecting the table
var Displayedtable = $("#recordTable").DataTable();
// fetching the rows of the table
var datatable_rows = Displayedtable.rows().data().toArray();
// creating an array to hold data.
var table_data = new Array();
// fetching data from each cell and putting it into the array.
$.each(datatable_rows,function (index,value) {
table_data.push(value['record_id']);
});
var records = JSON.stringify(table_data);
var ajax = new XMLHttpRequest();
ajax.open("Post","/ReportsPage/Ajax_DownloadImages",true);
ajax.setRequestHeader("Content-Type","application/json");
ajax.responseType = "blob";
ajax.onreadystatechange = function () {
if (this.readyState == 4) {
var blob = new Blob([this.response],{ type: "application/octet-stream" });
console.log(this.response);
alert(this.response);
var fileName = "Myzip.zip";
saveAs(blob,fileName);
}
};
ajax.send(records);
}
这肯定会下载所需的zip文件。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。