Example #1
0
 public async Task <HttpResponseMessage> DownloadAsync([FromUri] DownloadFileDto model)
 {
     return(await DownloadAsync(Request, model));
 }
Example #2
0
        private async Task <HttpResponseMessage> DownloadAsync(HttpRequestMessage request, DownloadFileDto model)
        {
            if (model == null)
            {
                throw new ArgumentNullException("model");
            }

            if (string.IsNullOrWhiteSpace(model.VirtualPath))
            {
                throw new InvalidOperationException("无效的虚拟目录");
            }

            //todo check allowed location from config 防止恶意下载
            if (!model.VirtualPath.ToLower().StartsWith("~/content/upload"))
            {
                throw new InvalidOperationException("不支持的下载路径");
            }

            //var virtualPathRoot = request.GetRequestContext().VirtualPathRoot; // => /
            var server   = HttpContext.Current.Server;
            var filePath = server.MapPath(model.VirtualPath);

            if (!File.Exists(filePath))
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }


            var result = request.CreateResponse(HttpStatusCode.OK);
            //var result = new HttpResponseMessage(HttpStatusCode.OK);
            //var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
            var stream = File.OpenRead(filePath);

            result.Content = new StreamContent(stream);
            result.Content.Headers.ContentType                 = new MediaTypeHeaderValue("application/octet-stream");
            result.Content.Headers.ContentDisposition          = new ContentDispositionHeaderValue("attachment");
            result.Content.Headers.ContentDisposition.FileName =
                string.IsNullOrWhiteSpace(model.FileName)
                ? Path.GetFileName(filePath)
                : model.FileName;
            return(await Task.FromResult(result));
        }
Example #3
0
 public HttpResponseMessage Download([FromUri] DownloadFileDto model)
 {
     //=> ~/api/FileApi/Download?VirtualPath=~/Content/Uploads/1.xlsx&FileName=abc.xlsx
     return(DownloadAsync(model).Result);
 }