ASP.NET WebApi实现文件下载

  • 普通下载
    public class DownLoadController : ApiController
        {
            //响应的MimeType类型
            private const string MimeType = "application/octet-stream";
    
            //待下载文件存放目录
            private readonly string DirFilePath = "D:\\SoftWare";
    
            /// <summary>
            /// 缓冲区大小
            /// </summary>
            private const int BufferSize = 80 * 1024;
    
            // GET api/<controller>
            public HttpResponseMessage Get(string fileName = "SD_GhostWin10X64RS4Pro_228.iso")
            {
                var fullFilePath = Path.Combine(DirFilePath, fileName);
    
                if (!File.Exists(fullFilePath))
                {
                    throw new HttpResponseException(HttpStatusCode.NotFound);
                }
    
                FileStream fileStream = File.Open(fullFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
    
                var response = new HttpResponseMessage();
    
                response.Content = new StreamContent(fileStream, BufferSize);
    
                response.Content.Headers.ContentDisposition
                    = new ContentDispositionHeaderValue("attachment") { FileName = fileName };
    
                response.Content.Headers.ContentType
                    = new MediaTypeHeaderValue(MimeType);
    
                response.Content.Headers.ContentLength
                    = fileStream.Length;
    
                return response;
            }
        }

     

posted @ 2021-08-27 13:50  大龄Coder  阅读(1472)  评论(0)    收藏  举报