如何使用jvery从mvc4 webapi弹出下载

时间:2012-11-29 00:47:24

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

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

 public HttpResponseMessage PostOfficeSupplies()
 {
    HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
    result.Content = new StreamContent(File.OpenRead("D:\\Others\\Images\\file.png"));
    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;    
}

用jquery为我弹出下载的客户端代码(视图)怎么样?

我的客户方:

                 $.ajax(
                    {
                        url: 'api/MyAPI'
                    , type: "post"
                    , contentType: "application/octet-stream"
                    , data: ''
                    , success:
                    function (retData) {
                        $("body").append("<iframe src='" + retData + "' style='display: block;' ></iframe>");
                                        $("#sp123").text(retData);}

                    });       

我只想弹出一个下载

1 个答案:

答案 0 :(得分:0)

我不确定您是否能够使用ajax调用显示下载弹出窗口,但您可以通过提交表单来显示下载确认窗口

<form id="downloadForm" method="post" action="~/api/MyAPI">
 <!--use this if you want to pass any values !-->
 <!--  <input type="hidden" name="Param1" id="Param1HidenValue" /> !-->
</form>

并从JavaScript中调用它

$('#downloadForm').submit();