Javascript 在c#MVC5中使用DotNetZip下载zip文件
情景:Javascript 在c#MVC5中使用DotNetZip下载zip文件,javascript,c#,ajax,asp.net-mvc,download,Javascript,C#,Ajax,Asp.net Mvc,Download,情景: 根据需要筛选jquery数据表 除了页面长度下拉列表外,还可以使用“下载”按钮(这是一个简单的按钮,而不是“提交”按钮)。下载已过滤数据的图像 从表中获取记录ID,创建其数组并将其发送给控制器 在控制器中,从与从发送的记录ID关联的数据库中获取文件路径 ajax请求 获取文件,制作一个zip文件并将其发送回(作为响应)视图(下载) 正如我提到的场景,我希望在机器上下载zip。 但是文件没有被下载 ------------------------------编辑[解决方案]:-------
[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
}
}
这肯定会下载预期的zip文件。那么到底出了什么问题?还不清楚您是否有任何错误或某些特定的意外行为?
saveas()
做什么?这在下载过程中似乎很重要,但您还没有显示出来。而且…为什么不使用常规超链接下载文件呢?正如您刚刚发现的那样,通过AJAX下载是**中的一个难题。或者事实上,为什么要为此使用任何服务器端代码?从您的代码中,我可以看到放入Zip文件的所有数据都来自客户端,因此为什么不使用客户端JavaScript Zip库(例如,我认为JSZip很流行)?那么您就不需要AJAX或其他任何东西了。当我使用此解决方案时,我没有收到任何错误,但没有下载文件。我想知道控制器是否获得了值。它没有在中的调试器断点处停止controller@ADyson因为这些图片都在服务器上。我想从这些图片中下载一些这就是为什么它是服务器端哦,好吧,我明白了,我不太明白这一点。我以为你只是在添加表中的行。所以是的,服务器端是必要的。但我的其余评论现在是相关的。什么是C#中的obj#u记录
?它似乎没有定义。
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);
}