簡體   English   中英

如何下載服務器在 Ajax 調用中返回的文件?

[英]How do I download a file that is returned by the server in an Ajax call?

我有一個下載函數,其中的想法是當用戶單擊按鈕時,它會調用一個函數,該函數將創建一個包含用戶正在查看的所有信息的 csv 文件,並將該文件作為下載返回。 我有創建 csv 文件的服務器功能,但我不確定如何下載它。 這是我的服務器端代碼:

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

    var csv = new StringBuilder();

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

    var customer = order.CustomerNumber;
    var billToName = order.BTDisplayName;
    var shipToName = order.ShipTo.CustomerName;
    var orderNum = order.OrderNumber;
    var orderDate = order.OrderDate;
    var carrier = order.ShippingDisplay;
    var notes = order.Notes;
    var subtotal = order.OrderSubTotalDisplay;
    var total = order.OrderGrandTotalDisplay;
    var shipping = order.ShippingAndHandling;
    var tax = order.TotalSalesTaxDisplay;
    var patient = "";
    var purchaseOrder = order.CustomerPO;
    foreach (var cartLine in order.OrderLines)
    {
        var line = cartLine.Line;
        var itemNum = cartLine.Product.ProductCode;
        var itemDesc = cartLine.Description;
        var qty = cartLine.QtyOrdered;
        var uom = cartLine.UnitOfMeasure;
        var price = cartLine.ActualPriceDisplay;
        var ext = cartLine.ExtendedActualPriceDisplay;

        //Customer,Bill To Name,Ship To Name,Patient,Order#,Order Date," + 
        //"Line,Item#,Item Description,Qty,UOM,Price,Ext Price,Carrier," +
        //"Notes,Purchase Order
        var newLine = string.Format("{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},{13},{14},{15}",
            customer, billToName, shipToName, patient, orderNum, orderDate, line, itemNum, itemDesc,
            qty, uom, price, ext, carrier, notes, purchaseOrder);

        csv.AppendLine(newLine);
    }

    csv.AppendLine();
    csv.AppendLine("Subtotal,Shipping & Handling,Tax,Total");
    csv.AppendLine(string.Format("{0},{1},{2},{3}", subtotal, shipping, tax, total));

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

    var bytes = Encoding.UTF8.GetBytes(csv.ToString());
    return this.File(bytes, "text/csv");
}

這是 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) {
            alert("downloaded");
        },
        error: function (ex) {
            console.log(ex);
        }
    });    
}

在ajax調用成功時,我檢查了“data”的值,它有信息,但我不知道如何下載。 收到數據后怎么辦?

你不能通過這樣的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>

您可以將文件存儲在服務器上並發送帶有響應的 URL。 然后在ajax上成功函數window.location=data.URL

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);
        }
    });    
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM