Exemplo n.º 1
0
        /// <inheritdoc />
        public override Task ExecuteResultAsync(ActionContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            var loggerFactory = context.HttpContext.RequestServices.GetRequiredService<ILoggerFactory>();
            var logger = loggerFactory.CreateLogger<FileResult>();

            var response = context.HttpContext.Response;
            response.ContentType = ContentType.ToString();

            if (!string.IsNullOrEmpty(FileDownloadName))
            {
                // From RFC 2183, Sec. 2.3:
                // The sender may want to suggest a filename to be used if the entity is
                // detached and stored in a separate file. If the receiving MUA writes
                // the entity to a file, the suggested filename should be used as a
                // basis for the actual filename, where possible.
                var contentDisposition = new ContentDispositionHeaderValue("attachment");
                contentDisposition.SetHttpFileName(FileDownloadName);
                context.HttpContext.Response.Headers[HeaderNames.ContentDisposition] = contentDisposition.ToString();
            }

            logger.FileResultExecuting(FileDownloadName);
            return WriteFileAsync(response);
        }
Exemplo n.º 2
0
        public static void SetFileHeaders(this IHttpResponse response,
                                          string fileName, string contentType, bool?inline)
        {
            if (contentType.HasBlackSpace())
            {
                response.SetContentType(contentType);
            }

            if (inline.HasValue || fileName.HasBlackSpace())
            {
                var dispositionType = GetDispositiontype();
                var dispHeader      = new ContentDispositionHeaderValue(dispositionType)
                {
                    FileName = fileName,
                };
                var dispositionHeaderValue = dispHeader.ToString();
                response.SetHeader("Content-Disposition", dispositionHeaderValue);

                string GetDispositiontype()
                {
                    if (inline.HasValue)
                    {
                        if (!inline.Value)
                        {
                            return("attachment");
                        }
                    }

                    return("inline");
                }
            }
        }
Exemplo n.º 3
0
        /// <inheritdoc />
        public override Task ExecuteResultAsync([NotNull] ActionContext context)
        {
            var response = context.HttpContext.Response;

            if (ContentType != null)
            {
                response.ContentType = ContentType;
            }

            if (!string.IsNullOrEmpty(FileDownloadName))
            {
                // From RFC 2183, Sec. 2.3:
                // The sender may want to suggest a filename to be used if the entity is
                // detached and stored in a separate file. If the receiving MUA writes
                // the entity to a file, the suggested filename should be used as a
                // basis for the actual filename, where possible.
                var cd = new ContentDispositionHeaderValue("attachment");
                cd.SetHttpFileName(FileDownloadName);
                context.HttpContext.Response.Headers.Set(HeaderNames.ContentDisposition, cd.ToString());
            }

            // We aren't flowing the cancellation token appropriately, see
            // https://github.com/aspnet/Mvc/issues/743 for details.
            return WriteFileAsync(response, CancellationToken.None);
        }
Exemplo n.º 4
0
 public ActionResult Get(string filename)
 {
     FileEntity fileEntity = GetFileInfo(filename);
     string fileFullPath = System.IO.Path.Combine(@"C:\", fileEntity.file_path, filename);
     if (fileEntity == null)
         return NotFound();
     FileStream fileStream = System.IO.File.Open(fileFullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
     long startByteIndex = 0;
     long endByteIndex = fileEntity.file_length-1;
     var reqTypedHeader = Request.GetTypedHeaders();
     if (reqTypedHeader.Range!=null && reqTypedHeader.Range.Ranges.Count>0)
     {
         //断点续传处理,多range情景没有处理
         startByteIndex = reqTypedHeader.Range.Ranges.First().From ?? 0;
         endByteIndex = reqTypedHeader.Range.Ranges.First().To ?? fileEntity.file_length - 1;
         Response.StatusCode = StatusCodes.Status206PartialContent;
         var contentRange = new ContentRangeHeaderValue(startByteIndex, endByteIndex);
         Response.Headers[HeaderNames.ContentRange] = contentRange.ToString();
     }
     Response.ContentType = fileEntity.file_mimetype;
     var contentDisposition = new ContentDispositionHeaderValue("attachment");
     contentDisposition.SetHttpFileName(fileEntity.file_name);
     Response.Headers[HeaderNames.ContentDisposition] = contentDisposition.ToString();
     Response.ContentLength = fileStream.Length;
     Response.Headers[HeaderNames.AcceptRanges] = "bytes";
     return new FileStreamResult(fileStream,fileEntity.file_mimetype);
 }
Exemplo n.º 5
0
 private static void SetContentDispositionHeader(HttpContext httpContext, string fileName)
 {
     if (!string.IsNullOrEmpty(fileName))
     {
         var contentDisposition = new Microsoft.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
         contentDisposition.SetHttpFileName(fileName);
         httpContext.Response.Headers[HeaderNames.ContentDisposition] = contentDisposition.ToString();
     }
 }
Exemplo n.º 6
0
        public static void WriteExcelToResponse(this IWorkbook book, HttpContext httpContext, string templateName)
        {
            var response = httpContext.Response;

            response.ContentType = "application/vnd.ms-excel";
            if (!string.IsNullOrEmpty(templateName))
            {
                var contentDisposition = new Microsoft.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
                contentDisposition.SetHttpFileName(templateName);
                response.Headers[HeaderNames.ContentDisposition] = contentDisposition.ToString();
            }
            book.Write(response.Body);
        }
Exemplo n.º 7
0
        public static Task <HttpResponseData> CreateFileContentResponseAsync(this HttpRequestData request, byte[] content, string contentType, string filename)
        {
            var contentDisposition = new Microsoft.Net.Http.Headers.ContentDispositionHeaderValue("attachment");

            contentDisposition.SetHttpFileName(filename);

            var httpResponse = request.CreateResponse(HttpStatusCode.OK);

            httpResponse.Headers.Add("Content-Type", contentType);
            httpResponse.Headers.Add("Content-Length", content.Length.ToString());
            httpResponse.Headers.Add(HeaderNames.ContentDisposition, contentDisposition.ToString());
            httpResponse.WriteBytes(content);

            return(Task.FromResult(httpResponse));
        }
Exemplo n.º 8
0
 /// <summary>
 /// Makes the zip of the app to download
 /// </summary>
 /// <param name="endpoints">The endpoints.</param>
 /// <param name="app">App builder.</param>
 public static void MapZip(this IEndpointRouteBuilder endpoints, IApplicationBuilder app)
 {
     //see more at
     //https://andrewlock.net/converting-a-terminal-middleware-to-endpoint-routing-in-aspnetcore-3/
     endpoints.Map("/zip", async context =>
     {
         var response         = context.Response;
         var name             = Assembly.GetEntryAssembly().GetName().Name + ".zip";
         response.ContentType = "application/octet-stream";
         var b = GetZip(app.ApplicationServices.GetService <IWebHostEnvironment>());
         //https://github.com/dotnet/aspnetcore/blob/master/src/Mvc/Mvc.Core/src/Infrastructure/FileResultExecutorBase.cs
         var contentDisposition = new Microsoft.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
         contentDisposition.SetHttpFileName(name);
         response.Headers[HeaderNames.ContentDisposition] = contentDisposition.ToString();
         await response.Body.WriteAsync(b);
     });
 }
Exemplo n.º 9
0
        public async Task <IActionResult> DownloadAttachment(string id)
        {
            var docField = await _queryService.GetDocumentFieldById(id);

            if (!String.IsNullOrEmpty(docField.FilePath))
            {
                var path = docField.FilePath;

                var contentDisposition = new Microsoft.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
                {
                    FileName = docField.Value
                };
                Response.Headers[HeaderNames.ContentDisposition] = contentDisposition.ToString();

                var response = new FileStreamResult(new FileStream(path, FileMode.Open), "application/octet-stream");
                return(response);
            }
            return(Json("File not found"));
        }
Exemplo n.º 10
0
        public void ToString_UseDifferentContentDispositions_AllSerializedCorrectly()
        {
            var contentDisposition = new ContentDispositionHeaderValue("inline");

            Assert.Equal("inline", contentDisposition.ToString());

            contentDisposition.Name = "myname";
            Assert.Equal("inline; name=myname", contentDisposition.ToString());

            contentDisposition.FileName = "my File Name";
            Assert.Equal("inline; name=myname; filename=\"my File Name\"", contentDisposition.ToString());

            contentDisposition.CreationDate = new DateTimeOffset(new DateTime(2011, 2, 15), new TimeSpan(-8, 0, 0));
            Assert.Equal("inline; name=myname; filename=\"my File Name\"; creation-date="
                         + "\"Tue, 15 Feb 2011 08:00:00 GMT\"", contentDisposition.ToString());

            contentDisposition.Parameters.Add(new NameValueHeaderValue("custom", "\"custom value\""));
            Assert.Equal("inline; name=myname; filename=\"my File Name\"; creation-date="
                         + "\"Tue, 15 Feb 2011 08:00:00 GMT\"; custom=\"custom value\"", contentDisposition.ToString());

            contentDisposition.Name = null;
            Assert.Equal("inline; filename=\"my File Name\"; creation-date="
                         + "\"Tue, 15 Feb 2011 08:00:00 GMT\"; custom=\"custom value\"", contentDisposition.ToString());

            contentDisposition.FileNameStar = "File%Name";
            Assert.Equal("inline; filename=\"my File Name\"; creation-date="
                         + "\"Tue, 15 Feb 2011 08:00:00 GMT\"; custom=\"custom value\"; filename*=UTF-8\'\'File%25Name",
                         contentDisposition.ToString());

            contentDisposition.FileName = null;
            Assert.Equal("inline; creation-date=\"Tue, 15 Feb 2011 08:00:00 GMT\"; custom=\"custom value\";"
                         + " filename*=UTF-8\'\'File%25Name", contentDisposition.ToString());

            contentDisposition.CreationDate = null;
            Assert.Equal("inline; custom=\"custom value\"; filename*=UTF-8\'\'File%25Name",
                         contentDisposition.ToString());
        }
Exemplo n.º 11
0
 private void SetContentDispositionHeader(ActionContext context, FileResult result)
 {
     if (!string.IsNullOrEmpty(result.FileDownloadName))
     {
         var contentDisposition = new Microsoft.Net.Http.Headers.ContentDispositionHeaderValue(ContentDispositionHeader.ToString());
         contentDisposition.SetHttpFileName(result.FileDownloadName);
         context.HttpContext.Response.Headers[HeaderNames.ContentDisposition] = contentDisposition.ToString();
     }
 }
Exemplo n.º 12
0
        public void GetHeaderValue_Produces_Correct_ContentDisposition(string input, string expectedOutput)
        {
            // Arrange & Act
            var cd = new ContentDispositionHeaderValue("attachment");
            cd.SetHttpFileName(input);
            var actual = cd.ToString();

            // Assert
            Assert.Equal(expectedOutput, actual);
        }
        public void ToString_UseDifferentContentDispositions_AllSerializedCorrectly()
        {
            var contentDisposition = new ContentDispositionHeaderValue("inline");
            Assert.Equal("inline", contentDisposition.ToString());

            contentDisposition.Name = "myname";
            Assert.Equal("inline; name=myname", contentDisposition.ToString());

            contentDisposition.FileName = "my File Name";
            Assert.Equal("inline; name=myname; filename=\"my File Name\"", contentDisposition.ToString());

            contentDisposition.CreationDate = new DateTimeOffset(new DateTime(2011, 2, 15));
            Assert.Equal("inline; name=myname; filename=\"my File Name\"; creation-date="
                + "\"Tue, 15 Feb 2011 08:00:00 GMT\"", contentDisposition.ToString());

            contentDisposition.Parameters.Add(new NameValueHeaderValue("custom", "\"custom value\""));
            Assert.Equal("inline; name=myname; filename=\"my File Name\"; creation-date="
                + "\"Tue, 15 Feb 2011 08:00:00 GMT\"; custom=\"custom value\"",  contentDisposition.ToString());

            contentDisposition.Name = null;
            Assert.Equal("inline; filename=\"my File Name\"; creation-date="
                + "\"Tue, 15 Feb 2011 08:00:00 GMT\"; custom=\"custom value\"", contentDisposition.ToString());

            contentDisposition.FileNameStar = "File%Name";
            Assert.Equal("inline; filename=\"my File Name\"; creation-date="
                + "\"Tue, 15 Feb 2011 08:00:00 GMT\"; custom=\"custom value\"; filename*=UTF-8\'\'File%25Name",
                contentDisposition.ToString());

            contentDisposition.FileName = null;
            Assert.Equal("inline; creation-date=\"Tue, 15 Feb 2011 08:00:00 GMT\"; custom=\"custom value\";"
                + " filename*=UTF-8\'\'File%25Name", contentDisposition.ToString());

            contentDisposition.CreationDate = null;
            Assert.Equal("inline; custom=\"custom value\"; filename*=UTF-8\'\'File%25Name",
                contentDisposition.ToString());
        }