使用JQuery AJAX从Web API下载PDF文件

时间:2017-06-04 21:38:48

标签: javascript jquery ajax asp.net-web-api2

我有一个web api方法,它返回一个文件。控制器方法如下:

        public HttpResponseMessage Get(string id)
        {
            HttpResponseMessage result = null;
            var localFilePath = HttpContext.Current.Server.MapPath("~/" + id);

            // check if parameter is valid
            if (String.IsNullOrEmpty(id))
            {
                result = Request.CreateResponse(HttpStatusCode.BadRequest);
            }
            // check if file exists on the server
            else if (!File.Exists(localFilePath))
            {
                result = Request.CreateResponse(HttpStatusCode.Gone);
            }
            else
            {// serve the file to the client
                result = Request.CreateResponse(HttpStatusCode.OK);
                result.Content = new StreamContent(new FileStream(localFilePath, FileMode.Open, FileAccess.Read));
                result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
                result.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/pdf");
                result.Content.Headers.ContentDisposition.FileName = id;
            }

            return result;
        }       

我需要编写一个示例html,它会调用此api并从html页面下载该文件。我怎么能用$ .ajax或其他方式做到这一点?

此致 约翰

0 个答案:

没有答案
相关问题