Ejemplo n.º 1
3
        public override void ExecuteResult(ControllerContext context)
        {
            byte[] data = new CsvFileCreator().AsBytes(ModelListing);

            var fileResult = new FileContentResult(data, "text/csv")
            {
                FileDownloadName = "CsvFile.csv"
            };

            fileResult.ExecuteResult(context);
        }
Ejemplo n.º 2
3
        public FileContentResult Narrate(string text)
        {
            if (string.IsNullOrWhiteSpace(text))
            {
                throw new ArgumentNullException("text");
            }

            text = text.Trim();

            // Only allow short narrating
            if (text.Length > 50)
            {
                throw new ArgumentException("Given text is too length, please use sentences below 50 chars of length.", "text");
            }

            var cacheKey = "Narrated:" + text;
            var data = this.HttpContext.Cache[cacheKey] as byte[];

            if (data == null)
            {
                using (var client = new System.Net.WebClient())
                {
                    client.Headers.Add("user-agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)");
                    data = client.DownloadData(GoogleTranslateBaseAddress + this.Server.UrlEncode(text));
                    this.HttpContext.Cache.Add(
                        cacheKey,
                        data,
                        null,
                        Cache.NoAbsoluteExpiration,
                        TimeSpan.FromMinutes(5),
                        CacheItemPriority.Normal,
                        null);
                }
            }

            var result = new FileContentResult(data, "audio/mpeg");
            return result;
        }
Ejemplo n.º 3
1
 public FileContentResult LoadAttachment(int id)
 {
     var attachment = Repository.GetById<Attachment>(id);
     var fileResult = new FileContentResult(attachment.Content, attachment.ContentType);
     fileResult.FileDownloadName = attachment.Name;
     return fileResult;
 }
        public void ConstructorSetsFileContentsProperty() {
            // Arrange
            byte[] fileContents = new byte[0];

            // Act
            FileContentResult result = new FileContentResult(fileContents, "contentType");

            // Assert
            Assert.AreSame(fileContents, result.FileContents);
        }
Ejemplo n.º 5
1
        public ActionResult DownloadFile(string Id)
        {
            DBDataContext db = new DBDataContext();

            int IdCur = Convert.ToInt32(Id);
            EducationSearching.Files fFile = db.Files.FirstOrDefault(u => u.Id == IdCur);
            FileContentResult tr = new FileContentResult(fFile.FileData.ToArray(), fFile.MimeType);
            tr.FileDownloadName = fFile.Name;
            return tr;
        }
 public ActionResult Download(int id)
 {
     File file = db.File.Single(f => f.id == id);
     FileResult result = new FileContentResult(file.data.ToArray(), file.content_type);
     result.FileDownloadName = file.name;
     return result;
 }
Ejemplo n.º 7
0
        public static nameFile.FileContentResult GerarArquivo(string nomeExtensaoArquivo, MemoryStream memoryStream, string contentType, bool dataHoraControleAcesso = false)
        {
            try
            {
                if (dataHoraControleAcesso)
                {
                    using (MemoryStream msTemp = new MemoryStream(memoryStream.ToArray()))
                    {
                        memoryStream.Close();
                        memoryStream.Dispose();
                        memoryStream = Tecnomapas.Blocos.Etx.ModuloRelatorio.ITextSharpEtx.PdfMetodosAuxiliares.AdicionarDataHoraControleAcesso(msTemp);
                    }
                }

                nameFile.FileContentResult pdf = new nameFile.FileContentResult(memoryStream.ToArray(), contentType);
                pdf.FileDownloadName = nomeExtensaoArquivo;
                return(pdf);
            }
            catch (Exception exc)
            {
                Validacao.AddErro(exc);
            }
            finally
            {
                memoryStream.Close();
                memoryStream.Dispose();
            }
            return(null);
        }
Ejemplo n.º 8
0
 public FileResult Download(string file)
 {
     byte[] fileBytes = System.IO.File.ReadAllBytes(Path.Combine(Server.MapPath("~/ScanDocuments/"), file));
        // var response = new FileContentResult(fileBytes, "application/octet-stream");
     var response = new FileContentResult(fileBytes, "application/vnd.ms-excel");
     response.FileDownloadName = "AnnualSales_Calc" + CurrentMerchantID + "_" + ContractID;
     return response;
 }
Ejemplo n.º 9
0
        public ActionResult FileDownload(string id)
        {
            var keyId = int.Parse(id);

            var dissFile = _ncuEntities.dissertation_checklist.First(f => f.dissertation_id == keyId);

            var fileRes = new FileContentResult(dissFile.dissertation_file.ToArray(), "application/octet-stream");
            fileRes.FileDownloadName = dissFile.dissertation_file_name;

            return fileRes;
        }
Ejemplo n.º 10
0
        private FileResult GetFile(string id, string fileName)
        {
            using (SCORMObjectModel dataRepo = CurrentModel)
            {
                var result = dataRepo.GetFileBytes(id);
                var fileContent = new FileContentResult(result.Content, result.ContentType);
                fileContent.FileDownloadName = fileName;
                return fileContent;

            }
        }
Ejemplo n.º 11
0
        public FileContentResult ObterImagem(int id)
        {
            var _obj = _context.ImageMedias.Find(id);

            if (_obj != null)
            {
                System.Web.Mvc.FileContentResult _file = File(_obj.Imagem, _obj.ImagemMimeType);

                return(_file);
            }
            return(null);
        }
Ejemplo n.º 12
0
        public ActionResult Attendees()
        {
            var attendeeList = CurrentAttendee.List();
            var serializer = new CSVSerializer();

            var builder = new StringBuilder();

            builder.AppendLine(serializer.Header(new CurrentAttendee()));
            attendeeList.ForEach(x=>builder.AppendLine(serializer.Serialize(x)));

            var result = new FileContentResult(Encoding.ASCII.GetBytes(builder.ToString()), "text/csv")
                             {FileDownloadName = "Attendees.csv"};
            return new EmptyResult();
        }
Ejemplo n.º 13
0
        public FileContentResult Get(Guid id)
        {
            var file = _fileManager.GetById(id);

            if (file != null)
            {
                var result = new FileContentResult(file.Data.Bytes, file.Data.MimeType);
                return result;
            }
            else
            {
                return null;
            }
        }
Ejemplo n.º 14
0
        private FileContentResult GetImageById(Func<Guid, FileImage> func, Guid id)
        {
            var image = func(id);

            if (image != null)
            {
                var result = new FileContentResult(image.Data.Bytes, image.Data.MimeType);
                return result;
            }
            else
            {
                return null;
            }
        }
Ejemplo n.º 15
0
        public ActionResult ExportBoard(string id)
        {
            var exporter = new JsonExporter(id, TrelloConfigurationManager.ApiKey, HttpContext.User.Identity.Name);

            var csv = exporter.BuildCsv();

            if (string.IsNullOrWhiteSpace(csv))
            {
                return HttpNotFound("Unable to build CSV");
            }

            var result = new FileContentResult(Encoding.UTF8.GetBytes(exporter.BuildCsv()), "application/CSV");
            result.FileDownloadName = String.Format("{0:ddMMMHHmmss}.csv", DateTime.Now);

            return result;
        }
Ejemplo n.º 16
0
 public FileContentResult Download(string i)
 {
     //return new DownloadResult { VirtualPath = u, FileDownloadName = n };
     string infoCode = StringUtils.base64Decode(i);
     IdxInfoDAO infoDAO = new IdxInfoDAO(this.mapper);
     IdxInfoModels model = infoDAO.GetInfo(infoCode);
     if (model == null)
     {
         return null;
     }
     else
     {
         var fileRes = new FileContentResult(model.fileContent.ToArray(), "application/octet-stream");
         fileRes.FileDownloadName = model.fileName;
         return fileRes;
     }
 }
Ejemplo n.º 17
0
        public ActionResult FileDownload(string id)
        {
            /*well good to know that I can't use this in the repository.
            Need to do more research about conflict with type model admin and
            and filecontentresult. Would really like to put this method in the
            admin repository but at this point I am uncertain on how to proceed.
            */

            using (var _libEntity = new LibEntities())
            {
                int keyId = int.Parse(id);

                var file = _libEntity.file_uploads.First(f => f.q_id == keyId);

                var fileRes = new FileContentResult(file.attachment_file.ToArray(), "application/octet-stream");

                fileRes.FileDownloadName = file.attachment_file_name;

                return fileRes;
            }
        }
Ejemplo n.º 18
0
        public override void ExecuteResult(ControllerContext context)
        {
            var xmlSerializerNamespaces = new XmlSerializerNamespaces();
            xmlSerializerNamespaces.Add(string.Empty, string.Empty);

            var xmlWriterSettings = new XmlWriterSettings();
            xmlWriterSettings.Indent = false;
            xmlWriterSettings.OmitXmlDeclaration = true;

            var xmlSerializer = new XmlSerializer(typeof (Projects));

            string xml;
            using (var textWriter = new StringWriter())
            {
                using (XmlWriter xmlWriter = XmlWriter.Create(textWriter, xmlWriterSettings))
                {
                    xmlSerializer.Serialize(xmlWriter, _model, xmlSerializerNamespaces);
                }
                xml = textWriter.ToString();
            }
            var fileContentResult = new FileContentResult(Encoding.UTF8.GetBytes(xml), "text/xml");
            fileContentResult.FileDownloadName = "status.xml";
            fileContentResult.ExecuteResult(context);
        }
Ejemplo n.º 19
0
 public FileResult Download(string file)
 {
     string[] filename = file.Split('\\');
     string filePath = Server.MapPath(file).ToString();
     byte[] fileBytes = System.IO.File.ReadAllBytes(filePath);
     var response = new FileContentResult(fileBytes, "application/octet-stream");
     response.FileDownloadName = filename[1].ToString();
     return response;
 }
 private FileContentResult GetData(FileType fileType)
 {
     FileContentResult fr = null;
     ReadDataFromRouteData();
     string folderPrefix = string.Empty;
     switch (fileType.ToString())
     {
         case "js":
             folderPrefix = "Scripts";
             break;
         case "css":
             folderPrefix = "Styles";
             break;
         case "image":
             folderPrefix = "Images";
             break;
     }
     try
     {
         string fileFullPath = Path.Combine(_adminManager.DataPath, "knowledgebase", "portalConfiguration", clientId.ToString(), portalId.ToString(), folderPrefix, fileName);
         System.IO.MemoryStream s = _adminManager.ReadFileStream(fileFullPath);
         byte[] bts = new byte[s.Length];
         s.Read(bts, 0, bts.Length);
         string contentType = Mime.FromExtension(Path.GetExtension(fileFullPath));
         fr = new FileContentResult(bts, contentType);
     }
     catch (IOException ex)
     {
         KBCustomException kbCustExp = KBCustomException.ProcessException(ex, KBOp.LoadContent, KBErrorHandler.GetMethodName(), GeneralResources.IOError,
             new KBExceptionData("fileType", fileType.ToString()), new KBExceptionData("clientId", clientId), new KBExceptionData("portalId", portalId),
             new KBExceptionData("folderPrefix", folderPrefix), new KBExceptionData("fileName", fileName));
         throw kbCustExp;
     }
     catch (Exception ex)
     {
         KBCustomException kbCustExp = KBCustomException.ProcessException(ex, KBOp.LoadContent, KBErrorHandler.GetMethodName(), GeneralResources.GeneralError,
             new KBExceptionData("fileType", fileType.ToString()), new KBExceptionData("clientId", clientId), new KBExceptionData("portalId", portalId),
             new KBExceptionData("folderPrefix", folderPrefix), new KBExceptionData("fileName", fileName));
         throw kbCustExp;
     }
     return fr;
 }
Ejemplo n.º 21
0
        public FileResult DownloadInspecaoRecebimento(int idCTM)
        {
            CTM ctm = CTMService.getCTM(idCTM);

              Clientes cliente = ClienteService.getCliente(ctm.IDCliente);
              Equipamentos equipamento = EquipamentoService.getEquipamento(ctm.IDEquipamento);

              CtmFirc ctmFirc = CTMFircService.get(null, idCTM);
              CtmOrdemServico ordemServico = CTMOrdemServicoService.getCTMOrdemServicoByCTM(idCTM);
              var dictValue = new Dictionary<string, string>();

              dictValue.Add("PRODUTO", equipamento.Descricao);
              dictValue.Add("PN", ctm.PartNumber);
              dictValue.Add("SN", ctm.SerialNumber);
              dictValue.Add("FABRICANTE", equipamento.Fabricante);
              dictValue.Add("OSN", ordemServico != null ? ordemServico.IDCTMOrdemServico.ToString() : "");

              if (ctmFirc != null) {

            //dictValue.Add("DATA", ctmFirc.Data.Value.ToShortDateString());
            dictValue.Add("CMM", ctmFirc.CMM);
            dictValue.Add("REV", ctmFirc.NumeroRevisao);
            dictValue.Add("G1", returnXOREmpty(ctmFirc.Garantia));
            dictValue.Add("G0", returnXOREmpty(!ctmFirc.Garantia));
            dictValue.Add("C1", returnXOREmpty(ctmFirc.Conforme));
            dictValue.Add("C0", returnXOREmpty(!ctmFirc.Conforme));

            dictValue.Add("D1", returnXOREmpty(ctmFirc.DocumentosCumpridos));
            dictValue.Add("D0", returnXOREmpty(!ctmFirc.DocumentosCumpridos));

            dictValue.Add("DOCN", ctmFirc.NumeroDocumentoNaoCumprido);
            dictValue.Add("INSPETOR", ctmFirc.InspetorRecebimento);

            dictValue.Add("FALHASMAUFUNC", ctmFirc.RelatoriosFalhasMauFunc);
            dictValue.Add("TESTEFUNC", ctmFirc.TesteFuncional);
            dictValue.Add("DISCREAPOS", ctmFirc.DiscrepanciasAposMontagem);

            dictValue.Add("I1", returnXOREmpty(ctmFirc.InspecaoFalhasOcultas));
            dictValue.Add("I0", returnXOREmpty(!ctmFirc.InspecaoFalhasOcultas));
            dictValue.Add("DATA", DateTime.Now.ToShortDateString());
              }

              var b = new CTMStorageService().GetDocumentoPreenchidoAzure("MUP-009 FICHA DE INSPEÇÃO DE RECEBIMENTO E CONTINUADA - FIRC.docx", dictValue);

              var fileResult = new FileContentResult(b, "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
              fileResult.FileDownloadName = "MUP-009 FICHA DE INSPEÇÃO DE RECEBIMENTO E CONTINUADA - FIRC.docx";
              return fileResult;
        }
Ejemplo n.º 22
0
        private ActionResult ConvertToExcelFile(OperationDataParamConfigurationViewModel viewModel,
                                                OperationDataConfigurationViewModel data)
        {
            var resultPath = Server.MapPath(string.Format("{0}{1}/", TemplateDirectory, ConfigType.OperationData));
            if (!Directory.Exists(resultPath))
            {
                Directory.CreateDirectory(resultPath);
            }

            string workSheetName = new StringBuilder(viewModel.PeriodeType).ToString();
            string dateFormat = string.Empty;
            switch (viewModel.PeriodeType)
            {
                case "Yearly":
                    dateFormat = "yyyy";
                    break;
                case "Monthly":
                    dateFormat = "mmm-yy";
                    workSheetName = string.Format("{0}_{1}", workSheetName, viewModel.Year);
                    break;
                default:
                    dateFormat = "dd-mmm-yy";
                    workSheetName = string.Format("{0}_{1}-{2}", workSheetName, viewModel.Year,
                                                  viewModel.Month.ToString().PadLeft(2, '0'));
                    break;
            }

               string fileName = string.Format(@"{0}.xlsx", DateTime.Now.ToString("yyyymmddMMss"));
            /*string fileName = new StringBuilder(guid).Append(".xlsx").ToString();*/

            IWorkbook workbook = new Workbook();
            Worksheet worksheet = workbook.Worksheets[0];

            worksheet.Name = workSheetName;
            workbook.Worksheets.ActiveWorksheet = worksheet;
            RowCollection rows = workbook.Worksheets[0].Rows;
            ColumnCollection columns = workbook.Worksheets[0].Columns;

            Row headerRow = rows[0];
            headerRow.FillColor = Color.DarkGray;
            headerRow.Alignment.Horizontal = SpreadsheetHorizontalAlignment.Center;
            headerRow.Alignment.Vertical = SpreadsheetVerticalAlignment.Center;
            Column kpiIdColumn = columns[0];
            Column kpiNameColumn = columns[1];
            kpiIdColumn.Visible = false;

            headerRow.Worksheet.Cells[headerRow.Index, kpiIdColumn.Index].Value = "KPI ID";
            headerRow.Worksheet.Cells[headerRow.Index, kpiNameColumn.Index].Value = "KPI Name";

            int i = 1;
            foreach (var kpi in data.Kpis)
            {
                int j = 2;
                worksheet.Cells[i, kpiIdColumn.Index].Value = kpi.Id;
                worksheet.Cells[i, kpiNameColumn.Index].Value = string.Format(@"{0} ({1})", kpi.Name, kpi.MeasurementName);

                foreach (var operationData in kpi.OperationData.OrderBy(x => x.Periode))
                {
                    worksheet.Cells[headerRow.Index, j].Value = operationData.Periode;
                    worksheet.Cells[headerRow.Index, j].NumberFormat = dateFormat;
                    worksheet.Cells[headerRow.Index, j].AutoFitColumns();

                    worksheet.Cells[i, j].Value = operationData.Value;
                    worksheet.Cells[i, j].NumberFormat = "#,0.#0";
                    worksheet.Columns[j].AutoFitColumns();
                    j++;
                }

                Column totalValueColumn = worksheet.Columns[j];
                if (i == headerRow.Index + 1)
                {
                    worksheet.Cells[headerRow.Index, totalValueColumn.Index].Value = "Average";
                    worksheet.Cells[headerRow.Index, totalValueColumn.Index + 1].Value = "SUM";
                    Range r1 = worksheet.Range.FromLTRB(kpiNameColumn.Index + 1, i, j - 1, i);
                    worksheet.Cells[i, j].Formula = string.Format("=AVERAGE({0})", r1.GetReferenceA1());
                    worksheet.Cells[i, j + 1].Formula = string.Format("=SUM({0})", r1.GetReferenceA1());
                }
                else
                {
                    // add formula
                    Range r2 = worksheet.Range.FromLTRB(kpiNameColumn.Index + 1, i, j - 1, i);
                    worksheet.Cells[i, j].Formula = string.Format("=AVERAGE({0})", r2.GetReferenceA1());
                    worksheet.Cells[i, j + 1].Formula = string.Format("=SUM({0})", r2.GetReferenceA1());
                }

                i++;
            }

            kpiNameColumn.AutoFitColumns();
            worksheet.FreezePanes(headerRow.Index, kpiNameColumn.Index);

            string resultFilePath = string.Format("{0},{1}", resultPath, fileName);

            using (FileStream stream = new FileStream(resultFilePath, FileMode.Create, FileAccess.ReadWrite))
            {
                workbook.SaveDocument(stream, DevExpress.Spreadsheet.DocumentFormat.Xlsx);
                stream.Close();
            }

            string namafile = Path.GetFileName(resultFilePath);
            byte[] fileBytes = System.IO.File.ReadAllBytes(resultFilePath);
            var response = new FileContentResult(fileBytes, "application/octet-stream") { FileDownloadName = fileName };
            return response;
        }
Ejemplo n.º 23
-1
        /// <summary>
        /// Exports lectures to bitmap format.
        /// </summary>
        /// <param name="lectures">List of lectures.</param>
        /// <param name="title">Title displayed at top-left corner of the image.</param>
        /// <param name="created">Date the timetable was created from config.</param>
        /// <param name="linkToInfo">Hyperlink to webpage with additional information.</param>
        /// <param name="path">Path to folder where temp files will be created and where Inkspace folder is.</param>
        /// <param name="format">Bitmap format to export ie. png jpg pdf</param>
        /// <returns></returns>
        public FileResult DownloadAsBITMAP(List<TimetableField> lectures, string title, DateTime created, string linkToInfo,
            string path, string format)
        {
            SvgGenerator gen = new SvgGenerator();
            string text = gen.generateSVG(lectures, title, created, linkToInfo);
            Guid id = Guid.NewGuid();
            string svgName = string.Format(@"{0}.svg", id);
            string svgFileName = path + svgName;
            using (StreamWriter outfile = new StreamWriter(svgFileName))
            {
                outfile.Write(text);
            }

            string expName = string.Format(@"{0}.{1}", id, format);
            string expFileName = path + expName;

            string inkscapeArgs = string.Format(@"-f ""{0}"" -w 1600 -h 728 -e ""{1}""", svgFileName, expFileName);
            string inkspacePath = path + "InkscapePortable/InkscapePortable.exe";

            Process inkscape = Process.Start(new ProcessStartInfo(inkspacePath, inkscapeArgs));

            inkscape.WaitForExit(3000);
            FileStream fs = File.OpenRead(expFileName);
            byte[] data = new byte[fs.Length];
            fs.Read(data, 0, data.Length);
            var res = new FileContentResult(data, "image/" + format);
            res.FileDownloadName = "FJFIRozvrh." + format;
            fs.Close();
            File.Delete(expFileName);
            File.Delete(svgFileName);
            return res;
        }
		/// <summary>
		/// Load the specified resource.
		/// </summary>
		/// <param name='resource'>
		/// Resource.
		/// </param>
		/// <exception cref='HttpException'>
		/// Is thrown when the http exception.
		/// </exception>
		public ActionResult load(string resource) {
			if (!String.IsNullOrEmpty(Request.Headers["If-Modified-Since"])) {
				Response.StatusCode = 304;
	            Response.StatusDescription = "Not Modified";
	            return Content(String.Empty);
		    }
		    
		    string extension;
			string contentType;
			
			try {
				extension = Path.GetExtension(resource);
				contentType = this.resolveContextType(extension);
				
				FileContentResult fileContent = new FileContentResult(this.readResource(resource, extension), contentType);
				
				Response.ContentType = contentType;
					
				Response.CacheControl = "public";
				Response.Cache.SetCacheability(HttpCacheability.Public);
				
				Response.Cache.SetLastModified(this.getResourcesCreationTime());
				
				 
				
				return fileContent;
			} catch(FileNotFoundException exception) {
				throw new HttpException(404, "Not found", exception);
			}
		}
Ejemplo n.º 25
-1
        public FileResult Download(string FileName, string Platform)
        {
            string fileExtension = Path.GetExtension(FileName);
            if (fileExtension.ToLower() == ".plist")
            {
                //pList are generated
                string ipaFileName = String.Format("{0}.ipa", Path.GetFileNameWithoutExtension(FileName));
                string ipaFilePath = Path.Combine(Server.MapPath("~/App_Data/Files"), ipaFileName);


                string baseUrl = Common.Functions.GetBaseUrl();
                if (baseUrl == null)
                    baseUrl = "http://localhost/";
                string xml = Platforms.iOS.iOSBundle.GenerateBundlesSoftwarePackagePlist(
                    ipaFilePath,
                   string.Format("{0}App/Download?FileName={1}", baseUrl, ipaFileName));

                var bytes = Encoding.UTF8.GetBytes(xml);
                var result = new FileContentResult(bytes, System.Net.Mime.MediaTypeNames.Text.Xml);
                result.FileDownloadName = FileName;
                return result;
            }
            else
            {
                string filePath = Path.Combine(Server.MapPath("~/App_Data/Files"), FileName);
                //Return actual file
                byte[] fileBytes = System.IO.File.ReadAllBytes(filePath);
                return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, FileName);
            }

        }
Ejemplo n.º 26
-1
 public ActionResult DownloadSQL()
 {
     var bytes = System.Text.Encoding.UTF8.GetBytes(_installer.GetInstallScript());
     var result = new FileContentResult(bytes, "text/plain");
     result.FileDownloadName = "install.sql";
     return result;
 }
Ejemplo n.º 27
-1
        public FileResult RecuperarImagem(byte[] arquivo)
        {
            FileResult saida = null;
            if (arquivo != null && arquivo.Length > 0)
                saida = new FileContentResult(arquivo, "image/jpg");

            return saida;
        }
Ejemplo n.º 28
-1
        public override void ExecuteResult(ControllerContext context)
        {
            var result = new FileContentResult(
                  _chart.GetBytes(_imageType),
                  "image/" + _imageType);

            result.ExecuteResult(context);
        }
Ejemplo n.º 29
-1
            public FileResult Download(string file,string name)
            {

                byte[] fileBytes = System.IO.File.ReadAllBytes(file);
                var response = new FileContentResult(fileBytes, "application/octet-stream");
                response.FileDownloadName = name;
                return response;
            }
Ejemplo n.º 30
-1
        /// <summary>
        /// 导出文件
        /// </summary>
        /// <param name="fileContents">字节数组</param>
        /// <param name="outputName">要输出的文件名称,含扩展名</param>
        public void OutPut(byte[] fileContents, string outputName)
        {
            var fileResult = new FileContentResult(fileContents, MimeMapping.GetMimeMapping(outputName))
            {
                FileDownloadName = outputName
            };

            fileResult.ExecuteResult(this.context);
        }
Ejemplo n.º 31
-1
        public override void ExecuteResult(ControllerContext context)
        {
            //excel -> icon-pageexcel
            //xml -> icon-pagecode
            //csv -> icon-pageattach

            FileContentResult contentResult = null;

            string jsonData = JSON.Serialize(data);

            if (exportFormat == "icon-pagecode")
                jsonData = jsonData.Replace("&", "&amp;").Replace("<", "&lt;").Replace(">", "&gt;");

            SubmitHandler handler = new SubmitHandler(jsonData);
            XmlNode xmlData = handler.Xml;

            switch (exportFormat)
            {
                case "icon-pageexcel":
                    XslCompiledTransform xtExcel = new XslCompiledTransform();
                    xtExcel.Load(HttpContext.Current.Server.MapPath("~/Content/ExportTemplate/Excel.xsl"));
                    StringBuilder resultExcelString = new StringBuilder();
                    XmlWriter excelWriter = XmlWriter.Create(resultExcelString);
                    xtExcel.Transform(xmlData, excelWriter);

                    contentResult = new FileContentResult(Encoding.UTF8.GetBytes(resultExcelString.ToString()), "application/vnd.ms-excel");
                    contentResult.FileDownloadName = DateTime.Now.ToString() + ".xls";
                    break;
                case "icon-pagecode":
                    contentResult = new FileContentResult(Encoding.UTF8.GetBytes(xmlData.OuterXml), "application/xml");
                    contentResult.FileDownloadName = DateTime.Now.ToString() + ".xml";
                    break;
                case "icon-pageattach":
                    XslCompiledTransform xtCsv = new XslCompiledTransform();
                    xtCsv.Load(HttpContext.Current.Server.MapPath("~/Content/ExportTemplate/Csv.xsl"));
                    StringBuilder resultCsvString = new StringBuilder();

                    XmlWriterSettings settings = new XmlWriterSettings();
                    settings.OmitXmlDeclaration = true;
                    settings.ConformanceLevel = ConformanceLevel.Fragment;
                    settings.CloseOutput = false;

                    XmlWriter csvWriter = XmlWriter.Create(resultCsvString, settings);
                    xtCsv.Transform(xmlData, csvWriter);

                    contentResult = new FileContentResult(Encoding.UTF8.GetBytes(resultCsvString.ToString()), "application/octet-stream");
                    contentResult.FileDownloadName = DateTime.Now.ToString() + ".csv";
                    break;
                default:
                    break;
            }

            if(contentResult != null)
                contentResult.ExecuteResult(context);
        }
 private FileContentResult GetArticleResources(string type)
 {
     FileContentResult fr = null;
     ReadDataFromRouteDataForImage();
     try
     {
         string fileFullPath = Path.Combine(_adminManager.DataPath, "knowledgebase", "articlesPublished", clientId.ToString(), kbId.ToString(), articleId.ToString()+ type, fileName);
         System.IO.MemoryStream s = _adminManager.ReadFileStream(fileFullPath);
         byte[] bts = new byte[s.Length];
         s.Read(bts, 0, bts.Length);
         string contentType = Mime.FromExtension(Path.GetExtension(fileFullPath));
         fr = new FileContentResult(bts, contentType);
     }
     catch (IOException ex)
     {
         KBCustomException kbCustExp = KBCustomException.ProcessException(ex, KBOp.LoadContent, KBErrorHandler.GetMethodName(), GeneralResources.IOError,
             new KBExceptionData("type", type), new KBExceptionData("kbId", kbId.ToString()), new KBExceptionData("articleId", articleId), new KBExceptionData("clientId", clientId), new KBExceptionData("portalId", portalId),
             new KBExceptionData("fileName", fileName));
         throw kbCustExp;
     }
     catch (Exception ex)
     {
         KBCustomException kbCustExp = KBCustomException.ProcessException(ex, KBOp.LoadContent, KBErrorHandler.GetMethodName(), GeneralResources.GeneralError,
             new KBExceptionData("type", type), new KBExceptionData("kbId", kbId.ToString()), new KBExceptionData("articleId", articleId), new KBExceptionData("clientId", clientId), new KBExceptionData("portalId", portalId),
             new KBExceptionData("fileName", fileName));
         throw kbCustExp;
     }
     return fr;
 }