コード例 #1
0
        private async Task WriteFileAsync(ActionContext context, PhysicalFileResult result)
        {
            var response = context.HttpContext.Response;

            if (!Path.IsPathRooted(result.FileName))
            {
                throw new NotSupportedException(Resources.FormatFileResult_PathNotRooted(result.FileName));
            }

            var sendFile = response.HttpContext.Features.Get<IHttpSendFileFeature>();
            if (sendFile != null)
            {
                await sendFile.SendFileAsync(
                    result.FileName,
                    offset: 0,
                    count: null,
                    cancellation: default(CancellationToken));
            }
            else
            {
                var fileStream = GetFileStream(result.FileName);

                using (fileStream)
                {
                    await fileStream.CopyToAsync(response.Body, DefaultBufferSize);
                }
            }
        }
コード例 #2
0
        public async Task <IActionResult> FileAsync(FullPath path, bool download)
        {
            IActionResult result;

            if (path.IsDirectory)
            {
                return(new ForbidResult());
            }

            if (!await path.File.ExistsAsync)
            {
                return(new NotFoundResult());
            }

            if (path.RootVolume.IsShowOnly)
            {
                return(new ForbidResult());
            }

            string contentType = download ? "application/octet-stream" : MimeHelper.GetMimeType(path.File.Extension);

            result = new PhysicalFileResult(path.File.FullName, contentType);

            return(await Task.FromResult(result));
        }
コード例 #3
0
        public async Task <PhysicalFileResult> ReadPhysicalFileByPermission(int documentID, int userID, string permission)
        {
            try
            {
                var document = await base.GetAsync(documentID);

                var filePath = $"{_rootUrl}{document.FilePath}";
                //override path
                filePath = filePath.Replace('\\', Path.DirectorySeparatorChar);
                var filePathWaterMark = filePath;
                //check if the user has permission to generate without the water mark
                var user = await _userService.GetAsync(userID);

                var roleIDs = user.Roles.Select(r => r.ID);
                //var menus = await FindByAsync(x => x.MenuRoles.Any(y => y.IsActive && roleIDs.Contains(y.RoleID)));
                var permissions = (await _rolePermissionService.FindByAsync(x => x.IsActive && roleIDs.Contains(x.RoleID))).Select(rp => rp.Permission.PermissionCode);

                if (document.ModuleDocument.DocumentType.IsSystemGenerated && !permissions.Contains(permission) && waterMarkedDocuments.Contains(document.ModuleDocument.DocumentType.DocumentTypeCode))
                {
                    filePathWaterMark = filePath.Replace(document.ModuleDocument.DocumentType.Name, $"{document.ModuleDocument.DocumentType.Name} Water-Marked");
                    await GenerateWaterMark(filePath, filePathWaterMark);
                }

                var result = new PhysicalFileResult(filePathWaterMark, document.FileType);
                return(result);
            } catch (Exception ex) {
                _logger.Log(ex);
            }
            return(null);
        }
コード例 #4
0
        public async Task <string> GetReportDetails(int reportNumber)
        {
            string staticResourcesPathBase = _webHostEnvironment.WebRootPath;
            string outFileName             = $"{DateTime.Now.ToString("yymmssfff")}-report.pdf";
            string fullOutFileName         = Path.Combine(staticResourcesPathBase, $"{DateTime.Now.ToString("yymmssfff")}-report.pdf");


            string sourceFilePath = string.Empty;

            switch (reportNumber)
            {
            case 0:
                sourceFilePath = Path.Combine(staticResourcesPathBase, "team1Report.xlsx");
                break;

            case 1:
                sourceFilePath = Path.Combine(staticResourcesPathBase, "team2Report.xlsx");
                break;

            case 2:
                sourceFilePath = Path.Combine(staticResourcesPathBase, "team3Report.xlsx");
                break;
            }


            var convertedFile = await ExcelToPDFConverter.GetConvertedResponseBySource(sourceFilePath, fullOutFileName);

            var phResult = new PhysicalFileResult(convertedFile.FullName, "application/pdf");

            return(outFileName);
        }
コード例 #5
0
        private async Task WriteFileAsync(ActionContext context, PhysicalFileResult result)
        {
            var response = context.HttpContext.Response;

            if (!Path.IsPathRooted(result.FileName))
            {
                throw new NotSupportedException(Resources.FormatFileResult_PathNotRooted(result.FileName));
            }

            var sendFile = response.HttpContext.Features.Get <IHttpSendFileFeature>();

            if (sendFile != null)
            {
                await sendFile.SendFileAsync(
                    result.FileName,
                    offset : 0,
                    count : null,
                    cancellation : default(CancellationToken));
            }
            else
            {
                var fileStream = GetFileStream(result.FileName);

                using (fileStream)
                {
                    await fileStream.CopyToAsync(response.Body, DefaultBufferSize);
                }
            }
        }
コード例 #6
0
        public async Task <IActionResult> File(string target, bool download)
        {
            IActionResult result;

            FullPath fullPath = ParsePath(target);

            if (fullPath.IsDirectory)
            {
                result = new ForbidResult();
            }
            if (!fullPath.File.Exists)
            {
                result = new NotFoundResult();
            }
            if (fullPath.Root.IsShowOnly)
            {
                result = new ForbidResult();
            }
            //result = new DownloadFileResult(fullPath.File, download);
            string contentType = download ? "application/octet-stream" : Utils.GetMimeType(fullPath.File);

            result = new PhysicalFileResult(fullPath.File.FullName, contentType);

            return(await Task.FromResult(result));
        }
コード例 #7
0
        public IActionResult Download(string id)
        {
            PhysicalFileResult file = GetFileResult(id);

            file.FileDownloadName = Path.GetFileName(file.FileName);

            return(file);
        }
コード例 #8
0
        public IActionResult DokumentPDF(string file)
        {
            var path = Path.Combine(Directory.GetCurrentDirectory(), file);

            var dfile = new PhysicalFileResult(path, "application/pdf");

            return(dfile);
        }
コード例 #9
0
        public IActionResult OnGet(string fileName)
        {
            if (string.IsNullOrEmpty(fileName))
            {
                return(NotFound());
            }

            var path = Path.Combine(_imageDirectory, fileName);

            if (System.IO.File.Exists(path))
            {
                if (Path.GetDirectoryName(path) == _imageDirectory)
                {
                    var            fi     = new FileInfo(path);
                    var            length = fi.Length;
                    DateTimeOffset last   = fi.LastWriteTime;
                    // Truncate to the second.
                    var lastModified = new DateTimeOffset(last.Year, last.Month, last.Day, last.Hour, last.Minute, last.Second, last.Offset).ToUniversalTime();

                    long etagHash = lastModified.ToFileTime() ^ length;
                    var  etag_str = '\"' + Convert.ToString(etagHash, 16) + '\"';

                    string incomingEtag = (Request.Headers as FrameRequestHeaders).HeaderIfNoneMatch;

                    if (String.Compare(incomingEtag, etag_str) == 0)
                    {
                        Response.Clear();
                        Response.StatusCode = (int)System.Net.HttpStatusCode.NotModified;
                        return(new StatusCodeResult((int)System.Net.HttpStatusCode.NotModified));
                    }
                    var etag = new EntityTagHeaderValue(etag_str);

                    //var fs = new FileStream(path, FileMode.Open, FileAccess.Read);
                    PhysicalFileResult pfr = base.PhysicalFile(path, "image/jpg");
                    pfr.EntityTag = etag;

                    return(pfr);

                    //var image = new FileInfo(path);
                    //if (!String.IsNullOrEmpty(Request.Headers["If-Modified-Since"]))
                    //{
                    //	CultureInfo provider = CultureInfo.InvariantCulture;
                    //	var lastMod = DateTime.ParseExact(Request.Headers["If-Modified-Since"], "r", provider).ToLocalTime();
                    //	if (lastMod == image.LastWriteTime.AddMilliseconds(-image.LastWriteTime.Millisecond))
                    //	{
                    //		Response.StatusCode = 304;
                    //		//Response.StatusDescription = "Not Modified";
                    //		return Content(String.Empty);
                    //	}
                    //}
                    //var stream = new MemoryStream(image.GetImage());
                    //Response.Cache.SetCacheability(HttpCacheability.Public);
                    //Response.Cache.SetLastModified(image.TimeStamp);
                    //return File(stream, image.MimeType);
                }
            }
            return(NotFound());
        }
コード例 #10
0
        public PhysicalFileResult GetBook(SpecificEBookViewModel eBookViewModel)
        {
            var fileToReturn = new PhysicalFileResult(eBookViewModel.Path, "application/text")
            {
                FileDownloadName = eBookViewModel.Title
            };

            return(fileToReturn);
        }
        public void WithFileDownloadName_GivenExpected_ShouldPass()
        {
            ActionResult result = new PhysicalFileResult(string.Empty, TestContentType)
            {
                FileDownloadName = TestFileDownloadName
            };

            result.Should().BePhysicalFileResult().WithFileDownloadName(TestFileDownloadName);
        }
コード例 #12
0
 public IActionResult GetFile(Photo photo)
 {
     string file_path = Path.Combine(_appEnvironment.ContentRootPath, $"wwwroot{photo.Path}");
     string MyString = Path.GetExtension(photo.Path);
     string NewString = MyString.TrimStart('.');
     string file_type = $"application/{NewString}";
     PhysicalFileResult res = PhysicalFile(file_path, file_type,photo.PhotoId + "." + NewString);
     return res;
 }
        public void WithEntityTag_GivenExpected_ShouldPass()
        {
            ActionResult result = new PhysicalFileResult(string.Empty, TestContentType)
            {
                EntityTag = TestEntityTag
            };

            result.Should().BePhysicalFileResult().WithEntityTag(TestEntityTag);
        }
コード例 #14
0
        public IActionResult Get(string name)
        {
            string path = Path.Join(BasePath, name);
            //PhysicalFileResult result = PhysicalFile(path, "image/jpg");
            FileStream         file   = new FileStream(path, FileMode.Open);
            PhysicalFileResult result = PhysicalFile(path, "image/jpg");

            return(result);
        }
        public void WithLastModified_GivenExpected_ShouldPass()
        {
            ActionResult result = new PhysicalFileResult(string.Empty, TestContentType)
            {
                LastModified = TestLastModified
            };

            result.Should().BePhysicalFileResult().WithLastModified(TestLastModified);
        }
コード例 #16
0
        public async Task <FileResult> PlayMovieByIDAsync(string id, int season, int episode)
        {
            Console.WriteLine(id);
            string movieDir = await m_mediaDatabase.GetFilePathAsync(id, season, episode);

            PhysicalFileResult file = PhysicalFile(movieDir, "video/webm", true);

            return(file);
        }
        public void WithLastModified_GivenNull_ShouldPass()
        {
            var          actualLastModified   = null as DateTimeOffset?;
            var          expectedLastModified = null as DateTimeOffset?;
            ActionResult result = new PhysicalFileResult(string.Empty, TestContentType)
            {
                LastModified = actualLastModified
            };

            result.Should().BePhysicalFileResult().WithLastModified(expectedLastModified);
        }
        public void WithContentType_GivenUnexpected_ShouldFail()
        {
            var          actualContentType   = TestContentType;
            var          expectedContentType = "xyz";
            ActionResult result         = new PhysicalFileResult(string.Empty, actualContentType);
            var          failureMessage = FailureMessageHelper.ExpectedContextToBeXButY("PhysicalFileResult.ContentType", expectedContentType, actualContentType);

            Action a = () => result.Should().BePhysicalFileResult().WithContentType(expectedContentType, Reason, ReasonArgs);

            a.Should().Throw <Exception>().WithMessage(failureMessage);
        }
        public void WithPhysicalPath_GivenUnexpected_ShouldFail()
        {
            var          actualPhysicalPath   = TestPhysicalPath;
            var          expectedPhysicalPath = "xyz";
            ActionResult result         = new PhysicalFileResult(actualPhysicalPath, TestContentType);
            var          failureMessage = FailureMessageHelper.ExpectedContextToBeXButY("PhysicalFileResult.PhysicalPath", expectedPhysicalPath, actualPhysicalPath);

            Action a = () => result.Should().BePhysicalFileResult().WithPhysicalPath(expectedPhysicalPath, Reason, ReasonArgs);

            a.Should().Throw <Exception>().WithMessage(failureMessage);
        }
コード例 #20
0
ファイル: UsersController.cs プロジェクト: yuaruel/Monivault
        public FileResult DownloadUserUploadSampleFile()
        {
            var fileInfo = _fileProvider.GetFileInfo("wwwroot/user_upload_sample.xlsx");

            var physicalFileResult = new PhysicalFileResult(fileInfo.PhysicalPath, MimeTypeNames.ApplicationOctetStream)
            {
                FileDownloadName = "UserUploadFileSample.xlsx"
            };

            return(physicalFileResult);
        }
コード例 #21
0
        public IActionResult GetCssFile()
        {
            string wwwPath     = environment.WebRootPath;
            string contentPath = environment.ContentRootPath;
            string fileName    = "site.css";
            string filePath    = Path.Combine(wwwPath, "css", fileName);
            // https://developer.mozilla.org/zh-TW/docs/Web/HTTP/Basics_of_HTTP/MIME_types#%E9%87%8D%E8%A6%81%E7%9A%84mime%E9%A1%9E%E5%88%A5
            string             contentType = "text/css";
            PhysicalFileResult fileResult  = new PhysicalFileResult(filePath, contentType);

            return(fileResult);
        }
コード例 #22
0
        /// <summary>
        /// Called on GET.
        /// </summary>
        /// <param name="configuration">The configuration.</param>
        /// <param name="serverTiming">The server timing.</param>
        /// <param name="fileName">Name of the file.</param>
        /// <returns></returns>
        public IActionResult OnGet([FromServices] IConfiguration configuration, [FromServices] IServerTiming serverTiming, string fileName)
        {
            var watch = new Stopwatch();

            watch.Start();

            string imageDirectory = configuration["ImageDirectory"];

            if (string.IsNullOrEmpty(fileName) || string.IsNullOrEmpty(imageDirectory))
            {
                serverTiming.Metrics.Add(new Lib.AspNetCore.ServerTiming.Http.Headers.ServerTimingMetric("GET", watch.ElapsedMilliseconds, "error"));
                return(NotFound("No image directory present"));
            }

            string path = Path.Combine(imageDirectory, fileName);

            if (System.IO.File.Exists(path))
            {
                if (Path.GetDirectoryName(path) == imageDirectory)
                {
                    var            fi     = new FileInfo(path);
                    var            length = fi.Length;
                    DateTimeOffset last   = fi.LastWriteTime;
                    // Truncate to the second.
                    var lastModified = new DateTimeOffset(last.Year, last.Month, last.Day, last.Hour, last.Minute, last.Second, last.Offset).ToUniversalTime();

                    long etagHash = lastModified.ToFileTime() ^ length;
                    var  etag_str = $"\"{Convert.ToString(etagHash, 16)}\"";

                    if (Request.Headers.TryGetValue(HeaderNames.IfNoneMatch, out StringValues incomingEtag) &&
                        string.Compare(incomingEtag[0], etag_str) == 0)
                    {
                        Response.Clear();
                        Response.StatusCode = (int)HttpStatusCode.NotModified;
                        serverTiming.Metrics.Add(new Lib.AspNetCore.ServerTiming.Http.Headers.ServerTimingMetric("GET", watch.ElapsedMilliseconds, "NotModified GET"));

                        return(new StatusCodeResult((int)HttpStatusCode.NotModified));
                    }
                    var etag = new EntityTagHeaderValue(etag_str);

                    //var fs = new FileStream(path, FileMode.Open, FileAccess.Read);
                    PhysicalFileResult pfr = base.PhysicalFile(path, MediaTypeNames.Image.Jpeg);
                    pfr.EntityTag = etag;
                    //pfr.LastModified = lastModified;
                    serverTiming.Metrics.Add(new Lib.AspNetCore.ServerTiming.Http.Headers.ServerTimingMetric("GET", watch.ElapsedMilliseconds, "full file GET"));

                    return(pfr);
                }
            }
            serverTiming.Metrics.Add(new Lib.AspNetCore.ServerTiming.Http.Headers.ServerTimingMetric("GET", watch.ElapsedMilliseconds, "not found GET"));
            return(NotFound());
        }
        public void WithLastModified_GivenUnexpected_ShouldFail()
        {
            var          actualLastModified   = TestLastModified;
            var          expectedLastModified = TestLastModified.Value.AddMilliseconds(1);
            ActionResult result = new PhysicalFileResult(string.Empty, TestContentType)
            {
                LastModified = actualLastModified
            };
            var failureMessage = FailureMessageHelper.ExpectedContextToBeXButY("PhysicalFileResult.LastModified", expectedLastModified, actualLastModified);

            Action a = () => result.Should().BePhysicalFileResult().WithLastModified(expectedLastModified, Reason, ReasonArgs);

            a.Should().Throw <Exception>().WithMessage(failureMessage);
        }
コード例 #24
0
        public IActionResult OnPostAllInventory()
        {
            string filename = DateTime.Now.ToString("MMddyyyyhhmm") + ".csv";
            string filepath = @"wwwroot\csv\" + filename;

            using (StreamWriter streamWriter = new StreamWriter(filepath))
            {
                CsvWriter writer = new CsvWriter(streamWriter);
                writer.WriteRecords(_lensData.Lenses.Include(m => m.Material).ToList());
            }
            PhysicalFileResult result = new PhysicalFileResult(Path.Combine(_env.ContentRootPath, filepath), "text/csv");

            return(result);
        }
コード例 #25
0
        public virtual Task <FileResult> GetBackup()
        {
            string outputFile = $"{_backupFolder}/backup.zip";

            if (File.Exists(outputFile))
            {
                File.Delete(outputFile);
            }

            ZipFile.CreateFromDirectory(_folder, outputFile);

            var pfr = new PhysicalFileResult(outputFile, "application/zip");

            return(Task.FromResult((FileResult)pfr));
        }
        public void WithEntityTag_GivenUnexpected_ShouldFail()
        {
            var          actualEntityTag   = TestEntityTag;
            var          expectedEntityTag = new EntityTagHeaderValue("\"1234\"");
            ActionResult result            = new PhysicalFileResult(string.Empty, TestContentType)
            {
                EntityTag = actualEntityTag
            };
            var failureMessage = FailureMessageHelper.ExpectedContextToBeXButY("PhysicalFileResult.EntityTag", expectedEntityTag, actualEntityTag);

            Action a = () => result.Should().BePhysicalFileResult().WithEntityTag(expectedEntityTag, Reason, ReasonArgs);

            a.Should().Throw <Exception>()
            .WithMessage(failureMessage);
        }
コード例 #27
0
        /// <summary>
        /// 尝试下载
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public Task <FileResult> Download(string guid)
        {
            return(Task.Factory.StartNew <FileResult>(() =>
            {
                var success = CheckCanDownload(guid);
                if (!success)
                {
                    string message = null;
                    var guidNotFound = !ConfigHelper.CodeCollection.ContainsKey(guid);
                    if (guidNotFound)
                    {
                        message = "审核失败,请从官方下载页面进入!";
                    }
                    else
                    {
                        var codeRecord = ConfigHelper.CodeCollection[guid];
                        if (!codeRecord.AllowDownload)
                        {
                            message = string.Format("审核失败,文件不允许下载,或已经下载过!如需重新下载请刷新浏览器!(101 - {0})", guid);
                        }
                    }

                    message = message ?? string.Format("未通过审核,或此二维码已过期,请刷新网页后重新操作!(102 - {0})", guid);

                    var file = File(Encoding.UTF8.GetBytes(message), "text/plain");
                    file.FileDownloadName = "下载失败.txt";
                    return file;
                }
                else
                {
                    var codeRecord = ConfigHelper.CodeCollection[guid];
                    codeRecord.Used = true;
                    //codeRecord.AllowDownload = false;//这里如果只允许一次下载,有的浏览器插件或者防护软件会自动访问页面上的链接,导致用户真实的下载时效
                    var configHelper = new ConfigHelper(this.HttpContext);
                    var filePath = configHelper.Download(codeRecord.Version, codeRecord.IsWebVersion);

                    //FileStream fs= new FileStream(filePath, FileAccess.Read);

                    var file = new PhysicalFileResult(filePath, "application/octet-stream");

                    file.FileDownloadName = string.Format("Senparc.Weixin{0}-v{1}.rar",
                                                          codeRecord.IsWebVersion?"-Web":"",
                                                          codeRecord.Version);
                    return file;
                }
            }));
        }
コード例 #28
0
        protected virtual Task WriteFileAsync(ActionContext context, PhysicalFileResult result, RangeItemHeaderValue range, long rangeLength)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (result == null)
            {
                throw new ArgumentNullException(nameof(result));
            }

            if (range != null && rangeLength == 0)
            {
                return(Task.CompletedTask);
            }

            var response = context.HttpContext.Response;

            if (!Path.IsPathRooted(result.FileName))
            {
                throw new NotSupportedException(Resources.FormatFileResult_PathNotRooted(result.FileName));
            }

            var sendFile = response.HttpContext.Features.Get <IHttpSendFileFeature>();

            if (sendFile != null)
            {
                if (range != null)
                {
                    return(sendFile.SendFileAsync(
                               result.FileName,
                               offset: range.From ?? 0L,
                               count: rangeLength,
                               cancellation: default(CancellationToken)));
                }

                return(sendFile.SendFileAsync(
                           result.FileName,
                           offset: 0,
                           count: null,
                           cancellation: default(CancellationToken)));
            }

            return(WriteFileAsync(context.HttpContext, GetFileStream(result.FileName), range, rangeLength));
        }
コード例 #29
0
        public async Task <PhysicalFileResult> ReadPhysicalFile(string relativeFilePath, string fileType)
        {
            try
            {
                var filePath = $"{_rootUrl}{relativeFilePath}";
                //override path
                filePath = filePath.Replace('\\', Path.DirectorySeparatorChar);

                var result = new PhysicalFileResult(filePath, fileType);
                return(result);
            }
            catch (Exception ex)
            {
                _logger.Log(ex);
            }
            return(null);
        }
コード例 #30
0
ファイル: ExcelManager.cs プロジェクト: onetcore/gentings
        /// <summary>
        /// 导出列表。
        /// </summary>
        /// <param name="models">模型数据表格。</param>
        /// <param name="fileName">文件名称。</param>
        /// <param name="sheetName">工作表名称。</param>
        /// <param name="sheetId">索引Id。</param>
        /// <returns>返回物理路径试图结果。</returns>
        public PhysicalFileResult Export(DataTable models, string fileName, string sheetName = "sheet1", uint sheetId = 1)
        {
            const string extension = ".xlsx";

            if (!fileName.EndsWith(extension, StringComparison.OrdinalIgnoreCase))
            {
                fileName += extension;
            }
            var storageDirectory = _serviceProvider.GetRequiredService <IStorageDirectory>();
            var path             = storageDirectory.GetTempPath(Guid.NewGuid().ToString("N"));

            Save(path, models, sheetName, sheetId);
            var result = new PhysicalFileResult(path, extension.GetContentType());

            result.FileDownloadName = fileName;
            return(result);
        }
コード例 #31
0
        public async Task <PhysicalFileResult> GetAttachmentAsync(VBAttachment attachment, string attachmentsPath)
        {
            string fullPath            = Path.Combine(attachmentsPath, attachment.FilePath);
            var    fileContentProvider = new FileExtensionContentTypeProvider();
            string mimeType;

            if (!fileContentProvider.TryGetContentType(attachment.FileName, out mimeType))
            {
                mimeType = "application/octet-stream";
            }

            var file = new PhysicalFileResult(fullPath, mimeType);

            attachment.DownloadsCount++;
            await db.SaveChangesAsync();

            return(file);
        }
コード例 #32
0
 public Task ExecuteAsync(ActionContext context, PhysicalFileResult result)
 {
     SetHeadersAndLog(context, result);
     return WriteFileAsync(context, result);
 }