0

我有 web api 控制器方法来下载 excel 文件,通过将“FileName”作为参数传递,任何人都可以帮助我如何使用 $.Ajax 或任何其他可能的方式下载文件。

API 控制器方法

[HttpPost]
[Route("api/POSTargets/DownloadFile")]
public HttpResponseMessage DownloadExcel(string FileName)
    {
        var filePath = @"~/POSTarget/" + FileName;

        var path = HttpContext.Current.Server.MapPath(filePath);
        if (path != null)
            return FileAsAttachment(path, "Errors POS Target.xlsx");
        return new HttpResponseMessage(HttpStatusCode.NotFound);
    }


    public static HttpResponseMessage FileAsAttachment(string path, string filename)
    {
        HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
        var stream = new FileStream(path, FileMode.Open);
        result.Content = new StreamContent(stream);
        result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
        result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
        result.Content.Headers.ContentDisposition.FileName = filename;
        return result;
    }

- -看法

 function downloadFile() {
        debugger;
        var fileName= "Error POS Target372016182355.xlsx";
        $.ajax({
            url: "http://localhost/RPMS/api/POSTargets/DownloadFile",
            type: "POST",
            data: fileName
        }).done(function (data) {
            alert(data);
        }).error(function (data) {
           alert(data);
        });


    }
4

0 回答 0