使用Asp.net web api下载时出错

时间:2015-05-08 05:52:17

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

我正在使用下面的代码在ASP.NET中使用Web API进行下载。 当我尝试单击下载按钮时,它会调用API。 执行“DownloadFile”功能后,下载对话框不会出现。

[HTTPGET]

    public HttpResponseMessage DownloadFile(string DownloadFilePath)
    {

        HttpResponseMessage result = null;
        var localFilePath = HttpContext.Current.Server.MapPath(DownloadFilePath);

        // check if parameter is valid
        if (String.IsNullOrEmpty(DownloadFilePath))
        {
            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.ContentDisposition.FileName = DownloadFilePath;
        }

        return result;




    }

我没有从上面的代码中得到任何异常,但下载文件的对话框没有到来。

1 个答案:

答案 0 :(得分:1)

以下是我正在使用的代码,效果很好。我希望它会给你一个想法

....
var fileBytes = Helper.GetFileBytes(filePath);//convert file to bytes
                    var stream = new MemoryStream(fileBytes);
                    resp.Content = new StreamContent(stream);
                    resp.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                    resp.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = filerequest.FileName };
                    resp.Content.Headers.Add("Content-Encoding", "UTF-8");               
                    return resp;

而且,这是GetFileBytes方法的代码,

public static byte[] GetFileBytes(string filePath)
        {
            var fileInfo = new FileInfo(filePath);
            if (fileInfo.Exists)
            {
                return File.ReadAllBytes(fileInfo.FullName);
            }
            return null;           
        }
相关问题