public ActionResult DownloadFile(int Id) { MembershipHelp mHelp = new MembershipHelp(); var role = mHelp.logingUserRole(User.Identity.Name); var roleId = db.RoleMasters.Where(w => w.Name == role).Select(s => s.Id).FirstOrDefault(); var canDelete = (from m in db.MenuInfoes join rm in db.RoleMenuMappings on m.Id equals rm.MenuInfoId where m.MenuURL.Contains("ArtWorks") && rm.RoleId == roleId select rm.CanDelete).FirstOrDefault(); if (!canDelete) { return(RedirectToAction("Index")); } string filename = db.ArtWorks.Where(w => w.Id == Id).Select(s => s.FileAddressInfo).FirstOrDefault(); string filepath = AppDomain.CurrentDomain.BaseDirectory + "/Content/Uploads/Originals/" + filename; byte[] filedata = System.IO.File.ReadAllBytes(filepath); string contentType = MimeMapping.GetMimeMapping(filepath); var cd = new System.Net.Mime.ContentDisposition { FileName = filename, Inline = true, }; Response.AppendHeader("Content-Disposition", cd.ToString()); return(File(filedata, contentType)); }
public static string GetHeaderValue(string fileName, bool inline = false, bool withoutBase = false) { // If fileName contains any Unicode characters, encode according // to RFC 2231 (with clarifications from RFC 5987) if (fileName.Any(c => (int)c > 127)) { var str = withoutBase ? "{0}; filename*=UTF-8''{2}" : "{0}; filename=\"{1}\"; filename*=UTF-8''{2}"; return string.Format(str, inline ? "inline" : "attachment", fileName, CreateRfc2231HeaderValue(fileName)); } // Knowing there are no Unicode characters in this fileName, rely on // ContentDisposition.ToString() to encode properly. // In .Net 4.0, ContentDisposition.ToString() throws FormatException if // the file name contains Unicode characters. // In .Net 4.5, ContentDisposition.ToString() no longer throws FormatException // if it contains Unicode, and it will not encode Unicode as we require here. // The Unicode test above is identical to the 4.0 FormatException test, // allowing this helper to give the same results in 4.0 and 4.5. var disposition = new ContentDisposition { FileName = fileName, Inline = inline }; return disposition.ToString(); }
public ActionResult Index() { var path = HttpContext.Server.MapPath("~\\App_Data\\Kentor.AuthServices.StubIdp.cer"); var disposition = new ContentDisposition { Inline = false, FileName = Path.GetFileName(path) }; Response.AppendHeader("Content-Disposition", disposition.ToString()); return File(path, MediaTypeNames.Text.Plain); }
public ActionResult ShowPdfFile(long? d) { Documentm doc=null; long DocNum=0; if(d!=null) { DocNum=(long)d; } Patientm patm; if(Session["Patient"]==null) { return RedirectToAction("Login"); } else { patm=(Patientm)Session["Patient"]; } if(DocNum!=0) { doc=Documentms.GetOne(patm.CustomerNum,DocNum); } if(doc==null || patm.PatNum!=doc.PatNum) {//make sure that the patient does not pass the another DocNum of another patient. return new EmptyResult(); //return a blank page todo: return page with proper message. } ContentDisposition cd = new ContentDisposition(); cd.Inline=true;//the browser will try and show the pdf inline i.e inside the browser window. If set to false it will force a download. Response.AppendHeader("Content-Disposition",cd.ToString()); return File(Convert.FromBase64String(doc.RawBase64),"application/pdf","Statement.pdf"); }
public ActionResult DownloadFile(string filename) { try { byte[] filedata = _filesHelper.DownloadFile(filename); var dir = WebConfigurationManager.AppSettings["DirForFeedback"]; string filepath = dir + filename; //byte[] filedata = System.IO.File.ReadAllBytes(filepath); string contentType = MimeMapping.GetMimeMapping(filepath); var cd = new System.Net.Mime.ContentDisposition { FileName = filename, Inline = true, }; Response.Headers.Add("Content-Disposition", cd.ToString()); //View file //Download file //Öppnar excel return(File(filedata, contentType)); } catch (Exception e) { Console.WriteLine(e); ErrorManager.WriteToErrorLog("FileUploadController", "DownloadFile", e.ToString(), e.HResult, User.Identity.Name); var errorModel = new CustomErrorPageModel { Information = "Ett fel inträffade vid öppningen av återkopplingsfilen", ContactEmail = ConfigurationManager.AppSettings["ContactEmail"], }; return(View("CustomError", errorModel)); } }
public ActionResult Export(string FileContent, string FileName) { var cd = new ContentDisposition { FileName = FileName + ".csv", Inline = false }; Response.AddHeader("Content-Disposition", cd.ToString()); return Content(FileContent, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); }
public ActionResult GeneratePDF() { var url = "http://www.google.com"; byte[] pdfBuf = PDFHelper.ConvertToPdf(PDFHelper.DataType.URL, url, "DocumentTitle"); var cd = new ContentDisposition { FileName = "DocName.pdf", Inline = false // always prompt the user for downloading, set to true if you want the browser to try to show the file inline }; Response.AppendHeader("Content-Disposition", cd.ToString()); return File(pdfBuf, "application/pdf"); }
public ActionResult DownloadExtension() { string path = AppDomain.CurrentDomain.BaseDirectory + "/vss-extension.json"; byte[] data = System.IO.File.ReadAllBytes(path); var header = new ContentDisposition { FileName = "vss-extension.json", Inline = false }; Response.AppendHeader("Content-Disposition", header.ToString()); return File(data, "application/force-download"); }
public static string GetHeaderValue(string fileName) { try { ContentDisposition disposition = new ContentDisposition { FileName = fileName }; return disposition.ToString(); } catch (FormatException) { return CreateRfc2231HeaderValue(fileName); } }
protected string GetHeaderValue(string fileName) { try { ContentDisposition contentDisposition = new ContentDisposition { FileName = fileName, Inline = Inline }; return contentDisposition.ToString(); } catch (FormatException ex) { return "FormatException"; } }
ActionResult Download(Guid id, bool inline) { using (var db = ApplicationDbContext.Create()) { ManagedFile file = db.Files.Where(x => x.Id == id) .Include(x => x.CatalogRecord) .Include(x => x.CatalogRecord.Organization).FirstOrDefault(); if (file == null) { //TODO error page? return(RedirectToAction("Index")); } // For non-public files, or unpublished files, verify that the user should have access. // For public files, anybody can download. if (!file.IsPublicAccess || file.CatalogRecord.Status != CatalogRecordStatus.Published) { EnsureUserIsAllowed(file.CatalogRecord, db); EnsureUserCanDownload(file.CatalogRecord.Organization); } string processingDirectory = SettingsHelper.GetProcessingDirectory(file.CatalogRecord.Organization, db); string path = Path.Combine(processingDirectory, file.CatalogRecord.Id.ToString()); path = Path.Combine(path, file.Name); // Use the PublicName as the downloaded file name. string fileDownloadName = file.Name; var cd = new System.Net.Mime.ContentDisposition { FileName = fileDownloadName, Inline = inline, }; Response.AppendHeader("Content-Disposition", cd.ToString()); // Set the MIME type. string ext = Path.GetExtension(cd.FileName).ToLower(); string mimeType = MediaTypeNames.Application.Octet; if (ext == ".pdf") { mimeType = MediaTypeNames.Application.Pdf; } return(File(path, mimeType)); } }
//public ActionResult Install() //{ // return File(Url.Content("~/installChocolatey.ps1"), "text/plain"); //} public FileResult InstallerBatchFile() { const string batchFile = @"@echo off SET DIR=%~dp0% %systemroot%\System32\WindowsPowerShell\v1.0\powershell.exe -NoProfile -ExecutionPolicy Bypass -Command ""((new-object net.webclient).DownloadFile('https://chocolatey.org/install.ps1','install.ps1'))"" %systemroot%\System32\WindowsPowerShell\v1.0\powershell.exe -NoProfile -ExecutionPolicy Bypass -Command ""& '%DIR%install.ps1' %*"" SET PATH=%PATH%;%ALLUSERSPROFILE%\chocolatey\bin"; var contentDisposition = new ContentDisposition { FileName = "installChocolatey.cmd", Inline = true, }; Response.AppendHeader("Content-Disposition", contentDisposition.ToString()); return File(Encoding.ASCII.GetBytes(batchFile), "text/plain"); }
/// <summary> /// Downloads exported image. /// </summary> /// <param name="key">Key.</param> /// <returns>Result.</returns> public ActionResult DownloadExportedImage(string key) { byte[] fileData = {}; ActionResult ret = null; string extension = string.Empty; Api.Export.ExportKey exportKey = null; string fullPhysicalPath = string.Empty; ContentDisposition contentDisposition = null; if (Api.Export.ExportKey.TryParse(key, out exportKey)) { extension = System.Enum.GetName(typeof(Models.ImageExportFormat), exportKey.Format).ToLowerInvariant(); fullPhysicalPath = System.Web.HttpContext.Current.Server.MapPath(string.Format("~/App_Data/Exports/{0}/{1}.{2}", exportKey.PresentationId, exportKey.ToString(), extension)); } if (System.IO.File.Exists(fullPhysicalPath)) { fileData = ServiceAdapter.ImageToPdfComposer.TryCompose(fullPhysicalPath); if (fileData == null) { fileData = System.IO.File.ReadAllBytes(fullPhysicalPath); System.IO.File.Delete(fullPhysicalPath); } } contentDisposition = new System.Net.Mime.ContentDisposition() { FileName = string.Format("image.{0}", extension), Inline = false }; Response.AppendHeader("Content-Disposition", contentDisposition.ToString()); Response.Headers.Remove("Cache-Control"); Response.Headers.Remove("Pragma"); Response.Headers.Remove("Expires"); ret = File(fileData, "application/octet-stream"); return(ret); }
public async Task <ActionResult> Download(Guid id, string format, string authToken) { using (var web = new System.Net.Http.HttpClient()) { web.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", authToken); var stream = await web.GetStreamAsync(WebConfigurationManager.AppSettings["ServiceUrl"] + "/response/ExportResponse?requestID=" + id + "&format=" + format); var contentDisposition = new System.Net.Mime.ContentDisposition { FileName = "response." + format, Inline = false }; Response.AppendHeader("Content-Disposition", contentDisposition.ToString()); return(File(stream, "application/octet-stream")); } }
/// <summary> /// Renders the content. /// </summary> /// <param name="fileName">Name of the file.</param> /// <param name="path">The path.</param> /// <param name="contentType">Type of the content.</param> /// <param name="inline">if set to <c>true</c> [inline].</param> /// <returns></returns> private ActionResult RenderContent(string fileName, string path, string contentType, bool inline) { string lowerpath = path.ToLower(); if (lowerpath.StartsWith("http") || lowerpath.StartsWith("www")) { return(new RedirectResult(path)); } ContentDisposition contentDisposition = new System.Net.Mime.ContentDisposition { FileName = fileName, Inline = inline, }; Response.AppendHeader("Content-Disposition", contentDisposition.ToString()); return(File(path, contentType)); }
/// <summary> /// Downloads the specified file by id. /// </summary> /// <param name="id">The id.</param> /// <returns></returns> public ActionResult Download(int id, Guid identityToken) { try { FileViewModel file = _fileService.GetFileByIdAndIdentityToken(id, identityToken); ContentDisposition contentDisposition = new System.Net.Mime.ContentDisposition { FileName = file.FileName, Inline = false, }; Response.AppendHeader("Content-Disposition", contentDisposition.ToString()); return(File(file.Content, file.ContentType)); } catch (Exception) { return(RedirectToAction("Index", "Home")); } }
public override void ProcessRequest(HttpContext context) { if (!BXPrincipal.Current.IsCanOperate("UpdateSystem")) { BXAuthentication.AuthenticationRequired(); return; } if (context.Request.QueryString["original"] != null) { System.Net.Mime.ContentDisposition cd = new System.Net.Mime.ContentDisposition(); cd.FileName = "web.config"; context.Response.ContentType = "application/x-octet-stream"; context.Response.AddHeader("Content-Disposition", cd.ToString()); context.Response.TransmitFile(HostingEnvironment.MapPath("~/web.config")); return; } if (context.Request.QueryString["convert4"] != null) { System.Net.Mime.ContentDisposition cd = new System.Net.Mime.ContentDisposition(); cd.FileName = "web.config"; context.Response.ContentType = "application/x-octet-stream"; context.Response.AddHeader("Content-Disposition", cd.ToString()); context.Response.ContentEncoding = Encoding.UTF8; XmlWriterSettings ws = new XmlWriterSettings(); ws.Indent = true; ws.IndentChars = "\t"; ws.Encoding = Encoding.UTF8; using (XmlWriter xml = XmlWriter.Create(context.Response.OutputStream, ws)) { MakeConfig(xml); } context.Response.End(); return; } base.ProcessRequest(context); }
public static void WriteResponse(HttpResponse response, byte[] filearray, string type) { response.ClearContent(); response.Buffer = true; response.Cache.SetCacheability(HttpCacheability.Private); response.ContentType = "application/pdf"; ContentDisposition contentDisposition = new ContentDisposition(); contentDisposition.FileName = "SaldoDotacao.pdf"; contentDisposition.DispositionType = type; response.AddHeader("Content-Disposition", contentDisposition.ToString()); response.BinaryWrite(filearray); HttpContext.Current.ApplicationInstance.CompleteRequest(); try { response.End(); } catch (System.Threading.ThreadAbortException) { } }
public void Test2() { var contentDispositionHeader = new System.Net.Mime.ContentDisposition() { FileName = "foo bar.pdf", DispositionType = "attachment" }; var result = contentDispositionHeader.ToString(); _output.WriteLine(result); var parsed = Microsoft.Net.Http.Headers.ContentDispositionHeaderValue.Parse(result); Assert.Equal("foo bar.pdf", parsed.FileName); var parsed0 = System.Net.Http.Headers.ContentDispositionHeaderValue.Parse(result); Assert.Equal("foo bar.pdf", parsed0.FileName); }
public FileResult Obtener_Archivo_Validado(String pSigString, String pNum_DNI) { String s_Nombre = "Archivo_PDF_Verificado.pdf"; String pRutaArchivo = string.Concat(System.Web.Hosting.HostingEnvironment.MapPath("~/DocumentosGenerados/"), "Firma_Electrina" + pNum_DNI + ".pdf"); byte[] archivo = ObtenerArchivo_ValTopaz(pSigString, pRutaArchivo); if (archivo == null) { s_Nombre = "NO SE CUMPLE LAS VALIDACIONES PARA MOSTRAR EL ARCHIVO"; } var cd = new System.Net.Mime.ContentDisposition { FileName = s_Nombre, Inline = false, CreationDate = DateTime.Now }; Response.AppendHeader("Content-Disposition", cd.ToString()); return(File(archivo, MediaTypeNames.Application.Octet)); }
public ActionResult Index(string filename, string ext) { if (string.IsNullOrEmpty(filename) || string.IsNullOrEmpty(ext)) return HttpNotFound(); filename = filename + "." + ext; Document document = ReaderFactory.GetDocumentReader().GetDocument(filename); if (document == null) { return HttpNotFound(); } var cd = new ContentDisposition { FileName = document.FileName, Inline = false, }; Response.AppendHeader("Content-Disposition", cd.ToString()); var contentType = GetContentType(document.FileName); return File(document.FileData, contentType); }
public ActionResult GetCandidateReportPdf(long id) { // return link file of Candidate report long clientId = -1; if (!long.TryParse(Session["ClientId"].ToString(), out clientId)) { return(RedirectToAction("ErrorDontHavePermission", "Error")); } var candidate = db.Candidates.FirstOrDefault(s => (s.CandidateId == id && s.ClientId == clientId)); if (candidate == null) { return(RedirectToAction("ErrorDontHavePermission", "Error")); } try { var attachment = db.AttachmentFiles.Where(s => s.CandidateId == id).OrderByDescending(s => s.AttachmentFileId).Take(1).Single(); if (attachment != null) { byte[] filedata = System.IO.File.ReadAllBytes(attachment.Link); string contentType = MimeMapping.GetMimeMapping(attachment.Link); var cd = new System.Net.Mime.ContentDisposition { FileName = attachment.FileName, Inline = true, }; Response.AppendHeader("Content-Disposition", cd.ToString()); return(File(filedata, contentType)); } return(RedirectToAction("Error", "Error")); } catch (Exception e) { return(RedirectToAction("Error", "Error")); } }
public IActionResult Download(string docPath, bool?ieDownload) { string filename = Path.GetFileName(docPath); string filepath = docPath; byte[] filedata = System.IO.File.ReadAllBytes(filepath); string contentType = MediaTypeNames.Application.Pdf; if (ieDownload == null || Convert.ToBoolean(ieDownload) == false) { var cd = new System.Net.Mime.ContentDisposition { FileName = filename, Inline = false, }; HttpContext.Response.Headers["Content-Disposition"] = cd.ToString(); } return(File(filedata, contentType)); }
public override void ExecuteResult(ControllerContext context) { if (context == null) { throw new ArgumentNullException("context"); } HttpResponseBase response = context.HttpContext.Response; 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. ContentDisposition disposition = new ContentDisposition() { FileName = FileDownloadName }; string headerValue = disposition.ToString(); context.HttpContext.Response.AddHeader("Content-Disposition", headerValue); } WriteFile(response); }
/// <summary> /// Downloads the protocol with the given id as a pdf-file or returns the user /// to the view with the table of info about meeting protocols if something went wrong. /// </summary> /// <param name="id">The id of the meeting protocol-file to download.</param> /// <returns>redirects the user to the table with info about meeting protcols /// if something went wrong, otherwise returns a file-download-prompt.</returns> /// <exception cref="ArgumentException">Thrown if the method is called without an id.</exception> public ActionResult DownloadFile(int? id) { //if no id is provided, an exception is thrown. if (!id.HasValue) { throw new ArgumentException("id must be provided!"); } LgProtocolModel model; //Fetches info about the meeting protocol based on its id from the database . using (IProtocolRepository repository = new ProtocolRepository()) { model = repository.GetLgProtocolById(id.Value); } //Gets the original file name from the model with info fetched from the database string fileName = model.Name + ".pdf"; //Gets the path to the file on the server. string filePath = Server.MapPath("~/App_Data/LgProtocols") + "/" + model.NameOnServer; try { //Loads the file i´nto memory. byte[] fileData = System.IO.File.ReadAllBytes(filePath); //Gets the extension of the file based on the mimetype. string contentType = MimeMapping.GetMimeMapping(".pdf"); /*Creates a contentdisposition header and appends it to the http-response. It is needed for a download prompt to be generated.*/ var contentDisposition = new ContentDisposition { FileName = fileName, Inline = false }; Response.AppendHeader("Content-Disposition", contentDisposition.ToString()); return File(fileData, contentType); } catch { //if an error occured return teh user tot he view with the table of info abóut meeting protocols. return RedirectToAction("Index"); } }
public ActionResult DownloadVersion(Guid id, string sha) { using (var db = ApplicationDbContext.Create()) { ManagedFile file = db.Files.Where(x => x.Id == id) .Include(x => x.CatalogRecord) .Include(x => x.CatalogRecord.Organization).FirstOrDefault(); if (file == null) { //TODO error page? return(RedirectToAction("Index")); } EnsureUserIsAllowed(file.CatalogRecord, db); EnsureUserCanDownload(file.CatalogRecord.Organization); string processingDirectory = SettingsHelper.GetProcessingDirectory(file.CatalogRecord.Organization, db); string path = Path.Combine(processingDirectory, file.CatalogRecord.Id.ToString()); using (var repo = new LibGit2Sharp.Repository(path)) { var blob = repo.Lookup <Blob>(sha); var cd = new System.Net.Mime.ContentDisposition { FileName = file.Name,//always uses the current file name right now... Inline = false, Size = blob.Size }; var contentStream = blob.GetContentStream(); Response.AppendHeader("Content-Disposition", cd.ToString()); return(new FileStreamResult(contentStream, "application/octet-stream")); } } }
/// <summary> /// Downloads exported video. /// </summary> /// <param name="key">Key.</param> /// <returns>Result.</returns> public ActionResult DownloadExportedVideo(string key) { byte[] fileData = {}; ActionResult ret = null; Api.Export.ExportKey exportKey = null; string fullPhysicalPath = string.Empty; ContentDisposition contentDisposition = null; if (Api.Export.ExportKey.TryParse(key, out exportKey)) { fullPhysicalPath = System.Web.HttpContext.Current.Server.MapPath(string.Format("~/App_Data/Exports/{0}/{1}.mp4", exportKey.PresentationId, exportKey.ToString())); } if (System.IO.File.Exists(fullPhysicalPath)) { fileData = System.IO.File.ReadAllBytes(fullPhysicalPath); System.IO.File.Delete(fullPhysicalPath); } contentDisposition = new System.Net.Mime.ContentDisposition() { FileName = "video.mp4", Inline = false }; Response.AppendHeader("Content-Disposition", contentDisposition.ToString()); Response.Headers.Remove("Cache-Control"); Response.Headers.Remove("Pragma"); Response.Headers.Remove("Expires"); ret = File(fileData, "application/octet-stream"); return(ret); }
public ActionResult InvoiceDigitalSignPDF(long obId) { string url = ConfigurationManager.AppSettings.Get("InvoicePDFPreview") + obId.ToString(); String pfxPath = ConfigurationManager.AppSettings.Get("PFXFileForInvoice"); string pfxpassword = ConfigurationManager.AppSettings.Get("PFXFileForInvoiceKey"); // PdfDocument pdf = new PdfDocument(); CLayer.Invoice data = BLayer.Invoice.GetInvoiceByOfflineBooking(obId); string filename = ""; if (data.InvoiceNumber == "") { filename = "Invoice_" + data.InvoiceId.ToString() + ".pdf"; } else { filename = "Invoice_" + data.InvoiceNumber + ".pdf"; } string filepath = Server.MapPath(INVOICE_FOLDER) + filename; //var thread = new Thread(() => pdf.LoadFromHTML(url, false, false, false)); //thread.SetApartmentState(ApartmentState.STA); //thread.Start(); //thread.Join(); WebClient wc = new WebClient(); wc.DownloadFile(url, filepath); // pdf.SaveToFile(filepath); //pdf.PageSettings.Margins.Top = 2.2F; //pdf.PageSettings.Margins.Left = 2.2F; //pdf.PageSettings.Margins.Right = 2.2F; // pdf.Close(); //pdf = new PdfDocument(); PdfDocument pdf = new PdfDocument(); pdf.LoadFromFile(filepath); PdfCertificate digi = new PdfCertificate(pfxPath, pfxpassword); PdfSignature signature = new PdfSignature(pdf, pdf.Pages[0], digi, "Staybazar.com"); signature.ContactInfo = "Staybazar.com"; signature.Certificated = true; signature.DocumentPermissions = PdfCertificationFlags.ForbidChanges; pdf.SaveToFile(filepath); pdf.Close(); byte[] filedata = System.IO.File.ReadAllBytes(filepath); string contentType = MimeMapping.GetMimeMapping(filepath); var cd = new System.Net.Mime.ContentDisposition { FileName = filename, Inline = true, }; Response.AppendHeader("Content-Disposition", cd.ToString()); return(File(filedata, contentType)); }
public async virtual Task<ActionResult> DownloadImageTemplate(string imageTemplatePath) { var encryptor = new DPAPIEncryptor(); var uriString = encryptor.Decrypt(imageTemplatePath); var uri = new Uri(uriString, UriKind.Absolute); var contentDisposition = new ContentDisposition() { FileName = uri.Segments.Last(), Inline = false, }; var webClient = new WebClient(); webClient.UseDefaultCredentials = true; var fileData = await webClient.DownloadDataTaskAsync(uri); Response.AppendHeader("Content-Disposition", contentDisposition.ToString()); return File(fileData, "image/png"); }
public void ToStringTest4 () { ContentDisposition dummy = new ContentDisposition ("attachment"); dummy.Parameters.Add ("foo", "bar"); Assert.AreEqual (1, dummy.Parameters.Count); Assert.AreEqual ("attachment; foo=bar", dummy.ToString ()); }
public void ToStringTest3 () { ContentDisposition dummy = new ContentDisposition (); dummy.Size = 0; Assert.AreEqual ("attachment; size=0", dummy.ToString ()); }
public ActionResult Download(Guid id) { var file = db.Revisions.Include(rev => rev.ParentDocument).Single(rev => rev.GUID == id); var isAuthenticated = User.Identity != null; if (isAuthenticated && OfficeExtensions.Contains(file.Extension) && isInternetExplorer) return Redirect("file://" + _hostname + "/Uploads/" + file.FileName); else { var cd = new ContentDisposition { FileName = file.ParentDocument.DisplayName, Inline = true }; Response.AppendHeader("Content-Disposition", cd.ToString()); return File(Path.Combine(Serverpath, file.FileName), MimeMapping.GetMimeMapping(file.FileName)); } }
private void StartSection (string section, ContentType sectionContentType, TransferEncoding transferEncoding, ContentDisposition contentDisposition) { SendData (String.Format ("--{0}", section)); SendHeader ("content-type", sectionContentType.ToString ()); SendHeader ("content-transfer-encoding", GetTransferEncodingName (transferEncoding)); if (contentDisposition != null) SendHeader ("content-disposition", contentDisposition.ToString ()); SendData (string.Empty); }
public void TestDisposition(ContentDisposition disposition, int paramCount) { string fieldText = disposition.ToString(); MimeFieldParameters fieldParams = new MimeFieldParameters(); Assert.DoesNotThrow(() => fieldParams.Deserialize(fieldText)); Assert.True(fieldParams.Count == paramCount); Assert.Equal(disposition.DispositionType, fieldParams[0].Value); Assert.Equal(disposition.FileName, fieldParams["filename"]); Assert.DoesNotThrow(() => Compare(fieldParams, disposition.Parameters)); string fieldTextSerialized = null; Assert.DoesNotThrow(() => fieldTextSerialized = fieldParams.Serialize()); fieldParams.Clear(); Assert.DoesNotThrow(() => fieldParams.Deserialize(fieldTextSerialized)); Assert.True(fieldParams.Count == paramCount); Assert.DoesNotThrow(() => new ContentDisposition(fieldTextSerialized)); }
/// <summary> /// Executes the View for Export /// </summary> public ActionResult BeerXml(int recipeId) { var recipe = this.RecipeService.GetRecipeById(recipeId); if (recipe == null) { return this.Issue404(); } var xmlString = this.BeerXmlExporter.Export(recipe); var xmlBytes = Encoding.Default.GetBytes(xmlString); var disposition = new ContentDisposition { // for example foo.bak FileName = string.Format("{0}-brewgr.xml", StringCleaner.CleanForUrl(recipe.RecipeName)), // always prompt the user for downloading, set to true if you want // the browser to try to show the file inline Inline = false, }; Response.AppendHeader("Content-Disposition", disposition.ToString()); return new FileStreamResult(new MemoryStream(xmlBytes), "text/xml"); }
public static string GetHeaderValue(string fileName) { try { // first, try using the .NET built-in generator ContentDisposition disposition = new ContentDisposition() { FileName = fileName }; return disposition.ToString(); } catch (FormatException) { // otherwise, fall back to RFC 2231 extensions generator return CreateRfc2231HeaderValue(fileName); } }
bool Equals(ContentDisposition other) { return(other != null && ToString() == other.ToString()); }
bool Equals (ContentDisposition other) { return other != null && ToString () == other.ToString (); }
public async Task<ActionResult> DownloadFile(SpecifyOptionsViewModel viewModel) { if (!await CheckOrganisationExists(viewModel.OrganisationID)) { return RedirectToAction("SelectOrganisation"); } if (!ModelState.IsValid) { return RedirectToAction("SpecifyOptions", new { viewModel.OrganisationID }); } TestFileSettings settings = new TestFileSettings( viewModel.OrganisationID, new Quarter(viewModel.ComplianceYear, viewModel.Quarter)); settings.NumberOfAatfs = viewModel.NumberOfAatfs; settings.NumberOfAes = viewModel.NumberOfAes; settings.AllProducers = viewModel.AllProducers; settings.NumberOfProduces = viewModel.NumberOfProducers; FileInfo xmlFile = await GenerateXml(settings); ContentDisposition cd = new ContentDisposition { FileName = xmlFile.FileName, Inline = false, }; Response.AppendHeader("Content-Disposition", cd.ToString()); return File(xmlFile.Data, "application/xml"); }
public ActionResult DownloadRecordOfMeeting(int id) { //oie RecordOfMeeting recordOfMeeting = _RecordOfMeetingService.GetRecordOfMeeting(new RecordOfMeetingFilter() { Id = id }); var cd = new ContentDisposition { FileName = recordOfMeeting.Date.ToShortDateString(), Inline = true }; Response.AddHeader("Content-Disposition", cd.ToString()); return File(recordOfMeeting.PDFFile, "application/pdf"); }
public override void ExecuteResult(ControllerContext context) { HttpResponseBase response = context.HttpContext.Response; try { response.ClearHeaders(); response.ClearContent(); } catch { } response.TrySkipIisCustomErrors = true; if (this.Resource == null) { response.ContentType = "text/plain"; response.StatusCode = (int)HttpStatusCode.NotFound; response.Write(response.Status); return; } HttpContext httpContext = HttpContext.Current; // check if client has cached copy ETag etag = new HashETag(this.Resource.Hash); if (etag.HandleETag(httpContext, HttpCacheability.ServerAndPrivate, this.IsDebug)) { return; } if (String.IsNullOrEmpty(this.Resource.ContentType)) { response.ContentType = "text/plain"; } else { response.ContentType = this.Resource.ContentType; } // this helps IE determine the Content-Type // http://tools.ietf.org/html/rfc2183#section-2.3 ContentDisposition disposition = new ContentDisposition { Inline = !this.IsAttachment, FileName = String.IsNullOrEmpty(this.Filename) ? Path.GetFileNameWithoutExtension(this.ResourcePath)+'.'+this.Resource.FileExtension : this.Filename }; response.AddHeader("Content-Disposition", disposition.ToString()); ResourceHandler.WriteResponse(httpContext, this.Resource, this.IsDebug); }
public async Task Invoke(HttpContext httpContext) { ClearCacheIfTimeout(); Stream oldStream = httpContext.Response.Body; Stream memStream = null; int imageId = -1; try { // (other middleware) => (we're here) => MVC var endpointFeature = httpContext.Features[typeof(IEndpointFeature)] as IEndpointFeature; Endpoint endpoint = endpointFeature?.Endpoint; if (endpoint != null) { var descriptor = endpoint.Metadata.GetMetadata <ControllerActionDescriptor>(); if (descriptor?.ControllerName == ImageCachingOptions.ControllerName && descriptor?.ActionName == ImageCachingOptions.ActionName) { imageId = Convert.ToInt32(httpContext.Request.RouteValues["id"]); var dirInfo = new DirectoryInfo(ImageCachingOptions.CacheDirectoryPath); FileInfo file = dirInfo.GetFiles(imageId + "_*.bmp").FirstOrDefault(); if (file != null) { int underscoreIndex = file.Name.IndexOf('_'); var cd = new System.Net.Mime.ContentDisposition { FileName = file.Name.Substring(underscoreIndex + 1), Inline = false }; httpContext.Response.Headers.Add("Content-Disposition", cd.ToString()); using (var img = Image.Load(file.FullName)) { // For production application we would recommend you create a FontCollection // singleton and manually install the ttf fonts yourself as using SystemFonts // can be expensive and you risk font existing or not existing on a deployment // by deployment basis. Font font = SystemFonts.CreateFont("Arial", 10); using (var img2 = img.Clone(ctx => ApplyScalingWaterMarkSimple(ctx, font, "This is from cache", Color.White, 5))) { using var m = new MemoryStream(); img2.Save(m, new SixLabors.ImageSharp.Formats.Bmp.BmpEncoder()); m.Seek(0, SeekOrigin.Begin); await m.CopyToAsync(httpContext.Response.Body); } } lastCacheHit = DateTime.UtcNow; return; } else { memStream = new MemoryStream(); httpContext.Response.Body = memStream; } } } await Next(httpContext); // (other middleware) <= (we're here) <= MVC // here we can save the image in the cache if (memStream != null && httpContext.Response.ContentType == "image/bmp") { var dirInfo = new DirectoryInfo(ImageCachingOptions.CacheDirectoryPath); if (dirInfo.GetFileSystemInfos("*.bmp").Length >= ImageCachingOptions.CacheCapacity) { return; } if (httpContext.Response.Headers.TryGetValue("Content-Disposition", out var values)) { var cd = new ContentDisposition(values); var path = Path.Combine(ImageCachingOptions.CacheDirectoryPath, imageId + "_" + cd.FileName); using var fileStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None); memStream.Position = 0; await memStream.CopyToAsync(fileStream); lastCacheHit = DateTime.UtcNow; } } } finally { if (memStream != null) { memStream.Position = 0; await memStream.CopyToAsync(oldStream); httpContext.Response.Body = oldStream; } } }
public void ToStringTest2 () { ContentDisposition dummy = new ContentDisposition (); Assert.AreEqual ("attachment", dummy.ToString ()); }
public static string GetHeaderValue(string fileName) { // If fileName contains any Unicode characters, encode according // to RFC 2231 (with clarifications from RFC 5987) foreach (char c in fileName) { if ((int)c > 127) { return CreateRfc2231HeaderValue(fileName); } } // Knowing there are no Unicode characters in this fileName, rely on // ContentDisposition.ToString() to encode properly. // In .Net 4.0, ContentDisposition.ToString() throws FormatException if // the file name contains Unicode characters. // In .Net 4.5, ContentDisposition.ToString() no longer throws FormatException // if it contains Unicode, and it will not encode Unicode as we require here. // The Unicode test above is identical to the 4.0 FormatException test, // allowing this helper to give the same results in 4.0 and 4.5. ContentDisposition disposition = new ContentDisposition() { FileName = fileName }; return disposition.ToString(); }
public async Task<ActionResult> DownloadFile(SpecifyOptionsViewModel viewModel) { if (!await CheckOrganisationExists(viewModel.OrganisationID)) { return RedirectToAction("SelectOrganisation"); } if (!ModelState.IsValid) { return RedirectToAction("SpecifyOptions", new { viewModel.OrganisationID }); } ProducerListSettings settings = new ProducerListSettings() { OrganisationID = viewModel.OrganisationID, SchemaVersion = viewModel.SchemaVersion, ComplianceYear = viewModel.ComplianceYear, NumberOfNewProducers = viewModel.NumberOfNewProducers, NumberOfExistingProducers = viewModel.NumberOfExistingProducers, NoCompaniesForNewProducers = viewModel.NoCompaniesForNewProducers, IncludeMalformedSchema = viewModel.IncludeMalformedSchema, IncludeUnexpectedFooElement = viewModel.IncludeUnexpectedFooElement, IgnoreStringLengthConditions = viewModel.IgnoreStringLengthConditions, }; PcsXmlFile xmlFile = await GenerateXml(settings); ContentDisposition cd = new ContentDisposition { FileName = xmlFile.FileName, Inline = false, }; Response.AppendHeader("Content-Disposition", cd.ToString()); return File(xmlFile.Data, "application/xml"); }
private ActionResult PrepareFileResult(IReport report, string ext, bool download, byte[] renderedBytes, ReportRegistry.Report reportInfo) { string fileDownloadName; var customFileName = report as ICustomFileName; if (customFileName != null) fileDownloadName = customFileName.GetFileName(); else fileDownloadName = (reportInfo.Title ?? reportInfo.Key) + "_" + DateTime.Now.ToString("yyyyMMdd_HHss"); fileDownloadName += "." + ext; if (download) { return new FileContentResult(renderedBytes, "application/octet-stream") { FileDownloadName = fileDownloadName }; } var cd = new ContentDisposition { Inline = true, FileName = fileDownloadName }; Response.AddHeader("Content-Disposition", cd.ToString()); return File(renderedBytes, UploadHelper.GetMimeType(fileDownloadName)); }
public ActionResult sendFileThoughMail(string reciverEmailAddress, int FileId) { MembershipHelp mHelp = new MembershipHelp(); var role = mHelp.logingUserRole(User.Identity.Name); var roleId = db.RoleMasters.Where(w => w.Name == role).Select(s => s.Id).FirstOrDefault(); var canEdit = (from m in db.MenuInfoes join rm in db.RoleMenuMappings on m.Id equals rm.MenuInfoId where m.MenuURL.Contains("ArtWorks") && rm.RoleId == roleId select rm.CanEdit).FirstOrDefault(); if (!canEdit) { return(RedirectToAction("Index")); } string returnString = ""; var saftyModel = db.SafetyModels.FirstOrDefault(); for (int l = 0; l < 2; l++) { var body = ""; if (l == 1) { body = "Email is sent To " + reciverEmailAddress + " using the Login Id = " + User.Identity.Name.ToString(); } if (l == 1) { reciverEmailAddress = saftyModel.Email; } var senderEmail = new MailAddress(saftyModel.Email, "Interior Design Firm"); var receiverEmail = new MailAddress(reciverEmailAddress, "Interior Desgin"); var password = saftyModel.MailPassword; var FileName = "File is attached "; string beginHtmlTag = "<html><head></head><body>"; body = body + "<BR> Please , have a look on the attached file"; string endHtmlTag = "</body></html>"; var smtp = new SmtpClient { Host = "smtp.gmail.com", Port = 587, EnableSsl = true, DeliveryMethod = SmtpDeliveryMethod.Network, UseDefaultCredentials = false, Credentials = new NetworkCredential(senderEmail.Address, password) }; using (var mess = new MailMessage(senderEmail, receiverEmail) { Subject = FileName, Body = beginHtmlTag + body + endHtmlTag }) { mess.IsBodyHtml = true; try { if (FileId.ToString() != string.Empty) { var artWork = db.ArtWorks.Where(w => w.Id == FileId).FirstOrDefault(); var FileAddress = Path.Combine(Server.MapPath("~/Content/Uploads/Originals"), artWork.FileAddressInfo); string fileExtension = Path.GetExtension(FileAddress); if (fileExtension.ToString().ToUpper() == ".EXE" || fileExtension.ToString().ToUpper() == ".DLL" || fileExtension.ToString().ToUpper() == ".ZIP") { return(RedirectToAction("Index")); } string filepath = FileAddress; byte[] filedata = System.IO.File.ReadAllBytes(filepath); // check if the file size is greater than 25 mb if (26214400 < filedata.Length) { returnString = "File size can not be greater than 25 MB"; int trhoughException = 1 / Convert.ToInt32("0"); } string contentType = MimeMapping.GetMimeMapping(filepath); var cd = new System.Net.Mime.ContentDisposition { FileName = artWork.FileAddressInfo, Inline = false }; Response.AppendHeader("Content-Disposition", cd.ToString()); MemoryStream ms = new MemoryStream(File(filedata, contentType).FileContents); mess.Attachments.Add(new Attachment(ms, artWork.FileAddressInfo, contentType)); smtp.Send(mess); returnString = "Mail is sent to " + reciverEmailAddress; } } catch (Exception ex) { if (returnString == "") { returnString = "Please , Check the Net Connection or Email Address"; } } } } return(Json(returnString, JsonRequestBehavior.AllowGet)); }