我正在編寫jQuery代碼來下載文件,下載文件之後必須從服務器刪除。以下是我的文件下載和刪除文件的代碼。javascript - jquery ajax成功之前先完成調用
if (method == "ValueAddedReportExportToExcel") {
$.ajax({
async: false,
type: "post",
cache: false,
url: '@Url.Action("ValueAddedReportExportToExcel", "report")',
data: {
fromDate: $('#txtFromDate').val(),
toDate: $('#txtToDate').val(),
reportForWhom: $("#ddlReportForWhom").val(),
customers: (ddlCustomers != null) ? ddlCustomers.join(',') : "",
salesReps: (salesReps != null) ? salesReps.join(',') : "",
users: (users != null) ? users.join(',') : "",
emailTo: emailTo,
subject: subject,
body: body,
},
success: function (data) {
fileName = data.fileName;
// call to download action.
window.location = '@Url.Action("Download", "Report")' + '?file=' + data.fileName;
console.log('Success Call');
},
complete: function() {
console.log('Complete Call');
$.ajax({
async: false,
type: "post",
url: '@Url.Action("DeleteFile", "Report")',
data: { file: filename },
success: function() {
alert(filename + ' is deleted successfuly. ');
}
});
}
});
//methodURL = '@Url.Action("ValueAddedReportExportToExcel", "report")';
}
下面兩個函數是用於控制器中的下載和刪除功能。
public virtual ActionResult Download(string file)
{
string fullPath = Path.Combine(Server.MapPath("~/CostSavingReport"), file);
byte[] fileBytes = System.IO.File.ReadAllBytes(fullPath);
//return File(fileBytes, "application/vnd.ms-excel", file);
return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, file);
}
public virtual void DeleteFile(string file)
{
try
{
var fullPath = Path.Combine(Server.MapPath("~/CostSavingReport"), file);
if (System.IO.File.Exists(fullPath))
{
System.IO.File.Delete(fullPath);
}
}
catch (Exception)
{
}
}
現在的問題是第一DeleteFile
動作被調用,而不是Download
動作怎麼做,使先打電話Download
和之後DeleteFile
。
刪除其服務器端。 –
之後,我應該怎麼做? @SergeK。 –
如果您想在下載文件後刪除文件,請在「下載」功能內移動刪除部分。否則,您將依賴於下載結束後可以離開頁面的客戶端,並且無論您是何種解決方案,都不會調用刪除代碼。 –