![](/img/trans.png)
[英]How do you detect if a file is being downloaded by a Browser or a Download Manager
[英]How to download excel file using Ajax method- here my file is downloaded in Temp folder not Downloaded in Browser?
我想下载一个Excel文件。 我使用AJAX方法来获取文件,但它不是为我工作。 我的文件下载到临时文件夹,但它在浏览器不下载。
C#和jQuery
jQuery的
//Exporting errors to excel file
function ExcportErrorListToExcel() {
debugger;
$.ajax({
url: 'Import/ExportErrorToExcel',
type: 'GET',
data: { dataExchangeSelectedColum: $('#hdnSelectedColumn').val(), entityvalue: $('#hdnEntity').val(), filename: $('#hdnFileName').val() },
//contentType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
success: function (returnValue) {
debugger;
window.location = '/Import/ExportErrorToExcel?file=' + returnValue.filename;
//alert('success');
}
});
}
调节器
#region ExportErrorToExcel
public ActionResult ExportErrorToExcel(string dataExchangeSelectedColum, string entityvalue, string filename)
{
UA patsUA = Session["PaTSUA"] as UA;
DataTable dataTable = null;
dataTable = _dataExchangeBusiness.DataValidation(dataExchangeSelectedColum, entityvalue, filename, patsUA.DBConnectionString);
string tempPath = Server.MapPath("~/Temp/" + Guid.NewGuid().ToString() + ".xlsx");
_dataExchangeBusiness.ExportErrorToExcel(dataTable,tempPath, entityvalue);
FileInfo fileInfo = new FileInfo(tempPath);
if (fileInfo.Exists)
{
Response.Clear();
byte[] excelBytes = System.IO.File.ReadAllBytes(tempPath);
MemoryStream memoryStream = new MemoryStream(excelBytes);
Response.ContentType= "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;filename=ErrorList.xlsx");
Response.Buffer = true;
memoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.End();
//System.IO.File.Delete(tempPath);
}
//var errorRowList = (from e in dataTable.AsEnumerable()
// where e.Field<string>("DataError").ToString() != ""
// select e).ToList();
return File(tempPath, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", Path.GetFileName(tempPath));
//return Json(new { Status = "OK", Records = tempPath, contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" });
}
#endregion ExportErrorToExcel
尝试这个
//Exporting errors to excel file
function ExcportErrorListToExcel() {
debugger;
$.ajax({
url: 'Import/ExportErrorToExcel',
type: 'GET',
data: { dataExchangeSelectedColum: $('#hdnSelectedColumn').val(), entityvalue: $('#hdnEntity').val(), filename: $('#hdnFileName').val() },
//contentType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
success: function (returnValue) {
debugger;
var link=document.createElement('a');
document.body.appendChild(link);
link.href="/Temp/" + returnValue.filename;
link.click();
link.remove();
}
});
}
这可以简单地通过将控制器函数分成两个来完成。第一个函数会将文件保存在temp文件夹中,并将文件名传递给jquery Ajax函数,并在其成功部分将其重定向到控制器中的第二个函数。在这里我们将下载文件
这是阿贾克斯
function ExportErrorListToExcel() {
debugger;
$.ajax({
url: "Import/ExportErrorToExcel",
type: "POST",
data: { dataExchangeSelectedColum: $('#hdnSelectedColumn').val(), entityvalue: $('#hdnEntity').val(), filename: $('#hdnFileName').val() },
success: function (responsetext, status, xhr) {
debugger;
window.location = 'Import/DownloadErrorData?fname=' + responsetext.FileName;
}
});
// $('#ExcelExportForm').submit();
}
这是控制器功能,文件保存在临时文件夹中
#region ExportErrorToExcel
//This function will return the file name to script
public ActionResult ExportErrorToExcel(string dataExchangeSelectedColum, string entityvalue, string filename)
{
UA patsUA = Session["PaTSUA"] as UA;
DataTable dataTable = null;
dataTable = _dataExchangeBusiness.DataValidation(dataExchangeSelectedColum, entityvalue, filename, patsUA.DBConnectionString);
string tempPath = Server.MapPath("~/Temp/" + Guid.NewGuid().ToString()+ ".xlsx");
_dataExchangeBusiness.ExportErrorToExcel(dataTable,tempPath, entityvalue);
string fname = Path.GetFileName(tempPath);
return Json(new { Result = "true", Message = "Success", FileName = fname,Entity=entityvalue });
}
#endregion ExportErrorToExcel
这是用于从Temp文件夹下载文件的控制器第二功能
#region DownloadErrorData
//In this function recieve the filename and will download it from the location
public ActionResult DownloadErrorData(string fname)
{
string fileName ="ErrorList.xlsx";
string filePath= Path.Combine(Server.MapPath("~/Temp/" + fname));
try
{
string[] allFiles = Directory.GetFiles(Path.GetDirectoryName(filePath) + Path.DirectorySeparatorChar);
foreach (string file in allFiles)
{
FileInfo fileinfo = new FileInfo(file);
if (fileinfo.CreationTime < DateTime.Now.AddDays(-2))
{
fileinfo.Delete();
}
}
}
catch (Exception ex)
{
throw ex;
}
string contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";//web content type of .xlsx files
return File(filePath, contentType, fileName);
}
#endregion DownloadErrorData
希望这会对某人有所帮助:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.