【问题标题】:Download file from ajax and ActionResult从 ajax 和 ActionResult 下载文件
【发布时间】:2017-06-13 13:18:46
【问题描述】:

我想用 ajax 和 ActionResult 在浏览器上下载文件。该文件从我的 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; }
});

谢谢大家

【问题讨论】:

    标签: ajax asp.net-mvc-4 download actionresult


    【解决方案1】:

    AJAX 只是一个瘦客户端。默认返回的响应没有任何反应。您有责任进行下载。但是,这样做需要作为 HTML5 一部分的 File API。因此,这只能在现代浏览器 (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看看它的工作原理。

    【讨论】:

    • 谢谢,明天早上我会测试这个。
    • 这不起作用,我有这个错误:“无法构造'Blob':第一个参数既不是数组,也没有索引属性”
    • 对不起,但这也不起作用。我收到消息“DOMException:无法从 'XMLHttpRequest' 读取 'responseText' 属性:该值仅在对象的 'responseType' 为 '' 或 'text'(为 'blob')时才可访问。”
    • 不确定你做了什么,但你可以从我的答案中包含的 CodePen 清楚地看到,代码有效。寻找您的代码与我的不同之处,或者至少更新您的问题以包含代码的最新状态。
    • 另外,您使用的是什么版本的 jQuery?如果您仍在 1.* 分支上,那可能是问题的一部分。就像我说的,这段代码需要现代浏览器,并且 jQuery 1.* 保持对 IE7 的支持。
    【解决方案2】:

    我改变了主意。我只是以 64 位发送我的 pdf(来自我的控制器)并在 ajax 中制作:

    success: function (data) {
         window.open("data:application/pdf;base64," + data.data, '_blank'); 
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-12-30
      • 1970-01-01
      • 2018-02-21
      • 2019-10-29
      • 2011-03-30
      • 2016-11-26
      相关资源
      最近更新 更多