我想用ajax和ActionResult在瀏覽器上下載文件。該文件被下載並從我的ActionResult返回。從ajax和ActionResult下載文件
我看到Http查詢沒問題,看到響應正文中的數據。問題是該文件不建議保存在瀏覽器中。
一切似乎都不錯。我在教程和論壇中看到的所有內容都和我所做的一樣,但是我不會說XD。我不明白我和其他人有什麼不同。
這裏是我的ActionResult:
public ActionResult ShippingDownloadDNPriority(string SALE_GUID)
{
int supId = -1;
int.TryParse(Session["SupId"].ToString(), out supId);
if (supId < 0)
return null;
WebResponse response = CallApi.DownloadAndCreateDN(Session["UserLogin"].ToString(), Session["IdentConnect"].ToString(), SALE_GUID, supId, true);
Stream responseStream = response.GetResponseStream();
var cd = new System.Net.Mime.ContentDisposition
{
FileName = "myfile.pdf",
Inline = false,
};
Response.Headers.Add("Content-Disposition", cd.ToString());
Response.ContentType = "application/octet-stream";
return File(responseStream, System.Net.Mime.MediaTypeNames.Application.Pdf, "myfile.pdf");
}
public static WebResponse DownloadAndCreateDN(string login, string session, string SALE_GUID, int supid, bool priority)
{
string[] res = new string[2];
StringBuilder postData = new StringBuilder();
postData.AppendLine("{");
postData.AppendLine(string.Format("\"login\":\"{0}\",", login));
postData.AppendLine(string.Format("\"session\":\"{0}\",", session));
postData.AppendLine(string.Format("\"saleguid\":\"{0}\",", SALE_GUID));
postData.AppendLine(string.Format("\"supid\":{0},", supid));
postData.AppendLine(string.Format("\"prority\":{0}", priority.ToString().ToLower()));
postData.AppendLine("}");
ASCIIEncoding ascii = new ASCIIEncoding();
byte[] postBytes = ascii.GetBytes(postData.ToString());
string url = Properties.Settings.Default.ISAPIAddress + "deliverynote/create";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/json";
request.ContentLength = postBytes.Length;
Stream postStream = request.GetRequestStream();
postStream.Write(postBytes, 0, postBytes.Length);
postStream.Flush();
postStream.Close();
return request.GetResponse();
}
這裏是我的javascript:
$.ajax({
url: '../Shipping/ShippingDownloadDNPriority?SALE_GUID=XXXXXXXXXXXXXX',
data: { SALE_GUID: DropShipping.GetRowKey(rowIndexSale) },
async: false,
//success: function (data) { window.downloadFile = data; }
});
感謝所有
謝謝,我會明天測試這moring。 – Gobelet
這不起作用,我有這個錯誤:「無法構造'Blob':第一個參數既不是數組,也沒有索引屬性」 – Gobelet
請參閱上面的編輯。 –