如何在Ajax调用中下载服务器返回的文件?

时间:2015-11-11 16:41:18

标签: javascript c# jquery ajax csv

我有一个下载功能,其中的想法是,当用户单击一个按钮时,它会对一个函数执行ajax调用,该函数将创建一个包含用户正在查看的所有信息的csv文件,并将该文件作为下载。我有服务器功能创建一个csv文件,但我不知道如何下载。这是我的服务器端代码:

function download(customerOrderId) {
    $.ajax({
        url: insite.core.actionPrefix + '/Checkout/Download/?customerOrderId=' + customerOrderId,
        type: 'Post',
        contentType: "application/json; charset=utf-8",
        async: false,
        cache: false,
        success: function (data) {
            alert("downloaded");
        },
        error: function (ex) {
            console.log(ex);
        }
    });    
}

这是ajax方法:

OFFSET

在ajax调用成功的过程中,我检查了" data"的值。它有信息,但我不知道如何下载。收到数据后我该怎么办?

3 个答案:

答案 0 :(得分:1)

你能不能通过像这样的href下载它?

public FileContentResult Download(Guid customerOrderId)
{
    // your code

    var response = new FileContentResult(bytes, "text/csv");
    response.FileDownloadName = filename;
    return response;
}

链接:

<a href="Checkout/Download/?customerOrderId=someId">Download</a>

答案 1 :(得分:0)

您可以将文件存储在服务器上并发送带响应的URL。然后在ajax成功函数window.location = data.URL

答案 2 :(得分:0)

Venerik也有一个有效的答案,但是与你当前的实施保持一致,我建议如下。

将文件保存到服务器后,可以返回URL的字符串。然后在成功时进行窗口位置重定向。我删除了变量赋值,因为除了发送到方法之外没有其他任何操作。

这里我们编写文件并返回字符串。您需要调整return以匹配您的网站信息等。

public ActionResult Download(Guid customerOrderId)
{
    var order = this.UnitOfWork.GetRepository<CustomerOrder>().Get(customerOrderId);

    var csv = new StringBuilder();

    csv.AppendLine("Customer,Bill To Name,Ship To Name,Patient,Order#,Order Date," +
        "Line,Item#,Item Description,Qty,UOM,Price,Ext Price,Carrier," +
        "Notes,Purchase Order");

    foreach (var cartLine in order.OrderLines)
    {
        //Customer,Bill To Name,Ship To Name,Patient,Order#,Order Date," + 
        //"Line,Item#,Item Description,Qty,UOM,Price,Ext Price,Carrier," +
        //"Notes,Purchase Order

        csv.AppendLine(string.Format("{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},{13},{14},{15}",
            order.CustomerNumber, order.BTDisplayName, order.ShipTo.CustomerName, "", order.OrderNumber, order.OrderDate, cartLine.Line, cartLine.Product.ProductCode, cartLine.Description,
            cartLine.QtyOrdered, cartLine.UnitOfMeasure, cartLine.ActualPriceDisplay, cartLine.ExtendedActualPriceDisplay, order.ShippingDisplay, order.Notes, order.CustomerPO));
    }

    csv.AppendLine();
    csv.AppendLine("Subtotal,Shipping & Handling,Tax,Total");
    csv.AppendLine(string.Format("{0},{1},{2},{3}", order.OrderSubTotalDisplay, order.ShippingAndHandling, order.TotalSalesTaxDisplay, order.OrderGrandTotalDisplay));

    var filename = "MSD-Order-" + orderNum + ".csv";  

    using (StreamWriter sw = File.CreateText(Server.MapPath("~/files/" + filename)) 
    {
        sw.Write(csv.ToString());
    } 

    // adjust your url accordingly to match the directory to which you saved
    // '/files/' corresponds to where you did the File.CreateText
    // returning Content in an ActionResult defaults to text
    return Content("http://foo.com/files/" + filename);
}

在您的AJAX方法中更新您的成功函数以重定向将提示下载的页面:

function download(customerOrderId) {
    $.ajax({
        url: insite.core.actionPrefix + '/Checkout/Download/?customerOrderId=' + customerOrderId,
        type: 'Post',
        contentType: "application/json; charset=utf-8",
        async: false,
        cache: false,
        success: function (data) {
            window.location.href = data;
        },
        error: function (ex) {
            console.log(ex);
        }
    });    
}