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

标签 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;




    }

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

最佳答案

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

....
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;           
        }

关于javascript - 使用 Asp.net web api 下载时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30116673/

相关文章:

c# - 远程处理异常 : Object 'xxx.rem' has been disconnected or does not exist at the server

javascript - 如何保留这个 jQuery 事件处理程序?

JavaScript 添加两个数字,添加与连接,FCC 高尔夫代码挑战

javascript - Uncaught ReferenceError : app is not defined in Angularjs

javascript - React.js 如何在内部组件中找到 ref 元素

javascript - Ajax 内容加载后运行每个函数

jquery - 使用 jQuery 根据按钮文本更改按钮上的 CSS 属性

javascript - 当有多个可编辑文本区域时,Tinymce 模糊功能不起作用

c# - MVC3 在 1 个 View 中显示来自 1 个以上实体的信息

asp.net - 是否可以在 ApplicationServices DB 中对电子邮件地址进行加密?