public ActionResult ConfirmCart(CartDto cart) { // check for second submission if (Session[CartKey] == null) { TempData["ErrorMessage"] = "Already submitted this cart; invoice has already been generated"; return RedirectToAction("DisplayCart"); } // dropping cart reference here to prevent double submission Session[CartKey] = null; if (cart.Rows == null || cart.Rows.Count == 0) { TempData["ErrorMessage"] = "Submitted an empty cart"; return View("EditCart", GetOrInitCartFromSession()); } var invoiceFile = Service.ConfirmCart(cart); var encoding = Encoding.UTF8; var bytes = invoiceFile.FileRows.SelectMany(row => encoding.GetBytes(row + Environment.NewLine)).ToArray(); var contentDisposition = new System.Net.Mime.ContentDisposition { FileName = string.Format("Invoice{0}.csv", invoiceFile.InvoiceNumber), Inline = false }; Response.AppendHeader("Content-Disposition", contentDisposition.ToString()); return File(bytes, contentDisposition.ToString()); }
public FileResult GetImage(string id, string ff) { try { if (!String.IsNullOrEmpty(id)) { byte[] fileBytes = System.IO.File.ReadAllBytes(String.Format(@"{0}/{1}/{2}.jpg", AppConfigManager.HeyFolderPath, ff, id)); string fileName = String.Format("{0}.jpg", id); var cd = new System.Net.Mime.ContentDisposition { FileName = fileName, Inline = true, }; Response.AppendHeader("Content-Disposition", cd.ToString()); return File(fileBytes, System.Net.Mime.MediaTypeNames.Image.Jpeg); } } catch (Exception ex) { string message = ex.Message; // changed here by yahya //throw new Exception(CodeHelper.UnableToFindFile); } return null; }
public ActionResult GetMediaItem(string id) { ActionResult res = Json(new ResultResponse(false, "Unknown error."), JsonRequestBehavior.AllowGet); try { var storedMediaItem = _mediaItemManager.GetOne(id); if (storedMediaItem != null) { var cd = new System.Net.Mime.ContentDisposition { FileName = storedMediaItem.Name, Inline = true }; Response.AppendHeader("Content-Disposition", cd.ToString()); res = File(storedMediaItem.Data, storedMediaItem.ContentType); } else { res = Json(new ResultResponse(false, "Couldn't find stored media item with ID = " + id + "."), JsonRequestBehavior.AllowGet); } } catch (Exception e) { res = Json(new ResultResponse(false, "Error: " + e.Message), JsonRequestBehavior.AllowGet); } return(res); }
public ActionResult Download() { WeatherDisplayData svetaNedeljaData = GetCityWeatherData("Sveta Nedelja"); WeatherDisplayData splitData = GetCityWeatherData("Split"); WeatherDisplayData osijekData = GetCityWeatherData("Osijek"); string filePath = Server.MapPath("~/weatherData.txt"); FileInfo allDataFile = new FileInfo(filePath); if (allDataFile.Exists) { allDataFile.Delete(); } using (StreamWriter w = allDataFile.CreateText()) { w.WriteLine(new JavaScriptSerializer().Serialize(svetaNedeljaData)); w.WriteLine(new JavaScriptSerializer().Serialize(splitData)); w.WriteLine(new JavaScriptSerializer().Serialize(osijekData)); } var cd = new System.Net.Mime.ContentDisposition { FileName = filePath, Inline = false, }; Response.AppendHeader("Content-Disposition", cd.ToString()); return(File(allDataFile.OpenRead(), "text/plain")); }
public ActionResult DownloadPorId(int id, string dataInicial, string dataFinal) { var appSettings = ConfigurationManager.AppSettings; string _diretorioProcessado = appSettings["_diretorioProcessado"]; var nomeArquivoGerado = _bllExportacao.ExportarPedido(id, dataInicial, dataFinal); string filepath = string.Format("{0}{1}{2}", AppDomain.CurrentDomain.BaseDirectory, _diretorioProcessado, nomeArquivoGerado); if (System.IO.File.Exists(filepath)) { byte[] filedata = System.IO.File.ReadAllBytes(filepath); string contentType = MimeMapping.GetMimeMapping(filepath); var cd = new System.Net.Mime.ContentDisposition { FileName = nomeArquivoGerado, Inline = false, }; Response.AppendHeader("Content-Disposition", cd.ToString()); return(File(filedata, contentType)); } else { return(RedirectToAction("Index")); } }
public ActionResult GetMessagePayloadFile(string testCaseId) { try { var testCase = _context.TestCases.FindAsync(testCaseId).Result; var filePath = testCase.PayloadFilePath; Log.Information( "GetMessagePayloadFile get file for protocol {Protocol}, testCaseName {TestCaseName}, {TestCaseId} with filePath {FilePath}", testCase.Protocol, testCase.TestName, testCaseId, filePath); var contentDispositionHeader = new System.Net.Mime.ContentDisposition() { FileName = testCase.PayloadFileName, DispositionType = "attachment" }; Response.Headers.Add("Content-Disposition", contentDispositionHeader.ToString()); return(GetPayload(filePath)); } catch (Exception e) { Log.Error(e, "GetMessagePayloadFile for protocol testCaseName {TestCaseName} failed", testCaseId); return(new NotFoundResult()); } }
public ActionResult Download(string Name) { byte[] filedata = { }; string contentType = string.Empty; try { string fullFilePath = center.GetCertificatePath(Name); string filename = Path.GetFileName(fullFilePath); string filepath = fullFilePath; filedata = System.IO.File.ReadAllBytes(filepath); contentType = MimeMapping.GetMimeMapping(filepath); System.Net.Mime.ContentDisposition cd = new System.Net.Mime.ContentDisposition { FileName = filename, Inline = true, }; Response.AppendHeader("Content-Disposition", cd.ToString()); } catch (Exception ex) { Logger.LogManager.Instance.WriteError("Error while trying to download certificate: " + ex.Message); } return File(filedata, contentType); }
public async Task<ActionResult> DownloadDocument(string feedName, string guid) { var parameters = new { feedName = feedName, guid = guid }; var attachment = await WebApiService.Instance.GetAsync<AttachmentDto>("/Attachments/Get", UserManager.User.AccessToken, parameters); if (attachment != null) { var blobData = await WebApiService.Instance.GetBlobAsync("/Documents/Get", UserManager.User.AccessToken, parameters); var cd = new System.Net.Mime.ContentDisposition { FileName = attachment.FileName, // Prompt the user for downloading; set to true if you want // the browser to try to show the file 'inline' (display in-browser // without prompting to download file). Set to false if you // want to always prompt them to download the file. Inline = true, }; Response.AppendHeader("Content-Disposition", cd.ToString()); // View document return File(blobData, attachment.ContentType); } return RedirectToAction("NotFound", "Error"); }
public ActionResult DetailsDownload(string stringId = "") { var o = m.MediaItemGetByStringId(stringId); if (o == null) { return(HttpNotFound()); } string extension; RegistryKey key; object value; // Open the Registry, attempt to locate the key key = Registry.ClassesRoot.OpenSubKey(@"MIME\Database\Content Type\" + o.ContentType, false); // Attempt to read the value of the key value = (key == null) ? null : key.GetValue("Extension", null); // Build/create the file extension string extension = (value == null) ? string.Empty : value.ToString(); // Create a new Content-Disposition header var cd = new System.Net.Mime.ContentDisposition { // Assemble the file name + extension FileName = $"img-{stringId}{extension}", // Force the media item to be saved (not viewed) Inline = false }; // Add the header to the response Response.AppendHeader("Content-Disposition", cd.ToString()); return(File(o.Content, o.ContentType)); }
public async Task <IActionResult> GetLatestArtifact([Required] string product, [Required] string os, [Required] string architecture) { var provider = new FileExtensionContentTypeProvider(); string contentType; var response = await ReleaseArtifactService.GetLatestArtifact(product, os, architecture); if (response == null) { return(NotFound("The specified product was not found!")); } //Determine the content type if (!provider.TryGetContentType(response.FileName, out contentType)) { contentType = "application/octet-stream"; } //Set the filename of the response var cd = new System.Net.Mime.ContentDisposition { FileName = response.FileName }; Response.Headers.Add("Content-Disposition", cd.ToString()); return(new FileContentResult(response.Payload, contentType)); }
public ActionResult VMT(string id) { long providedId; if (!long.TryParse(id, out providedId)) { return View("Error"); } var cd = new System.Net.Mime.ContentDisposition { // for example foo.bak FileName = id + ".vmt", // 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", cd.ToString()); string vmt_file = String.Format(@"""UnlitGeneric"" {{ ""$basetexture"" ""vgui\logos\{0}"" ""$translucent"" ""1"" ""$ignorez"" ""1"" ""$vertexcolor"" ""1"" ""$vertexalpha"" ""1"" }} ", id); return File(Encoding.UTF8.GetBytes(vmt_file), "application/vnd.valve.vmt"); }
public ActionResult ProjectFileDownload(Guid?id) { try { T_OE_DOCUMENTS doc = db_EECIP.GetT_OE_DOCUMENTS_ByID(id.ConvertOrDefault <Guid>()); var cd = new System.Net.Mime.ContentDisposition { FileName = doc.DOC_NAME, Inline = false }; Response.AppendHeader("Content-Disposition", cd.ToString()); if (doc.DOC_CONTENT != null) { return(File(doc.DOC_CONTENT, doc.DOC_FILE_TYPE ?? "application/octet-stream")); } } catch (Exception ex) { throw ex; } TempData["Error"] = "Unable to download document."; return(RedirectToAction("Index", "Forum")); }
public async Task <IActionResult> GetFileByPublicId(string publicIdAndExtension) { int index = publicIdAndExtension.IndexOf('.'); if (index <= 0) { return(NotFound()); } string publicId = publicIdAndExtension.Remove(index); var fileFromRepo = await _fileRepo.GetFile(publicId); if (fileFromRepo == null) { return(NotFound()); } // Check permissions and co. if (!fileFromRepo.IsPublic) { return(Unauthorized("This image is not public, please use the private URL for this image")); } var cd = new System.Net.Mime.ContentDisposition { FileName = fileFromRepo.Name + fileFromRepo.FileExtension, Inline = true }; Response.Headers.Add("Content-Disposition", cd.ToString()); var filePath = _utilsService.GenerateFilePath(publicId, fileFromRepo.FileExtension); return(PhysicalFile(filePath, fileFromRepo.ContentType)); }
public ActionResult CreatePDF(ReportModel model) { try { var helper = GetHelper(); helper.ServiceUserId = GetUser().Id; var upsert = helper.CreatePDF(false, model.Students); if (upsert.i_RecordId() <= 0) { ShowError(upsert.ErrorMsg); return(RedirectOnError()); } // 2017.06.14: Compute correct name for Universe var document = helper.GetDoc(); string fileName = string.Format("{0} Payments Report.pdf", Settings.COMPANY_ABBR); var cd = new System.Net.Mime.ContentDisposition { FileName = fileName, Inline = false }; Response.AddHeader("Content-Disposition", cd.ToString()); byte[] doc = System.IO.File.ReadAllBytes(document); return(File(doc, "application/x-download")); } catch (Exception ex) { ShowError(ex.Message); return(RedirectOnError()); } }
public virtual ActionResult PrintFolhaObra(int id) { FT_ManagementContext context = HttpContext.RequestServices.GetService(typeof(FT_ManagementContext)) as FT_ManagementContext; FolhaObra fo = context.ObterFolhaObra(id); if (!this.User.IsInRole("Admin") && !this.User.IsInRole("Escritorio") && fo.IntervencaosServico.Where(i => i.IdTecnico == context.ObterUtilizador(int.Parse(this.User.Claims.First().Value.ToString())).IdPHC).Count() == 0) { return(Redirect("~/Home/AcessoNegado")); } var file = context.PreencherFormularioFolhaObra(fo).ToArray(); var output = new MemoryStream(); output.Write(file, 0, file.Length); output.Position = 0; var cd = new System.Net.Mime.ContentDisposition { FileName = "FolhaObra_" + id + ".pdf", Inline = false, Size = file.Length, CreationDate = DateTime.Now, }; Response.Headers.Add("Content-Disposition", cd.ToString()); context.AdicionarLog(context.ObterUtilizador(int.Parse(this.User.Claims.First().Value)).NomeUtilizador, "Foi impressa uma folha de obra: " + id, 3); return(File(output, System.Net.Mime.MediaTypeNames.Application.Pdf)); }
public ActionResult exportaExcel() { string filename = "Empleados.csv"; string filepath = @"c:\tmp\" + filename; StreamWriter sw = new StreamWriter(filepath); sw.WriteLine("ID,Nombre,Cedula,Tanda,Porcentaje Comision, Fecha de ingreso, Estado"); //Encabezado foreach (var i in db.Empleadoes.ToList()) { if (i.Estado) { sw.WriteLine(i.ID.ToString() + "," + i.Nombre + "," + i.Cedula + "," + i.Tanda + "," + i.PorcientoComision.ToString() + "%" + "," + i.FechaIngreso.ToString() + "," + "Activo"); } else { sw.WriteLine(i.ID.ToString() + "," + i.Nombre + "," + i.Cedula + "," + i.Tanda + "," + i.PorcientoComision.ToString() + "%" + "," + i.FechaIngreso.ToString() + "," + "Inactivo"); } } sw.Close(); byte[] filedata = System.IO.File.ReadAllBytes(filepath); string contentType = MimeMapping.GetMimeMapping(filepath); var cd = new System.Net.Mime.ContentDisposition { FileName = filename, Inline = false, }; Response.AppendHeader("Content-Disposition", cd.ToString()); return File(filedata, contentType); }
public ActionResult DownloadFile() { string path = currentFile; if (!String.IsNullOrEmpty(path)) { byte[] filedata = System.IO.File.ReadAllBytes(path); var cd = new System.Net.Mime.ContentDisposition { FileName = Path.GetFileName(path), Inline = true, }; currentFile = ""; Response.AppendHeader("Content-Disposition", cd.ToString()); return(File(filedata, "application/force-download")); } else { ViewBag.Message = "No existe el archivo"; return(RedirectToAction("Download")); } }
//Para imprimir en Excel Inicio public ActionResult exportaExcel() { string filename = "Proveedores.csv"; string filepath = @"c:\tmp\" + filename; StreamWriter sw = new StreamWriter(filepath); sw.WriteLine("sep=,"); sw.WriteLine("Nombre,Cedula_o_RNC,Nombre_Comercial,Activo"); //Encabezado foreach (var i in db.Proveedores.ToList()) { sw.WriteLine(i.Nombre + "," + i.Cedula_o_RNC + "," + i.Nombre_Comercial + "," + i.Activo); } sw.Close(); byte[] filedata = System.IO.File.ReadAllBytes(filepath); string contentType = MimeMapping.GetMimeMapping(filepath); var cd = new System.Net.Mime.ContentDisposition { FileName = filename, Inline = false, }; Response.AppendHeader("Content-Disposition", cd.ToString()); return(File(filedata, contentType)); }
//Exportar a excel public ActionResult exportaExcel() { string filename = "prueba.csv"; string filepath = @"C:\temp\" + filename; StreamWriter sw = new StreamWriter(filepath); sw.WriteLine("ID del cliente,Nombre del cliente,Estado"); //Encabezado foreach (var i in db.CLIENTEs.ToList()) { sw.WriteLine(i.IdCliente.ToString() + "," + i.Nombre.ToString() + "," + i.IdCarrera.ToString()); } sw.Close(); byte[] filedata = System.IO.File.ReadAllBytes(filepath); string contentType = MimeMapping.GetMimeMapping(filepath); var cd = new System.Net.Mime.ContentDisposition { FileName = filename, Inline = false, }; Response.AppendHeader("Content-Disposition", cd.ToString()); return(File(filedata, contentType)); }
public ActionResult PostFileDownload(Guid?id) { try { PostFile doc = db_Forum.GetPostFile_ByID(id.ConvertOrDefault <Guid>()); var cd = new System.Net.Mime.ContentDisposition { FileName = doc.Filename, Inline = false }; Response.AppendHeader("Content-Disposition", cd.ToString()); if (doc.FileContent != null) { return(File(doc.FileContent, doc.FileContentType ?? "application/octet-stream")); } } catch (Exception ex) { throw ex; } TempData["Error"] = "Unable to download document."; return(RedirectToAction("Index", "Forum")); }
public ActionResult Exportar() { string filename = "Registro Visita.csv"; string filepath = @"C:\Users\Danyer\Desktop" + filename; StreamWriter sw = new StreamWriter(filepath); sw.WriteLine("Servicio,Descripcion,Estado"); //Encabezado foreach (var i in db.Registro_Visitas.ToList()) { sw.WriteLine(i.IdVisita.ToString() + "," + i.IdMedico.ToString() + "," + i.IdPaciente.ToString() + "," + i.FechaVisita + "," + i.HoraVisita + "," + i.Sintomas + "," + i.IdMedicamento.ToString() + "," + i.Recomendaciones + "," + i.Estado); } sw.Close(); byte[] filedata = System.IO.File.ReadAllBytes(filepath); string contentType = MimeMapping.GetMimeMapping(filepath); var cd = new System.Net.Mime.ContentDisposition { FileName = filename, Inline = false, }; Response.AppendHeader("Content-Disposition", cd.ToString()); return(File(filedata, contentType)); }
public ActionResult Descargar(string path) { //Recuperar path path = path.Replace("~", "/"); int cifradoValue = Int16.Parse(HttpContext.Request.Cookies["cifrado"].Value); //Descifrar SDES cipher = new SDES(); string rutaCifrado = cipher.DescifrarArchivo(path, Directories.directorioTemporal, cifradoValue); //Descomprimir string rutaComprimido = LZW.descomprimirArchivo(rutaCifrado, Directories.directorioDescargas); //Descargar if (!String.IsNullOrEmpty(rutaComprimido)) { byte[] filedata = System.IO.File.ReadAllBytes(rutaComprimido); var cd = new System.Net.Mime.ContentDisposition { FileName = Path.GetFileName(rutaComprimido), Inline = true, }; Response.AppendHeader("Content-Disposition", cd.ToString()); return(File(filedata, "application/force-download")); } else { return(RedirectToAction("Index")); } }
public IActionResult DownloadCreatedPackage(int id) { var package = _packagingService.GetCreatedPackageById(id); if (package == null) { return(NotFound()); } if (!System.IO.File.Exists(package.PackagePath)) { return(ValidationProblem("No file found for path " + package.PackagePath)); } var fileName = Path.GetFileName(package.PackagePath); var encoding = Encoding.UTF8; var cd = new System.Net.Mime.ContentDisposition { FileName = WebUtility.UrlEncode(fileName), Inline = false // false = prompt the user for downloading; true = browser to try to show the file inline }; Response.Headers.Add("Content-Disposition", cd.ToString()); // Set custom header so umbRequestHelper.downloadFile can save the correct filename Response.Headers.Add("x-filename", WebUtility.UrlEncode(fileName)); return(new FileStreamResult(System.IO.File.OpenRead(package.PackagePath), new MediaTypeHeaderValue("application/octet-stream") { Charset = encoding.WebName, })); }
public ActionResult exportaExcel() { string filename = "prueba.csv"; string filepath = @"c:\tmp\" + filename; StreamWriter sw = new StreamWriter(filepath); sw.WriteLine("Id tipo documento,Descripcion,Cuenta,Estado"); //Encabezado foreach (var i in db.Tipo_Documentos.ToList()) { sw.WriteLine(i.Id_tipoDocumento.ToString() + "," + i.Descripcion + "," + i.Cuenta_contable + "," + i.Estado); } sw.Close(); byte[] filedata = System.IO.File.ReadAllBytes(filepath); string contentType = MimeMapping.GetMimeMapping(filepath); var cd = new System.Net.Mime.ContentDisposition { FileName = filename, Inline = false, }; Response.AppendHeader("Content-Disposition", cd.ToString()); return(File(filedata, contentType)); }
public async Task <IActionResult> GetPrivateFileFromPublicId(string publicIdAndExtension) { int index = publicIdAndExtension.IndexOf('.'); if (index <= 0) { return(NotFound()); } string publicId = publicIdAndExtension.Remove(index); var fileFromRepo = await _fileRepo.GetFile(publicId); if (fileFromRepo == null) { return(NotFound()); } int userId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); if (fileFromRepo.OwnerId != userId) { return(Unauthorized()); } // File is owned by token holder var cd = new System.Net.Mime.ContentDisposition { FileName = fileFromRepo.Name + fileFromRepo.FileExtension, Inline = true }; Response.Headers.Add("Content-Disposition", cd.ToString()); var filePath = _utilsService.GenerateFilePath(fileFromRepo.PublicId, fileFromRepo.FileExtension); return(PhysicalFile(filePath, fileFromRepo.ContentType)); }
public IActionResult Get(int _, int tilePos1, int tilePos2) // _ used because we dont care :| { String targetTilePath = $"./data/tiles/16/{tilePos1}/{tilePos1}_{tilePos2}_16.png"; if (!System.IO.File.Exists(targetTilePath)) { var boo = Tile.DownloadTile(tilePos1, tilePos2, @"./data/tiles/16/"); //Lets download that lovely tile now, Shall we? if (boo == false) { return(Content("hi!")); } // Error 400 on Tile download error } //String targetTilePath = $"./data/tiles/creeper_tile.png"; byte[] fileData = System.IO.File.ReadAllBytes(targetTilePath); //Namespaces var cd = new System.Net.Mime.ContentDisposition { FileName = tilePos1 + "_" + tilePos2 + "_16.png", Inline = true }; Response.Headers.Add("Content-Disposition", cd.ToString()); return(File(fileData, "application/octet-stream", tilePos1 + "_" + tilePos2 + "_16.png")); }
public ActionResult DetailsDownload(string stringId = "") { var o = m.GetArtistMediaItemById(stringId); if (o == null) { return(HttpNotFound()); } else { string extension; RegistryKey key; object value; key = Registry.ClassesRoot.OpenSubKey(@"MIME\Database\Content Type\" + o.ContentType, false); value = (key == null) ? null : key.GetValue("Extension", null); extension = (value == null) ? string.Empty : value.ToString(); var cd = new System.Net.Mime.ContentDisposition { FileName = $"{stringId}{extension}", Inline = false }; Response.AppendHeader("Content-Disposition", cd.ToString()); return(File(o.Content, o.ContentType)); } }
} // Disable public ActionResult DownloadCompanyFile(int fileId) { var file = m_oServiceClient.Instance.GetCompanyFile(_context.UserId, fileId); var fileMetaData = _companyFiles.Get(fileId); if (file != null && fileMetaData != null) { var document = file; var cd = new System.Net.Mime.ContentDisposition { FileName = fileMetaData.FileName, Inline = true, }; Response.AppendHeader("Content-Disposition", cd.ToString()); if (fileMetaData.FileContentType.Contains("image") || fileMetaData.FileContentType.Contains("pdf") || fileMetaData.FileContentType.Contains("html") || fileMetaData.FileContentType.Contains("text")) { return(File(document, fileMetaData.FileContentType)); } var pdfDocument = AgreementRenderer.ConvertToPdf(document); return(pdfDocument == null?File(document, fileMetaData.FileContentType) : File(pdfDocument, "application/pdf")); } return(null); } // DownloadCompanyFile
public ActionResult DownloadDir(string path) { path = FixPath(path); if (!Directory.Exists(path)) { throw new Exception(LangRes("E_CreateArchive")); } string dirName = new FileInfo(path).Name; string tmpZip = _hostingEnvironment.MapWwwPath("~/FileManager/tmp/" + dirName + ".zip"); if (System.IO.File.Exists(tmpZip)) { System.IO.File.Delete(tmpZip); } ZipFile.CreateFromDirectory(path, tmpZip, CompressionLevel.Fastest, true); byte[] bytes = System.IO.File.ReadAllBytes(tmpZip); System.IO.File.Delete(tmpZip); var cd = new System.Net.Mime.ContentDisposition { // for example foo.bak FileName = dirName + ".zip", // always prompt the user for downloading, set to true if you want // the browser to try to show the file inline Inline = false, }; Response.Headers.Add("Content-Disposition", cd.ToString()); return(File(bytes, "application/force-download")); }
public ActionResult Download(string id, int azienda) { if (!string.IsNullOrEmpty(id)) { var service = new SferaService(); var info = new UserInfo(0, azienda); var documentoFileName = getDocumentoFileName(id, service, info); var documento = documentoFileName.Documento; var docInfo = getDocumentInfo(documento, service, info); if (docInfo.Body != null) { var fileName = documento.FileName; if (!fileName.EndsWith(".pdf")) fileName = $"{fileName}.pdf"; var cd = new System.Net.Mime.ContentDisposition { // for example foo.bak FileName = fileName, // always prompt the user for downloading, set to true if you want // the browser to try to show the file inline Inline = true, }; Response.AddHeader("set-cookie", "fileDownload=true; path=/"); Response.AppendHeader("Content-Disposition", cd.ToString()); return File(docInfo.Body, "application/pdf"); } } return null; }
public ActionResult ExportReport() { string filename = "Facturación.csv"; string filepath = @"C:\Users\Fabio Victor\Desktop\" + filename; StreamWriter sw = new StreamWriter(filepath); sw.WriteLine("Facturacion, Forma de Pago, Cantidad, Precio Unitario, Cantidad X Precio, ID Articulo, Articulos, ID Cliente, Cliente, Cedula Cliente, Condicion de Pago, ID Vendedor, Vendedor"); //Encabezado foreach (var i in db.Facturacion.ToList()) { sw.WriteLine(i.IdFacuracion.ToString() + "," + i.Forma_Pago + "," + i.Cantidad + "," + i.Precio_Unitario + "," + i.Cantidad * i.Precio_Unitario + "," + i.IdArticulo + "," + i.Articulos_Facturables.Descripcion + "," + i.IdCliente + "," + i.Clientes.Nombre_Comercial + "," + i.Clientes.Cedula + "," + i.Condiciones_Pagos.Descripcion + "," + i.IdVendedor + "," + i.Vendedores.Nombre); } sw.Close(); byte[] filedata = System.IO.File.ReadAllBytes(filepath); string contentType = MimeMapping.GetMimeMapping(filepath); var cd = new System.Net.Mime.ContentDisposition { FileName = filename, Inline = false, }; Response.AppendHeader("Content-Disposition", cd.ToString()); return(File(filedata, contentType)); }
public ActionResult exportaExcel() { string filename = "TiposUsuario.csv"; string filepath = @"c:\tmp\" + filename; StreamWriter sw = new StreamWriter(filepath); sw.WriteLine("ID,Descripcion,Estado"); //Encabezado foreach (var i in db.IdentityRoles.ToList()) { if (i.Estado) { sw.WriteLine(i.Id.ToString() + "," + i.Name + "," + "Activo"); } else { sw.WriteLine(i.Id.ToString() + "," + i.Name + "," + "Inactivo"); } } sw.Close(); byte[] filedata = System.IO.File.ReadAllBytes(filepath); string contentType = MimeMapping.GetMimeMapping(filepath); var cd = new System.Net.Mime.ContentDisposition { FileName = filename, Inline = false, }; Response.AppendHeader("Content-Disposition", cd.ToString()); return(File(filedata, contentType)); }
public static ActionResult TiffViewResult(string Type, string TypeId, string FilePath, Controller controller, HttpResponseBase Response) { var model = new UserExceptionViewModel(); model.TiffType = Type; model.TiffTypeId = TypeId; string extension = Path.GetExtension(FilePath); if (extension == ".tiff" || extension == ".tif") { TIF TheFile = new TIF(FilePath); model.TotalTIFPgs = TheFile.PageCount; TheFile.Dispose(); var result = GetViewResult(controller, "UserException/TiffViewerModal", model); return(result); } else { byte[] fileBytes = System.IO.File.ReadAllBytes(FilePath); var cd = new System.Net.Mime.ContentDisposition { FileName = Path.GetFileName(FilePath), // 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", cd.ToString()); var result = new FileContentResult(fileBytes, MimeMapping.GetMimeMapping(FilePath)); return(result); } }
/// <summary> /// Get Document /// </summary> /// <param name="oid">Oid docsDocument</param> /// <returns>ActionResult</returns> public ActionResult GetDocument(string oid) { var info = new DocumentInfo { OidDocument = Guid.Parse(oid), Version = 1 }; if (!string.IsNullOrWhiteSpace(oid)) { DocsDocument.DownloadDocument(info, ConfigHelper.DownloadLocation, DocumentDownloadMode.LastVersion); } var cd = new System.Net.Mime.ContentDisposition { FileName = Path.GetFileName(info.DocumentName), // 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", cd.ToString()); return(File(info.DocumentName, MimeType.GetMimeType(info.DocumentName))); }
public ActionResult Download(Guid id) { var Context = new ProjectDBEntities(); var track = Context.Tracks.Find(id); if (track == null) { Content("test"); } var cd = new System.Net.Mime.ContentDisposition { FileName = "track.mp3", Inline = false, }; Response.AppendHeader("Content-Disposition", cd.ToString()); var path = Server.MapPath("~" + track.TrackPath); byte[] file = System.IO.File.ReadAllBytes(path); return(File(file, "application/octet-stream")); }
public ActionResult exportaExcel() { string filename = "Usuarios.csv"; string filepath = @"c:\tmp\" + filename; StreamWriter sw = new StreamWriter(filepath); sw.WriteLine("ID,Nombre,Cedula,Tipo de Usuario,Limite de credito,Fecha de Registro,Estado"); //Encabezado foreach (var i in db.Usuarios.ToList()) { if (i.Estado) { sw.WriteLine(i.ID.ToString() + "," + i.Nombre + "," + i.Cedula + "," + i.Tipo_Usuario.Name + "," + i.LimiteCredito.ToString() + "," + i.FechaRegistro.ToString() + "," + "Activo"); } else { sw.WriteLine(i.ID.ToString() + "," + i.Nombre + "," + i.Cedula + "," + i.Tipo_Usuario.Name + "," + i.LimiteCredito.ToString() + "," + i.FechaRegistro.ToString() + "," + "Inactivo"); } } sw.Close(); byte[] filedata = System.IO.File.ReadAllBytes(filepath); string contentType = MimeMapping.GetMimeMapping(filepath); var cd = new System.Net.Mime.ContentDisposition { FileName = filename, Inline = false, }; Response.AppendHeader("Content-Disposition", cd.ToString()); return(File(filedata, contentType)); }
public ActionResult Pdf() { var cd = new System.Net.Mime.ContentDisposition { FileName = @"thornton-resume.pdf", Inline = false, }; Response.AppendHeader("Content-Disposition", cd.ToString()); return File(@"..\Content\thornton-resume.pdf", "application/pdf"); }
// GET: /Sql/Download? public ActionResult Download(string id) { var result = !string.IsNullOrEmpty(id) ? new SqloogleSearcher(ConfigurationManager.AppSettings.Get("SearchIndexPath")).Find(id) : null; if (result != null) { var cd = new System.Net.Mime.ContentDisposition { FileName = $"{id}.sql", Inline = false, }; Response.AppendHeader("Content-Disposition", cd.ToString()); return File(new MemoryStream(Encoding.ASCII.GetBytes(result["sqlscript"])), "application/x-sql"); } throw new HttpException(404, "NotFound"); }
public ActionResult Download(string ISBN) { WebClient Client = new WebClient(); Book Download = BooksRepository.GetBookByISBN(ISBN); byte[] bookData = Client.DownloadData(ConfigurationManager.AppSettings["MOBI_URL"].ToString() + ISBN + ".mobi"); var cd = new System.Net.Mime.ContentDisposition { FileName = Download.Title.Replace("(", String.Empty).Replace(")", String.Empty) + ".mobi", Inline = false, }; Response.AppendHeader("Content-Disposition", cd.ToString()); return File(bookData, "application/x-mobipocket-ebook"); }
public ActionResult SpecSheet() { string path = AppDomain.CurrentDomain.BaseDirectory + "\\App_Data\\Programming Exercise EYC.docx"; byte[] filedata = System.IO.File.ReadAllBytes(path); var cd = new System.Net.Mime.ContentDisposition { FileName = "Programming Exercise EYC.docx", Inline = false, }; Response.AppendHeader("Content-Disposition", cd.ToString()); return File(filedata, "application/msword"); }
public ActionResult Download(int campanhaId, string nome, string hash) { var rules = new CampanhaRules(); var filename = rules.GetPdfFilename(campanhaId, hash); System.Net.Mime.ContentDisposition cd = new System.Net.Mime.ContentDisposition { FileName = nome + ".pdf", Inline = true, }; Response.AppendHeader("Content-Disposition", cd.ToString()); return File(filename, "application/force-download"); }
public ActionResult Download(string hash) { var arquivoRules = new ArquivoRules(); var arquivo = arquivoRules.GetByHash(hash); System.Net.Mime.ContentDisposition cd = new System.Net.Mime.ContentDisposition { FileName = arquivo.Nome, Inline = true, }; Response.AppendHeader("Content-Disposition", cd.ToString()); return File(Application.Path("/Public/files/" + arquivo.Hash), "application/force-download"); }
// // GET: /RadChart/ public ActionResult Image(int MarketId = 1) { RadChart rc = new RadChart(); rc.CreateChart(MarketId); var cd = new System.Net.Mime.ContentDisposition { // always prompt the user for downloading, set to true if you want // the browser to try to show the file inline Inline = true, }; Response.AppendHeader("Content-Disposition", cd.ToString()); return File(rc.ChartData, "image/jpg"); }
// GET: Pigeon public ActionResult CV() { var file = new FileInfo("~/App_Data/cv.docx"); var cd = new System.Net.Mime.ContentDisposition { // for example foo.bak FileName = file.Name, // always prompt the user for downloading, set to true if you want // the browser to try to show the file inline Inline = false, }; //a comprendre Response.AppendHeader("Content-Disposition", cd.ToString()); return File ("~/App_Data/cv.docx", "application/ms-word"); }
public FileContentResult GetFileContent(string fileName) { string filepath = Path.Combine(Server.MapPath("~/Resources/PDF"), 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 ActionResult Get(int id) { var document = Data.Objects.GetStudentDocument(id); var cd = new System.Net.Mime.ContentDisposition { // for example foo.bak FileName = document.Name, // 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", cd.ToString()); return File(document.Contents.ToArray(), Helpers.Misc.GetMimeType(document.Name)); }
// // GET: /File/ public ActionResult Download(string EMPLOYEE_ID, string YEAR_CHECKUP, string FILE_NAME) { string filePath = string.Format("{0}\\{1}_{2}\\{3}", ConfigurationManager.AppSettings["FileUpload"], EMPLOYEE_ID, YEAR_CHECKUP, FILE_NAME); var cd = new System.Net.Mime.ContentDisposition { // for example foo.bak FileName = FILE_NAME, // 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", cd.ToString()); return File(filePath, Path.GetExtension(filePath)); }
public ActionResult GetData(string data ="", DataSource source= DataSource.Old) { string fileName = $"{source}data", filePath = ""; switch (data) { //case "csv": fileName = DataGenerator.GenerateCSVDocument(source, Path.GetTempPath()); fileName += ".csv"; break; } 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 ActionResult GetAttachment(string aid, string attname, string mid) { ExchangeService service = Connection.ConnectEWS(); EmailMessage message = EmailMessage.Bind(service, new ItemId(mid), new PropertySet(ItemSchema.Attachments)); message.Load(); System.IO.MemoryStream ms = new System.IO.MemoryStream(); byte[] ContentBytes = null; string filename = null; string contentType = null; foreach (Attachment att in message.Attachments) { if (aid == att.Id.ToString() && att is FileAttachment) { FileAttachment fileAt = att as FileAttachment; fileAt.Load(ms); filename = fileAt.Name; contentType = fileAt.ContentType; } else if (aid == att.Id.ToString() && att is ItemAttachment) { ItemAttachment itemAttachment = att as ItemAttachment; itemAttachment.Load(new PropertySet(EmailMessageSchema.MimeContent)); MimeContent mc = itemAttachment.Item.MimeContent; ContentBytes = mc.Content; filename = itemAttachment.Name + ".eml"; contentType = itemAttachment.ContentType; } } var cd = new System.Net.Mime.ContentDisposition { FileName = filename, // 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", cd.ToString()); // return the file return File(ms.ToArray() ?? ContentBytes, attname); }
// GET: Files public ActionResult DownloadCV(string url) { if (url != null) { byte[] filedata = System.IO.File.ReadAllBytes(url); string contentType = MimeMapping.GetMimeMapping(url); var cd = new System.Net.Mime.ContentDisposition { FileName = url, Inline = true, }; Response.AppendHeader("Content-Disposition", cd.ToString()); return File(filedata, contentType); } TempData["Error"] = "You have to load up your CV! Click Hello in the header."; return View("Apply"); }
public ActionResult Download(string FileName) { //byte[] fileBytes = System.IO.File.ReadAllBytes("~/App_Data/CalculatedAddresses.xlsx"); //var response = new FileContentResult(fileBytes, "application/octet-stream"); //response.FileDownloadName = "~/App_Data/CalculatedAddresses.xlsx"; //return response; string filepath = AppDomain.CurrentDomain.BaseDirectory + "/App_Data/" + FileName; byte[] filedata = System.IO.File.ReadAllBytes(filepath); string contentType = MimeMapping.GetMimeMapping(filepath); System.Net.Mime.ContentDisposition cd = new System.Net.Mime.ContentDisposition { FileName = FileName, Inline = true, }; Response.AppendHeader("Content-Disposition", cd.ToString()); return File(filedata, contentType); }
public ActionResult DetailsDownload(string stringId = "") { // Attempt to get the matching object var o = m.PropertyPhotoGetById(stringId); if (o == null) { return HttpNotFound(); } else { // Get file extension, assumes the web server is Microsoft IIS based // Must get the extension from the Registry (which is a key-value storage structure for configuration settings, for the Windows operating system and apps that opt to use the Registry) // Working variables string extension; RegistryKey key; object value; // Open the Registry, attempt to locate the key key = Registry.ClassesRoot.OpenSubKey(@"MIME\Database\Content Type\" + o.ContentType, false); // Attempt to read the value of the key value = (key == null) ? null : key.GetValue("Extension", null); // Build/create the file extension string extension = (value == null) ? string.Empty : value.ToString(); // Create a new Content-Disposition header var cd = new System.Net.Mime.ContentDisposition { // Assemble the file name + extension FileName = $"img-{stringId}{extension}", // Force the media item to be saved (not viewed) Inline = false }; // Add the header to the response Response.AppendHeader("Content-Disposition", cd.ToString()); return File(o.Content, o.ContentType); } }
// GET: Image public ActionResult Index(string extension, string imageType) { if (imageType.IsNullOrWhiteSpace()) { imageType = DefaultFileType; } if (extension.IsNullOrWhiteSpace()) { return View(); } if (!Types.Contains(imageType.ToLowerInvariant())) { ViewBag.Message = "Filetype not supported"; return View("Error"); } var dir = Path.Combine(Server.MapPath("~/Content"), imageType); var files = Directory.GetFiles(dir).Select(Path.GetFileNameWithoutExtension).ToArray(); if (!files.Contains(extension)) { //We don't have an icon for this file type return null; } var file = extension + "." + imageType; var fileLocation = Path.Combine(dir, file); var cd = new System.Net.Mime.ContentDisposition { // for example foo.bak FileName = file, // 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", cd.ToString()); return File(fileLocation, "image/" + imageType); }
public FileContentResult ReturnBookInPdf(string isbn) { try { var bytes = new BookManager().GetPdf(Convert.ToInt64(isbn)); const string mimeType = "application/pdf"; var content = new System.Net.Mime.ContentDisposition { FileName = "Test.pdf", Inline = true }; Response.AppendHeader("Content-Disposition", content.ToString()); return File(bytes, mimeType); } catch (Exception) { return null; } }
// GET: Issue public ActionResult Index(int id = 1) { try { string filename = id + ".pdf"; string filepath = AppDomain.CurrentDomain.BaseDirectory + "/Content/Issues/" + 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); } catch { return View(); } }
private ActionResult GetArticleFile(string filePath, string type, int articleId) { if (System.IO.File.Exists(filePath)) { string fileExtension = Path.GetExtension(filePath); string articleType = type == "review" ? "reviewers_" : string.Empty; string fileName = string.Format("{0}_{1}article_{2}{3}", SiteConfiguration.SystemName, articleType, articleId, fileExtension).ToLower(); var cd = new System.Net.Mime.ContentDisposition { FileName = fileName, Inline = true }; Response.AppendHeader("Content-Disposition", cd.ToString()); byte[] fileData = System.IO.File.ReadAllBytes(filePath); string contentType = MimeMapping.GetMimeMapping(filePath); return File(fileData, contentType); } return HttpNotFound(); }
public ActionResult Open(int id, string name) { MidiFile crumbsmodel = crumbsRepository.FindMidiFile(id); if (CurrentUser == null) return base.Content("Not Authorized"); Payment payment = crumbsRepository.FindConfirmedPaymentForMIDI(CurrentUser.UserID, id); if(payment == null) return base.Content("Not Authorized"); string path = MidiFileHelper.getMidiPath(crumbsmodel); string FullPath = HostingEnvironment.ApplicationPhysicalPath + path; var cd = new System.Net.Mime.ContentDisposition { // for example foo.bak FileName = crumbsmodel.FileName, // 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", cd.ToString()); return base.File(FullPath, "audio/midi"); }
public ActionResult DownloadMIDI(string userKey, int midiID) { User user = usersRepository.FindUser(userKey); if (user != null) { MidiFile crumbsmodel = crumbsRepository.FindMidiFile(midiID); if (crumbsmodel != null) { Payment payment = crumbsRepository.FindConfirmedPaymentForMIDI(user.UserID, midiID); if (payment != null) { string path = MidiFileHelper.getMidiPath(crumbsmodel); string FullPath = HostingEnvironment.ApplicationPhysicalPath + path; var cd = new System.Net.Mime.ContentDisposition { // for example foo.bak FileName = crumbsmodel.FileName, // 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", cd.ToString()); Response.AppendHeader("Access-Control-Allow-Origin", "*"); return File(FullPath, "audio/midi"); } } } return base.Content("Not Authorized"); }
public ActionResult Report(RequestIssue requestıssue, FormCollection formcollection) { ReportDocument rptH = new ReportDocument(); rptH.FileName = Server.MapPath("~/RDLC/SurveyReport.rpt"); rptH.Refresh(); //rptH.Load(); var value = new ParameterDiscreteValue(); var requests_ = db.RequestIssues.AsNoTracking().Include(p => p.Locations).Include(p => p.Personnels).Include(p => p.CorporateAccounts); int x_index = 0; foreach (int req_ in requests_.Select(i => i.RequestIssueID).ToList()) { value.Value = req_; rptH.ParameterFields["RequestIDs"].CurrentValues.Add(value); x_index++; } if (x_index == 0) { return RedirectToAction("Index", new { custommerr = "Belirttiğiniz Kriterlere Uygun Kayıt(lar) Bulunamadı" }); } // rptH.SetDataSource([datatable]); var cd = new System.Net.Mime.ContentDisposition { // for example foo.bak FileName = "rapor_klimasanHelpDeskAnketler.pdf", // always prompt the user for downloading, set to true if you want // the browser to try to show the file inline Inline = false, }; Stream stream = rptH.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat); Response.AppendHeader("Content-Disposition", cd.ToString()); return File(stream, "application/pdf"); }
public ActionResult Download(int id, string type = "docx", bool forcorrector = false) { try { using (PaperSubmissionsContext db = new PaperSubmissionsContext()) { var document = Tools.PaperSubmissionControllerHelper.CreateOrGetExistingDocument(db.PaperSubmissions.First(x => x.Id == id), forcorrector, false); if (type == "docx") { var cd = new System.Net.Mime.ContentDisposition { // for example foo.bak FileName = forcorrector ? "request_corrector.docx" : "request.docx", // 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", cd.ToString()); return File(System.IO.File.ReadAllBytes(document), "application/vnd.openxmlformats-officedocument.wordprocessingml.document"); } else if (type == "pdf") { string pdfFile = Tools.PaperSubmissionControllerHelper.ConvertDocxToPDF(document); var cd = new System.Net.Mime.ContentDisposition { // for example foo.bak FileName = "request.pdf", // 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", cd.ToString()); return File(pdfFile, "application/pdf"); } else return File(System.Text.ASCIIEncoding.Default.GetBytes("Указан неизвестный формат выходного файла."), "text"); } } catch (Exception ex) { logger.Error(ex.Message); return File(System.Text.ASCIIEncoding.Default.GetBytes(ex.Message), "text"); //RedirectToAction("Index", db.PaperSubmissions.ToList()); } }