//[Obsolete("Replace with CachedUrl",true)] //public static HtmlString Url(string p) //{ // throw new InvalidOperationException(); //} public override async System.Threading.Tasks.Task ProcessRequestAsync(HttpContext context) { var Response = context.Response; if (Enabled) { Response.Cache.SetCacheability(HttpCacheability.Public); Response.Cache.SetMaxAge(MaxAge); Response.Cache.SetExpires(DateTime.UtcNow.Add(MaxAge)); } else { Response.Cache.SetCacheability(HttpCacheability.NoCache); Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-10)); } Response.BufferOutput = true; if (CORSOrigins != null) { Response.Headers.Add("Access-Control-Allow-Origin", CORSOrigins); } string FilePath = context.Items["FilePath"] as string; var file = new FileInfo(context.Server.MapPath("/" + FilePath)); if (!file.Exists) { Response.StatusCode = 404; Response.StatusDescription = "Not Found by CachedRoute"; Response.ContentType = "text/plain"; Response.Output.Write("File not found by CachedRoute at " + file.FullName); return; } Response.ContentType = MimeMapping.GetMimeMapping(file.FullName); Response.WriteFile(file.FullName, true); /*using (var fs = file.OpenRead()) * { * await fs.CopyToAsync(Response.OutputStream); * }*/ }
private ActionResult getFileResult(string path, Report report) { var contentType = MimeMapping.GetMimeMapping(path); var result = new FilePathResult(path, contentType); if (contentType != "text/html") { if (report != null) { result.FileDownloadName = Helper.CleanFileName(report.DisplayNameEx + Path.GetExtension(path)); } else { result.FileDownloadName = Path.GetFileName(path); } } return(result); }
public FileResult DownloadFileHoaDon() { var sp = Request.FilePath.Split('/'); if (sp == null) { return(null); } var fileName = sp[sp.Length - 1]; gnSqlNomal gn = new gnSqlNomal(); general gns = new general(); var dicAppSet = gns.ReadAppseting(); //var filepath = System.IO.Path.Combine(Server.MapPath("/Files/"), fileName); var filepath = dicAppSet["hddt_path_downloadfilehoadon"] + fileName; //File z = File(filepath, MimeMapping.GetMimeMapping(filepath), fileName); return(File(filepath, MimeMapping.GetMimeMapping(filepath), fileName)); }
public void Add(RequestFile item) { if (string.IsNullOrEmpty(item.Name)) { throw new ArgumentException("name of file can't be empty", "item"); } if (item.Data == null) { throw new ArgumentException("file can't be empty", "item"); } if (string.IsNullOrEmpty(item.ContentType)) { item.ContentType = MimeMapping.GetMimeMapping(item.Name); } _files.Add(item); }
public FileResult DownloadPDF() { try { String path = Server.MapPath("~/App_Data/MVC_tutorial.pdf"); string fileName = Path.GetFileName(path); String mimeType = MimeMapping.GetMimeMapping(path); byte[] stream = System.IO.File.ReadAllBytes(path); return(File(stream, mimeType, fileName)); //return File("/App_Data/ProASP.NET-MVC-5_Platform.pdf", "application/pdf"); } catch (Exception ex) { throw ex; } }
protected override Task ProcessRequestAsync(HttpContext context) { var task = new Task(() => { try { var file = context.Server.MapPath(context.Request.Url.LocalPath); if (!File.Exists(file)) { return; } string etag; using (var fs = new FileStream(file, FileMode.Open)) { etag = new MD5CryptoServiceProvider().ComputeHash(fs).ToBase64String(); } var ifnonematch = context.Request.Headers[Header.IfNoneMatch]; if (!string.IsNullOrEmpty(ifnonematch) && etag.Equals(ifnonematch)) { context.Response.StatusCode = 304; } else { context.Response.AddHeader(Header.ETag, etag); context.Response.AddHeader(Header.CacheControl, "max-age=630000, public"); context.Response.AddHeader(Header.Vary, Header.AcceptEncoding); context.Response.AppendHeader(Header.Expires, DateTime.Now.Date.AddDays(8).ToString("R")); context.Response.ContentType = MimeMapping.GetMimeMapping(file); if (context.Response.ContentType.StartsWith("text/") || context.Response.ContentType.Equals("application/javascript") || context.Response.ContentType.Equals("application/json")) { context.SetCompression(); } context.Response.WriteFile(file); } } catch (Exception e) { IoC.Resolve <ILogger>().Error("Error in static file handler.", e); } }); task.Start(); return(task); }
public static GoogleDriveResultWithData <GoogleDriveFile> UploadFile(Connection connection, string localFilePath, string fileName = null, string parentFolderId = null, Action <IUploadProgress> progessUpdate = null) { CorrectFolderId(ref parentFolderId); CheckConnectionOrException(connection); if (fileName == null) { fileName = System.IO.Path.GetFileName(localFilePath); } if (string.IsNullOrEmpty(localFilePath)) { throw new ArgumentNullException("localFilePath", "localFilePath cannot be null or empty."); } using (System.IO.FileStream stream = System.IO.File.OpenRead(localFilePath)) try { var fileMetadata = new File() { Name = fileName, MimeType = MimeMapping.GetMimeMapping(fileName), Parents = new List <string> { parentFolderId } }; var request = connection.Service.Files.Create(fileMetadata, stream, MimeMapping.GetMimeMapping(fileName)); request.Fields = "id, name, mimeType, description, webViewLink"; if (progessUpdate != null) { request.ProgressChanged += progessUpdate; } GoogleDriveResultWithData <GoogleDriveFile> result = UploadRequest(request); return(result); } finally { stream.Close(); } }
public static string PostFile(string postImageUrl) { string baseURL = ConfigurationManager.AppSettings["apiBaseURL"].ToString(); //string postImage = System.IO.File.ReadAllText(postImageUrl); string destinationUrl = baseURL + "/FileTransmission/PostFile"; byte[] bytes = System.IO.File.ReadAllBytes(postImageUrl); string fileExtension = Path.GetExtension(postImageUrl); string mimeType = MimeMapping.GetMimeMapping(postImageUrl); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(destinationUrl); request.ContentType = mimeType + "; encoding='utf-8'"; request.ContentLength = bytes.Length; request.Method = "POST"; request.Timeout = Timeout.Infinite; Stream requestStream = request.GetRequestStream(); requestStream.Write(bytes, 0, bytes.Length); requestStream.Close(); HttpWebResponse response; try { response = (HttpWebResponse)request.GetResponse(); if (response.StatusCode == HttpStatusCode.NoContent) { Stream responseStream = response.GetResponseStream(); string responseStr = new StreamReader(responseStream).ReadToEnd(); return(responseStr); } } catch (WebException webex) { WebResponse errResp = webex.Response; using (Stream respStream = errResp.GetResponseStream()) { StreamReader reader = new StreamReader(respStream); string text = reader.ReadToEnd(); } } return(null); }
public void MediaUploadRequest() { HttpResponseMessage response = null; string token = null; var filename = "FileUpload.txt"; var filepath = Configuration.Instance.GetExecutingAssemblyLocation($"\\{filename}"); "Arrange - When I the set the data up" .x(() => { token = Fixture.GetAuthToken(); }); "Act - When I make a Http Request to a restricted email API" .x(() => { using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json")); var url = Configuration.Instance.DefaultUrl + "api/MediaUpload/Upload"; client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); using (var reader = new System.IO.FileStream(filepath, FileMode.Open)) using (var formData = new MultipartFormDataContent()) { // Add token to the Authorization header and make the request var content = new StreamContent(reader); content.Headers.ContentType = new MediaTypeHeaderValue(MimeMapping.GetMimeMapping(filepath)); formData.Add(content, filename, filename); response = client.PostAsync(new Uri(url), formData).Result; } } }); $"Assert - Then the response should be successful" .x(() => { response.Should().NotBeNull(); response.IsSuccessStatusCode.Should().BeTrue(); var result = response.Content.ReadAsStringAsync().Result; //result.Status.Should().Be(responseMessage); }); }
public async Task <FileResult> ExportExcel(string keyword = "") { var list = await _service.GetList(keyword); #region NPOI HSSFWorkbook book = new HSSFWorkbook(); //添加一个sheet ISheet sheet1 = book.CreateSheet("Sheet1"); //给sheet1添加第一行的头部标题 IRow row1 = sheet1.CreateRow(0); row1.CreateCell(0).SetCellValue("序号"); row1.CreateCell(1).SetCellValue("岗位编号"); row1.CreateCell(2).SetCellValue("岗位名称"); row1.CreateCell(3).SetCellValue("归属公司"); row1.CreateCell(4).SetCellValue("有效状态"); row1.CreateCell(5).SetCellValue("创建时间"); row1.CreateCell(6).SetCellValue("备注"); //将数据逐步写入sheet1各个行 for (int i = 0; i < list.Count; i++) { IRow rowtemp = sheet1.CreateRow(i + 1); rowtemp.CreateCell(0).SetCellValue((i + 1).ToString()); rowtemp.CreateCell(1).SetCellValue(list[i].F_EnCode != null ? list[i].F_EnCode.ToString() : ""); rowtemp.CreateCell(2).SetCellValue(list[i].F_FullName != null ? list[i].F_FullName.ToString() : ""); var set = await _setService.GetForm(_service.currentuser.CompanyId); rowtemp.CreateCell(3).SetCellValue(set != null ? set.F_CompanyName : ""); rowtemp.CreateCell(4).SetCellValue(list[i].F_EnabledMark == true ? "有效" : "无效"); rowtemp.CreateCell(5).SetCellValue(list[i].F_CreatorTime != null ? list[i].F_CreatorTime.ToString() : ""); rowtemp.CreateCell(6).SetCellValue(list[i].F_Description != null ? list[i].F_Description.ToString() : ""); } System.IO.MemoryStream ms = new System.IO.MemoryStream(); book.Write(ms); ms.Seek(0, SeekOrigin.Begin); string filename = "岗位信息" + DateTime.Now.ToString("yyyyMMdd_HHmmss") + ".xls"; var contentType = MimeMapping.GetMimeMapping(filename); #endregion return(File(ms, contentType, filename)); }
//...POST working fine private void ClientCall() { try { var client = new HttpClient(); var fileInfo = new FileInfo("D:\\index.html"); var fileContent = new StreamContent(fileInfo.OpenRead()); fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { Name = "\"file\"", FileName = "\"" + fileInfo.Name + "\"" }; fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse(MimeMapping.GetMimeMapping(fileInfo.Name)); // This is the postdata var postData = new List <KeyValuePair <string, string> >(); postData.Add(new KeyValuePair <string, string>("file", fileContent.ToString())); postData.Add(new KeyValuePair <string, string>("style", "Basic")); postData.Add(new KeyValuePair <string, string>("Client ", "Springer")); postData.Add(new KeyValuePair <string, string>("style", "Basic")); postData.Add(new KeyValuePair <string, string>("Language ", "En")); postData.Add(new KeyValuePair <string, string>("Format", "color")); // HttpContent content = new FormUrlEncodedContent(postData); MultipartFormDataContent form = new MultipartFormDataContent(); form.Add(new StringContent("Basic"), "style"); form.Add(new StringContent("Springer"), "Client"); form.Add(new StringContent("Basic"), "style"); form.Add(new StringContent("En"), "Language"); form.Add(new StringContent("color"), "Format"); client.PostAsync("http://192.168.84.140/cgi-enabled/Reflexica.cgi", form).ContinueWith( (postTask) => { var res = postTask.Result.Content.ReadAsStringAsync(); postTask.Result.EnsureSuccessStatusCode(); }); } catch (Exception ex) { throw new Exception(ex.Message); } }
public FileModel GetPdfFromHtmlString(string html, string fileName, PdfPageSize pageSize = PdfPageSize.A4, PdfPageOrientation orientation = PdfPageOrientation.Portrait) { var result = new FileModel() { FileName = fileName, Mime = MimeMapping.GetMimeMapping(fileName) }; HttpClient client = new HttpClient(); var req = HttpContext.Current.Request; //string url = req.Url.Scheme + "://" + req.Url.Authority + req.ApplicationPath.TrimEnd('/') + actionUrl; ////string url = actionUrl; //File.WriteAllText("C:\\Log\\pdf_serive" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".txt", url); HtmlToPdf converter = new HtmlToPdf(); // set converter options converter.Options.PdfPageSize = pageSize; converter.Options.PdfPageOrientation = orientation; converter.Options.MaxPageLoadTime = 200; converter.Options.MarginTop = 5; System.Drawing.Font font = new System.Drawing.Font("Arial", 1); //PdfTextSection footer = new PdfTextSection(0, 10, "Dokumen ini adalah surat perintah bayar yang sah walaupun tanpa tanda tangan pejabat ybs, dicetak dari system User Purchase PDSI", font); //converter.Footer.Add(footer); // create a new pdf document converting an url PdfDocument doc = converter.ConvertHtmlString(html); // save pdf document var byteresult = doc.Save(); result.Bytes = byteresult; // close pdf document doc.Close(); return(result); }
public ActionResult PreviewDigitalDownload(int?id) { if (!id.HasValue) { return(HttpBadRequest("ProductId = null")); } StoreFront storeFront = CurrentStoreFrontOrThrow; Product product = storeFront.Products.Where(p => p.ProductId == id.Value).SingleOrDefault(); if (product == null) { AddUserMessage("Product not found", "Sorry, the Product you are trying to view cannot be found. Product Id: [" + id.Value + "] for Store Front '" + storeFront.CurrentConfig().Name.ToHtml() + "' [" + storeFront.StoreFrontId + "]", UserMessageType.Danger); if (storeFront.Authorization_IsAuthorized(CurrentUserProfileOrThrow, GStoreAction.Products_Manager)) { return(RedirectToAction("Manager")); } return(RedirectToAction("Index", "CatalogAdmin")); } if (string.IsNullOrEmpty(product.DigitalDownloadFileName)) { string errorMessage = "There is no Digital Download File linked to this product"; return(View("DigitalDownload_Error", new DigitalDownloadFileError(product, errorMessage))); } string filePath = product.DigitalDownloadFilePath(Request.ApplicationPath, RouteData, Server); if (string.IsNullOrEmpty(filePath)) { string errorMessage = "Digital Download File '" + product.DigitalDownloadFileName + "' could not be found in store front, client, or server digital download files.\n" + "Be sure file exists, and it is located in the file system 'DigitalDownload/Products/[file name]"; return(View("DigitalDownload_Error", new DigitalDownloadFileError(product, errorMessage))); } string mimeType = MimeMapping.GetMimeMapping(filePath); return(new FilePathResult(filePath, mimeType) { FileDownloadName = product.DigitalDownloadFileName }); }
public ActionResult Edit([Bind(Include = "ProductID,ProductName,SupplierID,CategoryID,QuantityPerUnit,UnitPrice,UnitsInStock,UnitsOnOrder,ReorderLevel,Discontinued,Photo")] Product product) { if (Session["ConnectedUser"] != null) { //var prodID = db.Products.Where(p => p.CategoryID == product.CategoryID); //string tempProd = (string)prodID.ToList()[0].Photo; //prodID = null; //ViewBag.ImagePath = ImagePath; if (ModelState.IsValid) { if (Request.Files.Count > 0) { var file = Request.Files[0]; if (MimeMapping.GetMimeMapping(file.FileName) == "image/jpg" || MimeMapping.GetMimeMapping(file.FileName) == "image/png" || MimeMapping.GetMimeMapping(file.FileName) == "image/jpeg") { var fileName = Path.GetFileName(file.FileName); var path = Path.Combine(Server.MapPath("~/Content/Photos/"), fileName); file.SaveAs(path); product.Photo = fileName; } else { ViewBag.PhotoValidation = "fail"; } } //else if (tempProd != null) //{ // product.Photo = tempProd; //} db.Entry(product).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Index")); } ViewBag.CategoryID = new SelectList(db.Categories, "CategoryID", "CategoryName", product.CategoryID); ViewBag.SupplierID = new SelectList(db.Suppliers, "SupplierID", "CompanyName", product.SupplierID); return(View(product)); } else { return(RedirectToAction("Login", "Connect")); } }
public static MimePart ToMimePart(this MailAttachment attachment, bool loadAttachments) { var retVal = new MimePart(); var s3Key = MailStoragePathCombiner.GerStoredFilePath(attachment); var fileName = attachment.fileName ?? Path.GetFileName(s3Key); if (loadAttachments) { var byteArray = attachment.data; if (byteArray == null || byteArray.Length == 0) { using (var stream = StorageManager.GetDataStoreForAttachments(attachment.tenant).GetReadStream(s3Key)) { byteArray = stream.ReadToEnd(); } } retVal = new MimePart(byteArray, fileName); if (!string.IsNullOrEmpty(attachment.contentId)) { retVal.ContentId = attachment.contentId; } } else { var conentType = MimeMapping.GetMimeMapping(s3Key); retVal.ContentType = new ContentType { Type = conentType }; retVal.Filename = fileName; if (attachment.contentId != null) { retVal.ContentId = attachment.contentId; } retVal.TextContent = ""; } return(retVal); }
public ActionResult Create([Bind(Include = "ProductID,ProductName,SupplierID,CategoryID,QuantityPerUnit,UnitPrice,UnitsInStock,UnitsOnOrder,ReorderLevel,Discontinued,Photo")] Product product) { if (LoginController.isLoggedIn()) { if (ModelState.IsValid) { if (Request.Files.Count > 0) { var file = Request.Files[0]; if (file != null && file.ContentLength > 0) { if (MimeMapping.GetMimeMapping(file.FileName).Equals("image/png") || MimeMapping.GetMimeMapping(file.FileName).Equals("image/jpeg")) { var fileName = Path.GetFileNameWithoutExtension(file.FileName); var fileExtension = Path.GetExtension(file.FileName); var path = Path.Combine(Server.MapPath("~/Content/Images/"), fileName + fileExtension); file.SaveAs(path); product.Photo = fileName + fileExtension; db.Products.Add(product); db.SaveChanges(); return(RedirectToAction("Index")); } else { TempData["Error"] = "The file you're trying to upload isn't a 'png' or a 'jpg'!"; } } else { TempData["Error"] = "You didn't select any file to upload!"; } } return(RedirectToAction("Create")); } ViewBag.CategoryID = new SelectList(db.Categories, "CategoryID", "CategoryName", product.CategoryID); ViewBag.SupplierID = new SelectList(db.Suppliers, "SupplierID", "CompanyName", product.SupplierID); return(View(product)); } return(RedirectToAction("Login", "Login")); }
public FileUploadResult ProcessUpload(HttpContext context) { if (!VoipNumberData.Allowed || !CRMSecurity.IsAdmin) { throw CRMSecurity.CreateSecurityException(); } if (context.Request.Files.Count == 0) { return(Error("No files.")); } var file = context.Request.Files[0]; if (file.ContentLength <= 0 || file.ContentLength > maxFileSize * 1024L * 1024L) { return(Error(StudioResources.Resource.FileSizeMaxExceed)); } try { var path = file.FileName; AudioType audioType; if (Enum.TryParse(context.Request["audioType"], true, out audioType)) { path = Path.Combine(audioType.ToString().ToLower(), path); } var uri = Global.GetStore().Save("voip", path, file.InputStream, MimeMapping.GetMimeMapping(file.FileName), ContentDispositionUtil.GetHeaderValue(file.FileName, withoutBase: true)); return(Success(new VoipUpload { AudioType = audioType, Name = file.FileName, Path = CommonLinkUtility.GetFullAbsolutePath(uri.ToString()) })); } catch (Exception error) { return(Error(error.Message)); } }
/// <inheritdoc /> public override async Task ProcessRequestAsync(HttpContext ctx) { string cachePath = ctx.Items[WebRSizeModule.CachePathKey] as string; var s = ctx.Items[WebRSizeModule.ProcessImageSettingsKey] as ProcessImageSettings; var tsource = default(TaskCompletionSource <ArraySegment <byte> >); var task = tdic.GetOrAdd(cachePath, _ => { tsource = new TaskCompletionSource <ArraySegment <byte> >(TaskCreationOptions.RunContinuationsAsynchronously); return(tsource.Task); }); if (tsource?.Task == task) { ctx.Trace.Write(nameof(WebRSize), nameof(MagicImageProcessor.ProcessImage) + " Begin"); await process(tsource, ctx.Request.Path, cachePath, s); ctx.Trace.Write(nameof(WebRSize), nameof(MagicImageProcessor.ProcessImage) + " End"); } var img = await task; var res = ctx.Response; if (!res.IsClientConnected) { return; } try { res.BufferOutput = false; res.ContentType = MimeMapping.GetMimeMapping(Path.GetFileName(cachePath)); res.AddHeader("Content-Length", img.Count.ToString()); await res.OutputStream.WriteAsync(img.Array, img.Offset, img.Count); await res.OutputStream.FlushAsync(); } catch (HttpException ex) when(new StackTrace(ex).GetFrame(0)?.GetMethod().Name == "RaiseCommunicationError") { // no problem here. client just disconnected before transmission completed. } }
/// <summary> /// File upload to the Google Drive in existing folder with new file name /// </summary> /// <param name="file"></param> /// <param name="folderId"></param> /// <param name="newFileName"></param> public void UplaodFileOnDriveInFolder(HttpPostedFileBase file, string newFileName, string folderName) { if (file != null && file.ContentLength > 0) { //convert from folder name to it Id string folderId = this.folderNameToFolderId(folderName); //if folder not founded- create one and enter the file to the new folder if (folderId == null) { this.CreateFolder(folderName); folderId = this.folderNameToFolderId(folderName); } //create service DriveService service = GetService(); //get file path string path = Path.Combine(HttpContext.Current.Server.MapPath("~/GoogleDriveFiles"), Path.GetFileName(file.FileName)); file.SaveAs(path); //create file metadata var FileMetaData = new Google.Apis.Drive.v3.Data.File() { Name = newFileName + Path.GetExtension(file.FileName), MimeType = MimeMapping.GetMimeMapping(path), //id of parent folder Parents = new List <string> { folderId } }; Google.Apis.Drive.v3.FilesResource.CreateMediaUpload request; //create stream and upload using (var stream = new System.IO.FileStream(path, System.IO.FileMode.Open)) { request = service.Files.Create(FileMetaData, stream, FileMetaData.MimeType); request.Fields = "id"; request.Upload(); } var file1 = request.ResponseBody; } }
void Attach(MailMessage mail, EmailAttachmentDetails[] attachments) { if (attachments == null) { return; } foreach (var file in attachments) { Attachment attachment = new Attachment(file.File, MimeMapping.GetMimeMapping(file.FileName)); ContentDisposition disposition = attachment.ContentDisposition; disposition.CreationDate = DateTime.UtcNow; disposition.ModificationDate = DateTime.UtcNow; disposition.ReadDate = DateTime.UtcNow; disposition.FileName = file.FileName; disposition.Size = file.File.Length; disposition.DispositionType = DispositionTypeNames.Attachment; mail.Attachments.Add(attachment); } }
public ActionResult Media(int id) { if (Session["userType"] != null) { var w = db.Videos.Find(id); //Response.Write(w.path.Substring(61)); // s = x.path.Substring(61); string fn = Server.MapPath("~/Content/Videoes/" + w.path.Substring(68)); //I tried to load a local video and convert to stream, you need to replace the code to get the video from your data base. // string fn = Server.MapPath("~/Content/Files/small.mp4"); var memoryStream = new MemoryStream(System.IO.File.ReadAllBytes(fn)); return(new FileStreamResult(memoryStream, MimeMapping.GetMimeMapping(System.IO.Path.GetFileName(fn)))); } else { return(RedirectToAction("Errorpage", "Courses")); } }
private static RequestFileInfo GetAsAttachment(MIME_Entity entity) { var attachment = new RequestFileInfo { Body = ((MIME_b_SinglepartBase)entity.Body).Data }; if (!string.IsNullOrEmpty(entity.ContentDisposition.Param_FileName)) { attachment.Name = entity.ContentDisposition.Param_FileName; } else if (!string.IsNullOrEmpty(entity.ContentType.Param_Name)) { attachment.Name = entity.ContentType.Param_Name; } attachment.ContentType = MimeMapping.GetMimeMapping(attachment.Name); return(attachment); }
public Object DownloadPublicImages(string filename) { try { var fileFolder = HttpContext.Current.Server.MapPath("~/Files/public"); var filePath = Path.Combine(fileFolder, filename); HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK); var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read); result.Content = new StreamContent(stream); result.Content.Headers.ContentType = new MediaTypeHeaderValue(MimeMapping.GetMimeMapping(filename)); return(result); } catch (Exception) { return(new HttpResponseMessage(HttpStatusCode.ServiceUnavailable)); } }
private FileStreamResult GetFileStreamResult(string url) { IFileSystem fs = FileSystemProviderManager.Current.GetUnderlyingFileSystemProvider("media"); if (!fs.FileExists(url)) { throw new FileNotFoundException(url); } string fileName = fs.GetFileName(url); string mimeType = MimeMapping.GetMimeMapping(fs.GetFileName(url)); FileStreamResult result = new FileStreamResult(fs.OpenFile(url), mimeType); if (mimeType.StartsWith("application/")) { result.FileDownloadName = fileName; } return(result); }
public FileResult Download(long quotId, string fileName, string actualFileName) { using (var client = new WebClient()) { try { var content = client.DownloadData(AwsS3Bucket.AccessPath() + "/resources/vendor-owner-pmb/" + quotId + "/pmbFiles/" + fileName); using (var stream = new MemoryStream(content)) { byte[] buff = stream.ToArray(); return(File(buff, MimeMapping.GetMimeMapping(fileName), actualFileName)); } } catch (Exception ex) { TempData["Message"] = AppLogic.setMessage(-1, "Error! " + ex.Message); } } return(null); }
// GET: Download public ActionResult Index(int idIngreso) { BL.BLReportes blReportes = new BL.BLReportes(); GenericResponse <ArchivoIngresoResponse> response = blReportes.ObtenerArchivoIngreso(idIngreso); string filename = response.Result.Nombre; byte[] filedata = response.Result.Data; string contentType = MimeMapping.GetMimeMapping(response.Result.Nombre); var cd = new System.Net.Mime.ContentDisposition { FileName = filename, Inline = true, }; Response.AppendHeader("Content-Disposition", cd.ToString()); return(File(filedata, contentType)); }
/// <summary> /// Display file from file system. /// </summary> /// <param name="filePath"></param> /// <returns></returns> public ActionResult Show(string filePath) { // Maybe perform authorization before serving file const string basePath = @"D:\temp\Uploads"; var fileName = Path.GetFileName(filePath); if (fileName == null) { return(HttpNotFound("File Not Found")); } // Get MIME type var mimeType = MimeMapping.GetMimeMapping(fileName); var destinationPath = Path.Combine(basePath, fileName); return(File(destinationPath, mimeType, fileName)); }
public HttpResponseMessage GetConvertedFile(string convertedAudioFilename) { if (convertedAudioFilename == string.Empty) { return(new HttpResponseMessage(HttpStatusCode.BadRequest)); } string path = HttpContext.Current.Request.MapPath(Path.Combine(HttpContext.Current.Request.ApplicationPath, "App_Data/" + convertedAudioFilename)); var result = new HttpResponseMessage(HttpStatusCode.OK); var stream = new FileStream(path, FileMode.Open); result.Content = new StreamContent(stream); result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = convertedAudioFilename }; result.Content.Headers.ContentType = new MediaTypeHeaderValue(MimeMapping.GetMimeMapping(path)); return(result); }
public ActionResult DownloadPreinvocationFile() { string filePathName = Server.MapPath("~/FileStorage/Downloads/preinvocation.pdf"); if (System.IO.File.Exists(filePathName)) { byte[] filedata = System.IO.File.ReadAllBytes(filePathName); string contentType = MimeMapping.GetMimeMapping(filePathName); var cd = new System.Net.Mime.ContentDisposition { FileName = Path.GetFileName("~/FileStorage/Downloads/preinvocation.pdf"), Inline = true, }; Response.AppendHeader("Content-Disposition", cd.ToString()); return(File(filedata, contentType)); } return(HttpNotFound()); }
public HttpResponseMessage GetFile(string fileName, [FromUri(Name = "access_token")] Guid tokenId) { var fullFileName = GetFullPath(fileName); Validation(tokenId, fullFileName); var stream = new FileStream(fullFileName, FileMode.Open); var result = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StreamContent(stream) }; result.Content.Headers.ContentType = new MediaTypeHeaderValue(MimeMapping.GetMimeMapping(fileName)); result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = fileName }; return(result); }