从 ajax 和 ActionResult 下载文件
Download file from ajax and ActionResult
我想使用 ajax 和 ActionResult 在浏览器上下载文件。该文件已下载并从我的 ActionResult 返回。
我看到 Http 查询正常,并在响应正文中看到数据。问题是文件不建议保存在浏览器中
一切似乎都很好。我在教程和论坛中看到的所有内容都与我所做的一样,但我没有写 XD。我不明白我的和别人的有什么区别
这是我的操作结果:
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; }
});
谢谢大家
AJAX 只是一个瘦客户端。默认返回的响应没有任何反应。您有责任进行下载。但是,这样做需要文件 API,它是 HTML5 的一部分。因此,这只能在现代浏览器 (IE10+) 中实现。
在您的 AJAX 成功方法中:
var blob = new Blob(data, { type: 'application/pdf' });
var a = document.createElement('a');
var url = window.URL.createObjectURL(blob);
a.href = url;
a.download = 'myfile.pdf';
a.click();
window.URL.revokeObjectURL(url);
编辑
默认情况下,jQuery 不会正确解释响应类型。您需要稍微修改 $.ajax 调用:
$.ajax({
url: '../Shipping/ShippingDownloadDNPriority?SALE_GUID=XXXXXXXXXXXXXX',
data: { SALE_GUID: DropShipping.GetRowKey(rowIndexSale) },
async: false,
// -- ADD THIS --
xhrFields: {
responseType: 'blob'
},
success: function (data) {
// code above here, but no longer need to create blob
var a = document.createElement('a');
var url = window.URL.createObjectURL(data);
a.href = url;
a.download = 'myfile.pdf';
a.click();
window.URL.revokeObjectURL(url);
}
});
您可以check out a CodePen here查看它的工作情况。
我改变主意了。我只是将我的 pdf(来自我的控制器)发送到 64 base 并输入 ajax :
success: function (data) {
window.open("data:application/pdf;base64," + data.data, '_blank');
}
我想使用 ajax 和 ActionResult 在浏览器上下载文件。该文件已下载并从我的 ActionResult 返回。
我看到 Http 查询正常,并在响应正文中看到数据。问题是文件不建议保存在浏览器中
一切似乎都很好。我在教程和论坛中看到的所有内容都与我所做的一样,但我没有写 XD。我不明白我的和别人的有什么区别
这是我的操作结果:
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; }
});
谢谢大家
AJAX 只是一个瘦客户端。默认返回的响应没有任何反应。您有责任进行下载。但是,这样做需要文件 API,它是 HTML5 的一部分。因此,这只能在现代浏览器 (IE10+) 中实现。
在您的 AJAX 成功方法中:
var blob = new Blob(data, { type: 'application/pdf' });
var a = document.createElement('a');
var url = window.URL.createObjectURL(blob);
a.href = url;
a.download = 'myfile.pdf';
a.click();
window.URL.revokeObjectURL(url);
编辑
默认情况下,jQuery 不会正确解释响应类型。您需要稍微修改 $.ajax 调用:
$.ajax({
url: '../Shipping/ShippingDownloadDNPriority?SALE_GUID=XXXXXXXXXXXXXX',
data: { SALE_GUID: DropShipping.GetRowKey(rowIndexSale) },
async: false,
// -- ADD THIS --
xhrFields: {
responseType: 'blob'
},
success: function (data) {
// code above here, but no longer need to create blob
var a = document.createElement('a');
var url = window.URL.createObjectURL(data);
a.href = url;
a.download = 'myfile.pdf';
a.click();
window.URL.revokeObjectURL(url);
}
});
您可以check out a CodePen here查看它的工作情况。
我改变主意了。我只是将我的 pdf(来自我的控制器)发送到 64 base 并输入 ajax :
success: function (data) {
window.open("data:application/pdf;base64," + data.data, '_blank');
}