public FileResult GetSkuAverageDailySalesBySkuReportFile(string id) { var result = _cache.GetItem <byte[]>(String.Format(CacheKeys.ReportFormat, id)); if (result == null) { throw new AppValidationException("Please reload a file."); } var contentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = String.Format(FileConstants.AVERAGE_DAILY_SALES_BY_SKU, DateTime.Now) }; Response.Headers.Add("Content-Disposition", contentDisposition.ToString()); return(File(result, "text/csv")); }
/// <summary> /// 设置响应头信息 /// </summary> /// <param name="response"></param> /// <param name="partialFileInfo"></param> /// <param name="fileLength"></param> /// <param name="fileName"></param> private void SetResponseHeaders(HttpResponse response, PartialFileInfo partialFileInfo) { response.Headers[HeaderNames.AcceptRanges] = "bytes"; response.StatusCode = partialFileInfo.IsPartial ? StatusCodes.Status206PartialContent : StatusCodes.Status200OK; var contentDisposition = new ContentDispositionHeaderValue("attachment"); contentDisposition.SetHttpFileName(partialFileInfo.Name); response.Headers[HeaderNames.ContentDisposition] = contentDisposition.ToString(); response.Headers[HeaderNames.ContentType] = "application/octet-stream"; //response.Headers[HeaderNames.ContentMD5] = partialFileInfo.MD5; response.Headers[HeaderNames.ContentLength] = partialFileInfo.Length.ToString(); if (partialFileInfo.IsPartial) { response.Headers[HeaderNames.ContentRange] = new ContentRangeHeaderValue(partialFileInfo.From, partialFileInfo.To, partialFileInfo.FileLength).ToString(); } }
public FileResult GetGiftCertificatesReportFile(string id) { var result = _cache.GetItem <byte[]>(String.Format(CacheKeys.ReportFormat, id)); if (result == null) { throw new AppValidationException("Please reload a file."); } var contentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = String.Format(FileConstants.GCS_REPORT, DateTime.Now) }; Response.Headers.Add("Content-Disposition", contentDisposition.ToString()); return(File(result, "text/csv")); }
public async Task <ActionResult> DownloadByBuild(string buildConfig, string?typeFilter = null) { Logger.WriteLine("Serving listfile for build " + buildConfig); var filesPerBuild = await Database.GetFilesByBuild(buildConfig, typeFilter); var dataResponse = Encoding.ASCII.GetBytes(string.Join('\n', filesPerBuild.Values)); var contentDispositionHeader = new ContentDispositionHeaderValue(DispositionTypeNames.Attachment) { FileNameStar = "listfile.txt", FileName = "listfile.txt", Size = dataResponse.Length }; Response.Headers[HeaderNames.ContentDisposition] = contentDispositionHeader.ToString(); return(new FileContentResult(dataResponse, "text/plain")); }
public async Task <FileResult> GetGiftCertificatesWithOrderInfoReportFile([FromQuery] string from, [FromQuery] string to, [FromQuery] int?type = null, [FromQuery] int?status = null, [FromQuery] string billinglastname = null, [FromQuery] string shippinglastname = null, [FromQuery] bool notzerobalance = false) { DateTime?dFrom = !string.IsNullOrEmpty(from) ? from.GetDateFromQueryStringInPst(TimeZoneHelper.PstTimeZoneInfo) : null; DateTime?dTo = !string.IsNullOrEmpty(to) ? to.GetDateFromQueryStringInPst(TimeZoneHelper.PstTimeZoneInfo) : null; GCFilter filter = new GCFilter() { From = dFrom, To = dTo?.AddDays(1) ?? dTo, Type = type.HasValue ? (GCType?)type.Value : null, StatusCode = status.HasValue ? (RecordStatusCode?)status.Value : null, BillingAddress = !String.IsNullOrEmpty(billinglastname) ? new CustomerAddressFilter() { LastName = billinglastname }: null, ShippingAddress = !String.IsNullOrEmpty(shippinglastname) ? new CustomerAddressFilter() { LastName = shippinglastname } : null, NotZeroBalance = notzerobalance, }; filter.Paging = null; var data = await GCService.GetGiftCertificatesWithOrderInfoAsync(filter); foreach (var item in data.Items) { item.Created = TimeZoneInfo.ConvertTime(item.Created, TimeZoneInfo.Local, TimeZoneHelper.PstTimeZoneInfo); } var result = _gCWithOrderListItemModelCsvMapCSVExportService.ExportToCsv(data.Items); var contentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = String.Format(FileConstants.GIFT_CERTIFICATES_REPORT_STATISTIC, DateTime.Now) }; Response.Headers.Add("Content-Disposition", contentDisposition.ToString()); return(File(result, "text/csv")); }
public IActionResult DownloadZipFile(string sessionID, string path) { string tempLocation = Directory.GetCurrentDirectory() + @"\uploads\Zips\" + sessionID + @"\"; if (Directory.Exists(tempLocation)) { Directory.Delete(tempLocation, true); } var tempFolder = Directory.CreateDirectory(tempLocation); foreach (var file in Directory.GetFiles(path).Where(file => file.Split(@"\").Last().StartsWith(sessionID)).ToList()) { System.IO.File.Copy(file, tempFolder.FullName + file.Split(@"\").Last()); } //Create the zip folder string zipPath = Directory.GetCurrentDirectory() + @"\uploads\Zips\" + sessionID + ".zip"; if (System.IO.File.Exists(zipPath)) { System.IO.File.Delete(zipPath); } ZipFile.CreateFromDirectory(tempFolder.FullName, zipPath); //THe part below will package up a file to be sent through a byte stream var cd = new ContentDispositionHeaderValue("attachment") { FileNameStar = zipPath.Split(@"\").Last() }; Response.Headers.Add(HeaderNames.ContentDisposition, cd.ToString()); byte[] bytes = System.IO.File.ReadAllBytes(zipPath); using (FileStream fs = new FileStream(zipPath, FileMode.Open, FileAccess.Read)) { fs.Read(bytes, 0, System.Convert.ToInt32(fs.Length)); fs.Close(); } return(File(bytes, "application/zip")); }
public override async Task ExecuteResultAsync(ActionContext context) { if (_fileDownloadName != null) { ContentDispositionHeaderValue contentDispositionHeaderValue = new ContentDispositionHeaderValue("attachment"); contentDispositionHeaderValue.FileName = _fileDownloadName; context.HttpContext.Response.Headers["Content-Disposition"] = contentDispositionHeaderValue.ToString(); } context.HttpContext.Response.Headers["Content-Type"] = _contentType; #if !NETSTANDARD2_0 context.HttpContext.Features.Get <AspNetCore.Http.Features.IHttpResponseBodyFeature>()?.DisableBuffering(); #else context.HttpContext.Features.Get <AspNetCore.Http.Features.IHttpBufferingFeature>()?.DisableResponseBuffering(); #endif await _action(context.HttpContext.Response.Body, context.HttpContext.RequestAborted); }
/// <summary> /// 设置响应头信息 /// </summary> /// <param name="response"></param> /// <param name="fileInfo"></param> /// <param name="fileLength"></param> /// <param name="fileName"></param> private void SetResponseHeaders(HttpResponse response, FileInfo fileInfo, long fileLength, string fileName) { response.Headers[HeaderNames.AcceptRanges] = "bytes"; response.StatusCode = fileInfo.IsPartial ? StatusCodes.Status206PartialContent : StatusCodes.Status200OK; var contentDisposition = new ContentDispositionHeaderValue("attachment"); contentDisposition.SetHttpFileName(fileName); response.Headers[HeaderNames.ContentDisposition] = contentDisposition.ToString(); response.Headers[HeaderNames.ContentType] = MimeType; response.Headers[HeaderNames.ContentLength] = fileInfo.Length.ToString(); if (fileInfo.IsPartial) { response.Headers[HeaderNames.ContentRange] = new ContentRangeHeaderValue(fileInfo.From, fileInfo.To, fileLength).ToString(); } }
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()); }
public async Task <ActionResult> DownloadUnknownLookupCSV() { Logger.WriteLine("Serving unknown lookup listfile"); var unkFiles = await Database.GetUnknownLookups(); var dataResponse = Encoding.ASCII.GetBytes(string.Join('\n', unkFiles)); var contentDispositionHeader = new ContentDispositionHeaderValue(DispositionTypeNames.Attachment) { FileNameStar = "unknownlookups.csv", FileName = "unknownlookups.csv", Size = dataResponse.Length }; Response.Headers[HeaderNames.ContentDisposition] = contentDispositionHeader.ToString(); return(new FileContentResult(dataResponse, "text/csv")); }
public async Task <ActionResult> File(int assetId, string fileName, string extension) { var file = await GetFile(assetId); if (file == null) { return(FileAssetNotFound("File not found")); } // Set the filename header separately to force "inline" content // disposition even though a filename is specified. var contentDisposition = new ContentDispositionHeaderValue("inline"); contentDisposition.SetHttpFileName(file.FileName); Response.Headers[HeaderNames.ContentDisposition] = contentDisposition.ToString(); return(File(file.ContentStream, file.ContentType)); }
public async Task <IActionResult> getReport([FromHeader] Guid AccountId, [FromQuery] DateTime from, [FromQuery] DateTime to) { try { var response = await _mediator.Send(new GetMoneyTransferReportQuery(AccountId, from, to)); var file = ((GetAccountBalanceResponseData)response.Data).File; var cd = new ContentDispositionHeaderValue("attachment") { FileNameStar = "report.xlsx" }; Response.Headers.Add(HeaderNames.ContentDisposition, cd.ToString()); return(File(file, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")); } catch (BankAccountNotFoundException e) { return(BadRequest(e.Message)); } }
public async Task <FileResult> GetInventoriesSummaryUsageReportFile([FromQuery] string from, [FromQuery] string to, [FromQuery] string sku, [FromQuery] string invsku, [FromQuery] bool?assemble, [FromQuery] string idsinvcat, [FromQuery] int infotype, [FromQuery] int frequency) { var dFrom = from.GetDateFromQueryStringInPst(TimeZoneHelper.PstTimeZoneInfo); var dTo = to.GetDateFromQueryStringInPst(TimeZoneHelper.PstTimeZoneInfo); if (!dFrom.HasValue || !dTo.HasValue) { return(null); } InventoriesSummaryUsageReportFilter filter = new InventoriesSummaryUsageReportFilter() { From = dFrom.Value, To = dTo.Value, Sku = sku, InvSku = invsku, Assemble = assemble, IdsInvCat = !string.IsNullOrEmpty(idsinvcat) ? idsinvcat.Split(',').Select(Int32.Parse).ToList() : null, InfoType = infotype, FrequencyType = (FrequencyType)frequency }; filter.To = filter.To.AddDays(1); var result = await _inventorySkuService.GetInventoriesSummaryUsageReportAsync(filter); IList <DynamicExportColumn> columns = null; IList <ExpandoObject> items = null; _inventorySkuService.ConvertInventoriesSummaryUsageReportForExport(result, infotype, out columns, out items); var data = CsvExportService.ExportToCsv(columns, items); var contentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = String.Format(FileConstants.INVENTORY_SUMMARY_REPORT, DateTime.Now) }; Response.Headers.Add("Content-Disposition", contentDisposition.ToString()); return(File(data, "text/csv")); }
public virtual IActionResult GetFile(Guid id) { IFile file = this.fileService.GetFile(id); if (file == null) { return(NotFound()); } var contentDisposition = new ContentDispositionHeaderValue("attachment"); contentDisposition.SetHttpFileName(file.FileName); //Fix for Swagger UI contentDisposition.FileName = contentDisposition.FileName.Replace('?', '_').Replace(' ', '_').Replace("\"", ""); Response.Headers[HeaderNames.ContentDisposition] = contentDisposition.ToString(); //Response.Headers.Add("Access-Control-Expose-Headers", "Content-Disposition, Transfer-Encoding"); return(File(file.Bytes, "application/octet-stream")); }
public async Task <PhysicalFileResult> Get(int id) { using (SAEONLogs.MethodCall(GetType(), new MethodCallParameters { { nameof(id), id } })) { try { var literature = await dbContext.Literatures.FirstOrDefaultAsync(i => i.Id == id); //Guard.IsNotNull(image, nameof(image)); if (literature == null) { throw new ArgumentOutOfRangeException(nameof(id)); } var fileName = Path.Combine(environment.ContentRootPath, literature.Link.RemoveStartingBackSlash().RemoveStartingForwardSlash()); string contentType = MediaTypeNames.Application.Octet; if (Path.GetExtension(fileName) == ".pdf") { contentType = MediaTypeNames.Application.Pdf; } else if (Path.GetExtension(fileName) == ".doc") { contentType = "application/msword"; } var result = new PhysicalFileResult(fileName, contentType); var contentDisposition = new ContentDispositionHeaderValue("inline") { FileName = Path.GetFileName(fileName) }; Response.Headers[HeaderNames.ContentDisposition] = contentDisposition.ToString(); await RequestLogger.LogAsync(dbContext, Request, $"{literature.Title}|{literature.Link}"); return(result); } catch (Exception ex) { SAEONLogs.Exception(ex); throw; } } }
public ActionResult ExportXlsx() { var dt = OfficeHelper.ToDatatable(CreateTestData1List(), new Dictionary <string, Expression <Func <TestData1, object> > > { { "Id", it => it.Id }, { "Name", it => it.Name }, { "Time", it => it.Time } }); var ds = new DataSet(); ds.Tables.Add(dt); //直接输出到响应流以减少存取文件或MemoryStream的使用开销 Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; ContentDispositionHeaderValue contentDisposition = new ContentDispositionHeaderValue("attachment"); contentDisposition.FileName = "导出的Excel.xlsx"; Response.Headers["Content-Disposition"] = contentDisposition.ToString(); NPOIHelper.DatasetToExcel(ds, Response.OutputStream, ExcelFormat.Xlsx); return(new EmptyResult()); }
public async Task <IActionResult> Get(Guid fileGuid) { var file = await _dbContext.Files.FindAsync(fileGuid); if (file == null) { return(NotFound()); } // Set up the content-disposition header with proper encoding of the filename var contentDisposition = new ContentDispositionHeaderValue("inline"); contentDisposition.SetHttpFileName(MakeFileName(file.DisplayName, file.MimeType)); Response.Headers[HeaderNames.ContentDisposition] = contentDisposition.ToString(); // Return the actual filestream MemoryStream ms = new MemoryStream(file.Content, false); return(new FileStreamResult(ms, file.MimeType)); }
public void DownloadTemplate() { string filePath = Path.Combine(hostingEnvironment.WebRootPath, "Templates/BulkJobSeekerTemplates/BulkJobSeekers.xlsx"); using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read)) { HttpContext.Response.ContentType = "application/vnd.ms-excel"; ContentDispositionHeaderValue contentDisposition = new ContentDispositionHeaderValue("attachment"); contentDisposition.SetHttpFileName( string.Format("{0}.xlsx", DateTime.Now.Ticks)); HttpContext.Response.Headers[HeaderNames.ContentDisposition] = contentDisposition.ToString(); stream.CopyTo(HttpContext.Response.Body); } }
public async Task <FileResult> GetDiscountsReportFile([FromQuery] string validfrom, [FromQuery] string validto, [FromQuery] int?status = null, [FromQuery] string searchtext = null, [FromQuery] int?datestatus = null, [FromQuery] bool searchbyassigned = false, [FromQuery] int?assigned = null, [FromQuery] string path = null, [FromQuery] string sortorder = null) { DateTime?dValidFrom = !string.IsNullOrEmpty(validfrom) ? validfrom.GetDateFromQueryStringInPst(TimeZoneHelper.PstTimeZoneInfo) : null; DateTime?dValidTo = !string.IsNullOrEmpty(validto) ? validto.GetDateFromQueryStringInPst(TimeZoneHelper.PstTimeZoneInfo) : null; DiscountFilter filter = new DiscountFilter() { ValidFrom = dValidFrom, ValidTo = dValidTo, Status = (RecordStatusCode?)status, SearchText = searchtext, DateStatus = (DateStatus?)datestatus, SearchByAssigned = searchbyassigned, Assigned = (CustomerType?)assigned, }; filter.Paging = null; if (!string.IsNullOrEmpty(path) && !string.IsNullOrEmpty(sortorder)) { filter.Sorting = new SortFilter() { Path = path, SortOrder = sortorder == Enum.GetName(typeof(FilterSortOrder), FilterSortOrder.Asc) ? FilterSortOrder.Asc : FilterSortOrder.Desc, }; } var data = await _discountService.GetDiscountsAsync(filter); var result = _discountListItemExportCsvMapСSVExportService.ExportToCsv(data.Items.Select(p => new DiscountListItemModel(p)).ToList()); var contentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = String.Format(FileConstants.DISCOUNTS_REPORT, DateTime.Now) }; Response.Headers.Add("Content-Disposition", contentDisposition.ToString()); return(File(result, "text/csv")); }
public async Task<FileResult> GetWholesalesReportFile([FromQuery]int? idtradeclass = null, [FromQuery]int? idtier = null, [FromQuery]bool? onlyactive = true) { WholesaleFilter filter = new WholesaleFilter() { IdTradeClass = idtradeclass, IdTier = idtier, OnlyActive = onlyactive ?? true }; filter.Paging = null; var data = await _customerService.GetWholesalesAsync(filter); var result = _csvExportWholesaleListitemService.ExportToCsv(data.Items); var contentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = String.Format(FileConstants.WHOLESALE_LIST_REPORT, DateTime.Now) }; Response.Headers.Add("Content-Disposition", contentDisposition.ToString()); return File(result, "text/csv"); }
/// <inheritdoc /> public Func <CancellationToken, Task <IActionResult> > OnFetch(StorageOnFetchOptions options) { return(cancellationToken => { var readStream = File.OpenRead(GetFileLocation(options.File.Container, options.File.FileId)); var cd = new ContentDispositionHeaderValue(options.Download ? "attachment" : "inline") { Name = options.File.FileName, FileNameStar = options.File.FileName, Size = readStream.Length, FileName = options.File.FileName, }; options.HttpContext.Response.Headers["Content-Disposition"] = cd.ToString(); return Task.FromResult(new FileStreamResult(readStream, options.File.ContentType) { LastModified = options.File.Modified, } as IActionResult); }); }
public async Task <ActionResult> Document(int documentAssetId, long fileStamp, string verificationToken, string fileName, string extension) { var file = await GetDocumentAssetFile(documentAssetId); var validationAction = ValidateDocumentFileRequest(fileStamp, verificationToken, fileName, file, false); if (validationAction != null) { return(validationAction); } // Set the filename header separately to force "inline" content // disposition even though a filename is specified. var contentDisposition = new ContentDispositionHeaderValue("inline"); contentDisposition.SetHttpFileName(file.GetFileNameWithExtension()); Response.Headers[HeaderNames.ContentDisposition] = contentDisposition.ToString(); SetCacheHeader(_documentAssetsSettings.CacheMaxAge); return(File(file.ContentStream, file.ContentType)); }
public async Task <IActionResult> GetByUrl(int year, int month, int day, string filename, [FromQuery] string token, [FromQuery] bool?isInline = null) { if (token.IsBase64String() == false) { return(BadRequest(string.Format(ApiReturnMessages.TokenIsNotSpecified))); } var tokenWithFileId = token.Base64Decode().Split(":"); var isValidToken = await _tokenService.ValidateToken(tokenWithFileId[0]); if (isValidToken == false) { return(Unauthorized()); } var file = await _fileService.GetAsync(year, month, day, filename); if (file != null) { if (file.FileId.ToString() != tokenWithFileId[1]) { return(Unauthorized()); } var absoluteFilePath = _fileService.GetFilePath(file.FilePath); ////var contentDispositionType = isInline != null && (bool)isInline ? "inline" : "attachment"; var contentDispositionType = isInline ?? false ? "inline" : "attachment"; // Set up the content-disposition header with proper encoding of the filename var contentDisposition = new ContentDispositionHeaderValue(contentDispositionType); Response.Headers[HeaderNames.ContentDisposition] = contentDisposition.ToString(); return(await FileStreamingHelper.GetFile(absoluteFilePath, file.FileMimeType)); } return(NotFound()); }
public async Task <IActionResult> FileResultAsync(string filepath, string contentDispositionHeaderValue = "attachment") { var memory = new MemoryStream(); using (var stream = new FileStream(filepath, FileMode.Open)) { await stream.CopyToAsync(memory); } memory.Position = 0; var provider = new FileExtensionContentTypeProvider(); if (!provider.TryGetContentType(filepath, out string contentType)) { contentType = "application/octet-stream"; } var filename = Path.GetFileName(filepath); var contentDisposition = new ContentDispositionHeaderValue(contentDispositionHeaderValue); contentDisposition.SetHttpFileName(filename); Response.Headers[HeaderNames.ContentDisposition] = contentDisposition.ToString(); return(File(memory, contentType, filename)); }
public async Task <IActionResult> DownloadFile(string fileName) { try { if (!Directory.Exists(_uploadsPath)) { return(NoContent()); } var fullPath = Path.Combine(_uploadsPath, fileName); var cd = new ContentDispositionHeaderValue("attachment") { FileName = fileName }; Response.Headers.Add(HeaderNames.ContentDisposition, cd.ToString()); byte[] fileBytes = System.IO.File.ReadAllBytes(fullPath); return(Ok("data:image/png;base64," + Convert.ToBase64String(fileBytes))); } catch { return(NotFound(fileName)); } }
public async Task<FileContentResult> GetHiRes(int id) { using (SAEONLogs.MethodCall(GetType(), new MethodCallParameters { { nameof(id), id } })) { try { var image = await dbContext.Images.FirstOrDefaultAsync(i => i.Id == id); //Guard.IsNotNull(image, nameof(image)); if (image == null) { throw new ArgumentOutOfRangeException(nameof(id)); } if (string.IsNullOrWhiteSpace(image.LinkHiRes)) { throw new ArgumentOutOfRangeException(nameof(image.LinkHiRes)); } var fileName = Path.Combine(environment.ContentRootPath, image.LinkHiRes.RemoveStartingBackSlash().RemoveStartingForwardSlash()); using (MemoryStream outStream = new MemoryStream()) using (var jpgImage = await SixLabors.ImageSharp.Image.LoadAsync(fileName)) { await jpgImage.SaveAsJpegAsync(outStream); var imageBytes = outStream.ToArray(); var result = new FileContentResult(imageBytes, MediaTypeNames.Image.Jpeg); var contentDisposition = new ContentDispositionHeaderValue("inline"); contentDisposition.FileName = Path.GetFileName(fileName); Response.Headers[HeaderNames.ContentDisposition] = contentDisposition.ToString(); await RequestLogger.LogAsync(dbContext, Request, $"{image.Name}|{image.Link}"); return result; } } catch (Exception ex) { SAEONLogs.Exception(ex); throw; } } }
public async Task <FileResult> GetVitalGreenReportFile([FromQuery] string year, [FromQuery] string month) { DateTime utcDate = new DateTime(Int32.Parse(year), Int32.Parse(month), 1); utcDate = TimeZoneInfo.ConvertTime(utcDate, TimeZoneHelper.PstTimeZoneInfo, TimeZoneInfo.Local); var toReturn = await _vitalGreenService.GetVitalGreenReport(utcDate); var requests = new List <VitalGreenRequest>(); foreach (var date in toReturn.Dates) { requests.AddRange(date.Requests); } var data = _csvExportVitalGreenRequestService.ExportToCsv(requests); var contentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = String.Format(FileConstants.VITAL_GREEN_REPORT_FILE_NAME_FORMAT, month, year), }; Response.Headers.Add("Content-Disposition", contentDisposition.ToString()); return(File(data, "text/csv")); }
// TODO: override the ExecuteResult async method to allow async execution as well ? public override void ExecuteResult(ActionContext context) { ContentDispositionHeaderValue contentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = _downloadFilename }; context.HttpContext.Response.Headers.Add("Content-Length", _stream.Length.ToString()); context.HttpContext.Response.Headers.Add("Content-Disposition", contentDisposition.ToString()); // get chunks of data and write to the output stream Stream outputStream = context.HttpContext.Response.Body; byte[] buffer = new byte[BufferSize]; try { while (true) { int bytesRead = _stream.Read(buffer, 0, BufferSize); if (bytesRead == 0) { // no more data that must be transmitted so stop here. break; } outputStream.Write(buffer, 0, bytesRead); outputStream.Flush(); } } finally { _stream.Dispose(); } }
public async Task <ActionResult> DownloadCSVUnverified(string?typeFilter = null) { Logger.WriteLine("Serving unverified CSV listfile"); var knownFiles = await Database.GetKnownFiles(true, typeFilter); var nameList = new List <string>(); foreach (var entry in knownFiles) { nameList.Add(entry.Key + ";" + entry.Value.filename); } var dataResponse = Encoding.ASCII.GetBytes(string.Join('\n', nameList.ToArray())); var contentDispositionHeader = new ContentDispositionHeaderValue(DispositionTypeNames.Attachment) { FileNameStar = "listfile.csv", FileName = "listfile.csv", Size = dataResponse.Length }; Response.Headers[HeaderNames.ContentDisposition] = contentDispositionHeader.ToString(); return(new FileContentResult(dataResponse, "text/csv")); }
public async Task <FileResult> GetProductCategoriesStatisticReportFile([FromQuery] DateTime from, [FromQuery] DateTime to) { var rootItem = await productCategoryService.GetProductCategoriesStatisticAsync( new ProductCategoryStatisticFilter() { From = from, To = to }); List <ProductCategoryStatisticTreeItemModel> items = new List <ProductCategoryStatisticTreeItemModel>(); TransformProductCategoryTreeToList(rootItem, items, 1); items.Remove(rootItem); var data = productCategoryStatisticTreeItemCSVExportService.ExportToCsv(items); var contentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = String.Format(FileConstants.PRODUCT_CATEGORY_STATISTIC, DateTime.Now) }; Response.Headers.Add("Content-Disposition", contentDisposition.ToString()); return(File(data, "text/csv")); }