使用jquery下载Mvc4 web api文件

时间:2012-11-28 05:02:31

标签: jquery asp.net-mvc asp.net-web-api

我想从api的客户端下载文件   apicontroller:

     public HttpResponseMessage PostOfficeSupplies()
     {
        string csv = string.Format ("D:\\Others\\Images/file.png");
        HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
        result.Content = new StringContent(csv);
        result.Content.Headers.ContentType = new MediaTypeHeaderValue     ("application/octet-stream");

        result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
        result.Content.Headers.ContentDisposition.FileName = "file.png";
        return result;    
    }

1.如何从api控制器中使用jquery(octet-stream)弹出下载?

     my client side code:
     $(document).ready(function () {
            $.ajax(
            {
                url: 'api/MyAPI'
            , type: "post"
            , contentType: "application/octet-stream"
            , data: ''
            , success:
            function (retData) {
                $("body").append("<iframe src='" + retData + "' style='display: none;' ></iframe>");
                               }

            });


});

但是没有用!

1 个答案:

答案 0 :(得分:0)

更改以下代码

result.Content = new StringContent(csv);

到此:

result.Content = new StreamContent(File.OpenRead("D:\\Others\\Images\\file.png"));