【问题标题】:Error on Downloading From using Asp.net web api使用 Asp.net web api 下载时出错
【发布时间】:2015-07-18 22:44:00
【问题描述】:

我正在使用下面的代码通过 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;




    }

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

【问题讨论】:

  • 尝试在你的方法中加入try-catch,看看会不会有错误。
  • 在 try catch 中没有得到任何异常
  • "rob waminal" 是否需要更改网页配置?

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


【解决方案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;           
        }

【讨论】:

    猜你喜欢
    • 2012-08-30
    • 2019-11-22
    • 1970-01-01
    • 2014-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多