public async Task <FileManagerSaveFileResponse> SaveFileAsync(string path, string filename, byte[] data, bool overwriteExisting, string filter, CancellationToken token) { if (DirectMode) { return(await FileManager.SaveFile.RunAsync(new FileManagerSaveFileRequest { Path = path, FileName = filename, Data = data, OverwriteExisting = overwriteExisting, Filter = filter })); } else { var ar = await ApiClient.SendAsync("/filemanager/file/save", filename, data, new Dictionary <string, object> { { "path", GetPath(path) }, { "overwrite", overwriteExisting } }, Initializer, MimeHelper.GetMimeType(filename), token); var response = FinalizeResponse <FileManagerSaveFileResponse>(ar); return(response); } }
public async Task <FileManagerSaveFilesResponse> SaveFilesAsync(string path, HttpFileCollectionBase files, bool overwriteExisting, string filter, CancellationToken token) { if (DirectMode) { return(await FileManager.SaveFilesAsync(path, files, overwriteExisting, filter, token)); } else { var _files = new List <SendData>(); if (files != null) { for (var i = 0; i < files.Count; i++) { var file = files[i]; var data = await file.GetBytesAsync(8192, token); _files.Add(new SendData { FileName = file.FileName, Data = data, ContentType = MimeHelper.GetMimeType(file.FileName) }); } } var ar = await ApiClient.SendAsync("/filemanager/file/save", _files.ToArray(), new Dictionary <string, object> { { "path", GetPath(path) }, { "overwrite", overwriteExisting } }, Initializer, token); var response = FinalizeResponse <FileManagerSaveFilesResponse>(ar); return(response); } }
public AudioFileTag(string source) { using (TagLib.File file = TagLib.File.Create(source)) { this.AlbumArtists = file.Tag.JoinedAlbumArtists; this.Artists = file.Tag.JoinedPerformers; this.Album = file.Tag.Album; this.Title = file.Tag.Title; this.Track = (int)file.Tag.Track; this.TrackCount = (int)file.Tag.TrackCount; this.Disc = (int)file.Tag.Disc; this.DiscCount = (int)file.Tag.DiscCount; this.Year = (int)file.Tag.Year; this.Genre = file.Tag.JoinedGenres; List <AudioFileImage> images = new List <AudioFileImage>(); foreach (TagLib.IPicture picture in file.Tag.Pictures) { byte[] data = new byte[picture.Data.Count]; picture.Data.CopyTo(data, 0); images.Add(new AudioFileImage() { Data = data, MimeType = picture.MimeType, Description = picture.Description, Type = (ImageType)picture.Type, Extension = MimeHelper.GetExtensionForMimeType(picture.MimeType) }); } } }
public async Task <ResultContract <byte[]> > GetBreakpoint(string name, long startPos, long endPos) { var result = new ResultContract <byte[]>() { Code = 0, Msg = "获取成功" }; //先获取文件大小 try { var newName = Guid.NewGuid() + "-" + name; long fileLength = AliyunOSSHepler.GetInstance().GetFileLength(name); string mimeType = MimeHelper.GetMimeMapping(name); AliyunOSSHepler.GetInstance().Download(downloadPath, startPos, endPos, name, newName); var file = new byte[endPos - startPos]; using (var fileStream = new FileStream(downloadPath + newName, FileMode.Open)) { fileStream.Read(file, 0, file.Length); } System.IO.File.Delete(downloadPath + newName); result.Data = file; } catch (Exception e) { result.Msg = "获取失败"; result.Code = -1; } return(result); }
public async Task <IActionResult> BreakpointDownload(string name) { //先获取文件大小 var newName = Guid.NewGuid() + "-" + name; long fileLength = AliyunOSSHepler.GetInstance().GetFileLength(name); string mimeType = MimeHelper.GetMimeMapping(name); int partSize = 1024 * 1024 * 10; var partCount = AliyunOSSHepler.GetInstance().CalPartCount(fileLength, partSize); for (var i = 0; i < partCount; i++) { var startPos = partSize * i; var endPos = partSize * i + (partSize < (fileLength - startPos) ? partSize : (fileLength - startPos)) - 1; AliyunOSSHepler.GetInstance().Download(downloadPath, startPos, endPos, name, newName); } var file = new byte[fileLength]; using (var fileStream = new FileStream(downloadPath + newName, FileMode.Open)) { fileStream.Read(file, 0, file.Length); } System.IO.File.Delete(downloadPath + newName); return(File(file, mimeType, name)); }
public void GetMimeFromFileName_OverrideUserType_ReturnsOverrideValue() { const string mime = "application/x-ncontrib-testing"; MimeHelper.UserTypes.Add(".bmp", mime); Assert.AreEqual(mime, MimeHelper.GetMimeFromFileName("image.bmp")); }
private static bool AcceptsImages(string[] contentTypes) { bool acceptsPng = false, acceptsJpeg = false, acceptsGif = false; foreach (string contentType in contentTypes) { IDictionary values = MimeHelper.ParseContentType(contentType, true); string mainType = values[""] as string; switch (mainType) { case "*/*": case "image/*": return(true); case "image/png": acceptsPng = true; break; case "image/gif": acceptsGif = true; break; case "image/jpeg": acceptsJpeg = true; break; } } return(acceptsPng && acceptsJpeg && acceptsGif); }
private static bool AcceptsEntry(string contentType) { IDictionary values = MimeHelper.ParseContentType(contentType, true); string mainType = values[""] as string; switch (mainType) { case "entry": case "*/*": case "application/*": return(true); case "application/atom+xml": string subType = values["type"] as string; if (subType != null) { subType = subType.Trim().ToUpperInvariant(); } if (subType == "ENTRY") { return(true); } else { return(false); } default: return(false); } }
/// <summary> /// /// </summary> /// <param name="entryEl"></param> /// <param name="nsMgr"></param> /// <param name="rel"></param> /// <param name="contentType">e.g. application/atom+xml</param> /// <param name="contentSubType">e.g. "entry"</param> /// <param name="baseUri"></param> /// <returns></returns> public static string GetLink(IXmlNode entryEl, XmlNamespaceManager nsMgr, string rel, string contentType, string contentSubType, Uri baseUri) { Debug.Assert(contentSubType == null || contentType != null, "contentSubType is only used if contentType is also provided"); string xpath = string.Format(CultureInfo.InvariantCulture, @"atom:link[@rel='{0}']", rel); foreach (XmlElement link in entryEl.SelectNodesNS(xpath, nsMgr.ToNSMethodFormat())) { if (contentType != null) { string mimeType = link.GetAttribute("type"); if (mimeType == null || mimeType == "") { continue; } IDictionary mimeData = MimeHelper.ParseContentType(mimeType, true); if (contentType != (string)mimeData[""]) { continue; } if (contentSubType != null && contentSubType != (string)mimeData["type"]) { continue; } } return(XmlHelper.GetUrl(link, "@href", baseUri)); } return(""); }
public EArticlesController( MimeHelper mimeHelper, HtmlSanitizer htmlSanitizer, ILogger <EArticlesController> logger, SignInManager <IdentityUser> signInManager, X_DOVEHelper x_DOVEHelper, RoleManager <IdentityRole> roleManager, IEmailSender emailSender, UserManager <IdentityUser> userManager, ApplicationDbContext context, IHostingEnvironment hostingEnv, IStringLocalizer <Program> localizer) { _htmlSanitizer = htmlSanitizer; _hostingEnv = hostingEnv; _localizer = localizer; _context = context; _userManager = userManager; _emailSender = emailSender; _roleManager = roleManager; _x_DOVEHelper = x_DOVEHelper; _signInManager = signInManager; _mimeHelper = mimeHelper; _xUserFileHelper = new XUserFileHelper(); // _eArticleCategoryFilePath = _hostingEnv.ContentRootPath + $"/Data/LAppDoc/earticle_category.csv"; _unicode2StringRegex = new Regex(@"\\u([0-9A-F]{4})", RegexOptions.IgnoreCase | RegexOptions.Compiled); }
public ActionResult DownloadAttachment(int attachmentId, bool?needsDownload, int?width, int?height) { //TODO: security here var attContentInfo = SchoolLocator.AttachementService.GetAttachmentContent(attachmentId); if (attContentInfo == null) { Response.StatusCode = 404; Response.StatusDescription = HttpWorkerRequest.GetStatusDescription(Response.StatusCode); return(null); } var attName = attContentInfo.Attachment.Name; var content = attContentInfo.Content; var contentTypeName = MimeHelper.GetContentTypeByName(attName); if (MimeHelper.GetTypeByName(attName) == MimeHelper.AttachmenType.Picture && width.HasValue && height.HasValue) { content = ImageUtils.Scale(content, width.Value, height.Value); } if (needsDownload.HasValue && !needsDownload.Value) { Response.AddHeader(CONTENT_DISPOSITION, string.Format(HEADER_FORMAT, attName)); return(File(content, contentTypeName)); } return(File(content, contentTypeName, attName)); }
public ActionResult DownloadHealthFormDocument(int studentId, int healthFormId) { var file = SchoolLocator.StudentService.DownloadStudentHealthFormDocument(studentId, healthFormId); Response.AddHeader(CONTENT_DISPOSITION, string.Format(HEADER_FORMAT, "StudentHealthForm.pdf")); return(File(file, MimeHelper.GetContentTypeByExtension("pdf"))); }
void IAddItemScanTask.AssignScanWithRegistryItem(string fileName, int ownerID, int registryID, int itemNumber, string documentName, string documentDescription, string elementDescription, bool isMain, bool isRF) { IItemStorage storage = ItemStorageFactory.Create(); TypMime mimeType = MimeHelper.PobierzTypDlaRozszerzenia(Path.GetExtension(fileName)); Guid scanGuid = Guid.Empty; using (FileStream fs = File.OpenRead(fileName)) { scanGuid = storage.Save(fs); } XPathDocument xpd = new XPathDocument(File.OpenRead(Path.GetDirectoryName(fileName) + "\\" + Path.GetFileNameWithoutExtension(fileName) + ".xml")); XPathNavigator xpn = xpd.CreateNavigator(); Metadata md = new Metadata(); md.Add("dataPobrania", xpn.SelectSingleNode("/dokument/dataPobrania").Value); md.Add("nazwaPlikuSkanu", xpn.SelectSingleNode("/dokument/nazwaPlikuDokumentu").Value); md.Add("liczbaStron", xpn.SelectSingleNode("/dokument/liczbaStron").Value); md.Add("lokalizacjaSkanu", xpn.SelectSingleNode("/dokument/pochodzenie/lokalizacja").Value); md.Add("urzadzenie", xpn.SelectSingleNode("/dokument/pochodzenie/urzadzenie").Value); md.Add("rodzajSkanu", xpn.SelectSingleNode("/dokument/pochodzenie/rodzaj").Value); md.Add("zrodloSkanu", xpn.SelectSingleNode("/dokument/pochodzenie/zrodlo").Value); rdao.AddNewScan(ownerID, registryID, itemNumber, documentName, documentDescription, scanGuid, Path.GetFileName(fileName), elementDescription, mimeType.Nazwa, isMain, mimeType.Browsable, md.GetXml(), isRF); }
private static async Task AddFileAsync(MemoryStream postDataStream, string boundary, string filePath, string contentType, CancellationToken token) { //adding file data var fileInfo = new FileInfo(filePath); var _contentType = string.IsNullOrEmpty(contentType) ? MimeHelper.GetMimeType(filePath) : contentType; var header = $"--{boundary}{Environment.NewLine}Content-Disposition: form-data; name=\"{fileInfo.Name}\"; filename=\"{fileInfo.FullName}\"{Environment.NewLine}Content-Type: {_contentType}{Environment.NewLine}{Environment.NewLine}"; var headerBytes = Encoding.UTF8.GetBytes(header); postDataStream.Write(headerBytes, 0, headerBytes.Length); using (var fileStream = fileInfo.OpenRead()) { var buffer = new byte[16384]; // 16KB buffer int bytesRead = 0; while ((bytesRead = await fileStream.ReadAsync(buffer, 0, buffer.Length, token)) != 0) { await postDataStream.WriteAsync(buffer, 0, bytesRead, token); } fileStream.Close(); } }
// http://support.microsoft.com/kb/812406/en-us/ private static void streamFileToBrowser( HttpResponse response, FileInfo file, string fileName) { Stream iStream = null; try { // Open the file. iStream = new FileStream(file.FullName, FileMode.Open, FileAccess.Read, FileShare.Read); // Total bytes to read: var dataToRead = iStream.Length; response.Cache.SetExpires(DateTime.Now - TimeSpan.FromDays(1000)); response.ContentType = MimeHelper.MapFileExtensionToMimeType(file.Extension); //@"application/octet-stream"; response.AddHeader(@"Content-Disposition", @"attachment; filename=" + fileName); response.AddHeader( @"Content-Length", string.Format( @"{0}", file.Length)); // Read the bytes. while (dataToRead > 0) { // Verify that the client is connected. if (response.IsClientConnected) { // Read the data in buffer. var buffer = new byte[10000]; var length = iStream.Read(buffer, 0, 10000); // Write the data to the current output stream. response.OutputStream.Write(buffer, 0, length); // Flush the data to the HTML output. response.Flush(); dataToRead = dataToRead - length; } else { //prevent infinite loop if user disconnects dataToRead = -1; } } } finally { if (iStream != null) { iStream.Close(); iStream.Dispose(); } response.Close(); } }
public async Task <IActionResult> FileAsync(FullPath path, bool download) { IActionResult result; if (path.IsDirectory) { return(new ForbidResult()); } if (!await path.File.ExistsAsync) { return(new NotFoundResult()); } if (path.RootVolume.IsShowOnly) { return(new ForbidResult()); } string contentType = download ? "application/octet-stream" : MimeHelper.GetMimeType(path.File.Extension); result = new PhysicalFileResult(path.File.FullName, contentType); return(await Task.FromResult(result)); }
public async Task <ConnectorResult> FileAsync(FullPath path, bool download) { FileContent result; if (path.IsDirectory) { return(new ConnectorResult("errNotFile")); } if (!await path.File.ExistsAsync) { return(new ConnectorResult("errFileNotFound")); } if (path.RootVolume.IsShowOnly) { return(new ConnectorResult("errPerm")); } result = new FileContent { FileName = path.File.FullName, Length = await path.File.LengthAsync, ContentStream = File.OpenRead(path.File.FullName), ContentType = download ? "application/octet-stream" : MimeHelper.GetMimeType(path.File.Extension) }; return(new ConnectorResult(result)); }
public HttpWebRequest Create(string uri) { // TODO: choose rational timeout values HttpWebRequest request = HttpRequestHelper.CreateHttpWebRequest(uri, false); _parent.CreateAuthorizationFilter().Invoke(request); request.ContentType = MimeHelper.GetContentType(Path.GetExtension(_filename)); try { request.Headers.Add("Slug", Path.GetFileNameWithoutExtension(_filename)); } catch (ArgumentException) { request.Headers.Add("Slug", "Image"); } request.Method = _method; using (Stream s = request.GetRequestStream()) { using (Stream inS = new FileStream(_filename, FileMode.Open, FileAccess.Read, FileShare.Read)) { StreamHelper.Transfer(inS, s); } } return(request); }
public async Task <ImageWithMimeType> GenerateThumbnailAsync() { string name = File.FullName; for (int i = name.Length - 1; i >= 0; i--) { if (name[i] == '_') { name = name.Substring(0, i); break; } } string fullPath = $"{name}{File.Extension}"; if (RootVolume.ThumbnailDirectory != null) { IFile thumbFile; if (File.FullName.StartsWith(RootVolume.ThumbnailDirectory)) { thumbFile = File; } else { thumbFile = File.Open($"{RootVolume.ThumbnailDirectory}{RootVolume.DirectorySeparatorChar}{RelativePath}"); } if (!await thumbFile.ExistsAsync) { var thumbDir = thumbFile.Directory; if (!await thumbDir.ExistsAsync) { await thumbDir.CreateAsync(); thumbDir.Attributes = FileAttributes.Hidden; } using (var original = await File.Open(fullPath).OpenReadAsync()) { var thumb = RootVolume.PictureEditor.GenerateThumbnail(original, RootVolume.ThumbnailSize, true); await thumbFile.PutAsync(thumb.ImageStream); thumb.ImageStream.Position = 0; return(thumb); } } else { string mimeType = MimeHelper.GetMimeType(RootVolume.PictureEditor.ConvertThumbnailExtension(thumbFile.Extension)); return(new ImageWithMimeType(mimeType, await thumbFile.OpenReadAsync())); } } else { using (var original = await File.Open(fullPath).OpenReadAsync()) { return(RootVolume.PictureEditor.GenerateThumbnail(original, RootVolume.ThumbnailSize, true)); } } }
private void AddFile(string fileName, ImageType type) { byte[] data; try { data = File.ReadAllBytes(fileName); } catch { Dialogs.Error("Unable to read file!"); this.comboAddItem.SelectedIndex = 0; return; } Image image = new Image() { Type = type, Extension = Path.GetExtension(fileName), MimeType = MimeHelper.GetMimeTypeForExtension(Path.GetExtension(fileName)) }; if (this.AddImage(image, data)) { this.Release.Images.Add(image); } }
public async Task <IActionResult> FileAsync(FullPath path, bool download) { // Check if path is directory if (path.IsDirectory) { return(new ForbidResult()); } // Check if path exists if (!await AzureStorageAPI.FileExistsAsync(path.File.FullName)) { return(new NotFoundResult()); } // Check if access is allowed if (path.RootVolume.IsShowOnly) { return(new ForbidResult()); } string contentType = download ? "application/octet-stream" : MimeHelper.GetMimeType(path.File.Extension); var stream = new MemoryStream(); await AzureStorageAPI.GetAsync(path.File.FullName, stream); stream.Position = 0; return(new FileStreamResult(stream, contentType)); }
public void Should_get_the_user_mime_type() { var fileExtension = string.Format(".{0}", Guid.NewGuid()); const string mimeType = "application/csharp-cloufiles-mimetype-tests"; MimeHelper.UserTypes.Add(fileExtension, mimeType); Assert.That(MimeHelper.GetMimeType(string.Format("{0}.{1}", "file", fileExtension)), Is.EqualTo(mimeType)); }
public void TestMimeDetect() { var mime = MimeHelper.GetContentType("a.docx"); Assert.AreEqual("application/vnd.openxmlformats-officedocument.wordprocessingml.document", mime); mime = MimeHelper.GetContentType("b.pptx"); Assert.AreEqual("application/vnd.openxmlformats-officedocument.presentationml.presentation", mime); }
public void Should_get_the_mime_type() { Assert.That(MimeHelper.GetMimeType("file.aif"), Is.EqualTo("audio/aiff")); Assert.That(MimeHelper.GetMimeType("file.xlt"), Is.EqualTo("application/vnd.ms-excel")); Assert.That(MimeHelper.GetMimeType("file.vmf"), Is.EqualTo("application/vocaltec-media-file")); Assert.That(MimeHelper.GetMimeType("file.rtf"), Is.EqualTo("text/richtext")); Assert.That(MimeHelper.GetMimeType("file.midi"), Is.EqualTo("audio/midi")); }
public void GetMimeFromFileName_ValidMixedCaseExtensions_Found() { Assert.AreEqual("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", MimeHelper.GetMimeFromFileName("doc1.xlsx")); Assert.AreEqual("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", MimeHelper.GetMimeFromFileName("MYDOC.XLSX")); Assert.AreEqual("image/jpeg", MimeHelper.GetMimeFromFileName("pic.jpg")); Assert.AreEqual("image/jpeg", MimeHelper.GetMimeFromFileName("PIC.JPG")); Assert.AreEqual("image/jpeg", MimeHelper.GetMimeFromFileName("pic.Jpg")); }
public T PostWithFile <T>(string url, string fileName, byte[] fileContent, NameValueCollection parameters, HttpMethod method = null) { var headers = InitHeaders(); var fileType = MimeHelper.GetContentTypeByName(fileName); return(ChalkableHttpFileLoader.HttpUploadFile(url, fileName, fileContent, fileType , ThrowWebException, JsonConvert.DeserializeObject <T>, parameters, headers, method ?? HttpMethod.Post)); }
public static async Task <FileModel> CreateAsync(IFile file, RootVolume volume) { if (file == null) { throw new ArgumentNullException("file"); } if (volume == null) { throw new ArgumentNullException("volume"); } await file.RefreshAsync(); string parentPath = file.DirectoryName.Substring(volume.RootDirectory.Length); string relativePath = file.FullName.Substring(volume.RootDirectory.Length); var fileLength = await file.LengthAsync; FileModel response; if (volume.CanCreateThumbnail(file) && fileLength > 0) { using (var stream = await file.OpenReadAsync()) { try { var dim = volume.PictureEditor.ImageSize(stream); response = new ImageModel { Thumbnail = await volume.GenerateThumbHashAsync(file), Dimension = $"{dim.Width}x{dim.Height}" }; } catch { // Fix for non-standard formats // https://github.com/gordon-matt/elFinder.NetCore/issues/36 response = new FileModel(); } } } else { response = new FileModel(); } response.Read = file.GetReadFlag(volume); response.Write = file.GetWriteFlag(volume); response.Locked = file.GetLockedFlag(volume); response.Name = file.Name; response.Size = fileLength; response.UnixTimeStamp = (long)(await file.LastWriteTimeUtcAsync - unixOrigin).TotalSeconds; response.Mime = MimeHelper.GetMimeType(file.Extension); response.Hash = volume.VolumeId + HttpEncoder.EncodePath(relativePath); response.ParentHash = volume.VolumeId + HttpEncoder.EncodePath(parentPath.Length > 0 ? parentPath : file.Directory.Name); return(response); }
/// <summary> /// Content type for the storage item /// </summary> /// <returns> /// Storage item's content type /// </returns> private string ContentType() { if (String.IsNullOrEmpty(_fileUrl) || _fileUrl.IndexOf(".") < 0) { return("application/octet-stream"); } return(MimeHelper.GetMimeType(_fileUrl)); }
public void GetMimeFromFileTest() { var f = @"D:\_Test\sunamo\win\Helpers\MImeHelper\GetMimeFromFile\Real"; //application/octet-stream> Assert.AreEqual(string.Empty, MimeHelper.GetMimeFromFile(f + AllExtensions.webp)); // Assert.AreEqual(string.Empty, MimeHelper.GetMimeFromFile(f + AllExtensions.jpg)); }
public ActionResult ReadUserNavigationDemo() { UserContext userContext = new UserContext(); string filePath = SysContext.Config.TempDirectory_Physical + SysContext.CommonService.CreateUniqueNameForFile("siteMapDemo.xml"); userContext.Navigation.RootNode.Save(filePath); return(File(filePath, MimeHelper.GetMIMETypeForFile(".xml"))); }