/// <summary> /// Get file type from path /// </summary> /// <param name="filePath"></param> /// <returns>FileType</returns> public static FileType GuessFileType(string filePath) { var mime = GuessMimeType(filePath); var ext = MimeTypesMap.GetExtension(mime); return(new FileType(mime, ext)); }
private static void download_file2(string course, ChromeDriver driver, string path) { //string header = driver.FindElementById("courseMenu_link").Text; //string course_code = header.Replace("Old-", "").Split('-')[1].Split(' ')[0]; //path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + @"\Course\" + course_code + "\\" + path; System.IO.Directory.CreateDirectory(path); if (IsElementPresent(driver, By.Id("downloadPanelButton"))) { string outline = driver.FindElementById("downloadPanelButton").GetAttribute("href"); using (WebClient client = new WebClient()) { client.Headers[HttpRequestHeader.Cookie] = cookieString(driver); var data = client.DownloadData(outline); var extension = MimeTypesMap.GetExtension(client.ResponseHeaders["Content-Type"]); string fileName = GetSafeFilename(driver.FindElementById("downloadPanelFileName").Text); System.IO.Directory.CreateDirectory(path); File.WriteAllBytes(path + "\\" + System.IO.Path.GetFileNameWithoutExtension(fileName) + "." + extension, data); } } if (IsElementPresent(driver, By.Id("content_listContainer"))) { IList <IWebElement> elements = driver.FindElements(By.CssSelector("a[href*=bbcswebdav]")); foreach (var element in elements) { download_file3(course, driver, path, element); } } }
/// <summary> /// Get file type from bytes buffer /// </summary> /// <param name="buffer"></param> /// <returns>FileType</returns> public static FileType GuessFileType(byte[] buffer, int size = 512) { var mime = GuessMimeType(buffer, size); var ext = MimeTypesMap.GetExtension(mime); return(new FileType(mime, ext)); }
/// <summary> /// Get media's extension. /// </summary> /// <param name="name">The name of the attachment media.</param> /// <param name="type">The media's fallback type.</param> /// <returns>Media file extension.</returns> private static string GetMediaExtension(string name, string type) { var ext = MimeTypesMap.GetExtension(type); if (string.IsNullOrEmpty(ext)) { type = MimeTypesMap.GetMimeType(name) ?? type; ext = MimeTypesMap.GetExtension(type); } if (string.IsNullOrEmpty(ext)) { if (type.Contains(MediaTypes.Image) || type.Contains(MediaTypes.Thumb)) { return(".jpg"); } if (type.Contains(MediaTypes.Video)) { return(".mp4"); } if (type.Contains(MediaTypes.Voice)) { return(".mp3"); } } return($".{ext}"); }
/// <summary> /// Get file type from stream /// </summary> /// <param name="stream"></param> /// <returns>FileType</returns> public static FileType GuessFileType(Stream stream, int size = 512) { var mime = GuessMimeType(stream, size); var ext = MimeTypesMap.GetExtension(mime); return(new FileType(mime, ext)); }
public void GetExtension_throws_when_mimeType_is_null() { Should.Throw <ArgumentNullException>(() => { var extension = MimeTypesMap.GetExtension(null); }); }
/// <summary> /// Generates a new <see cref="IFile"/> containing random data, random file name /// and a random content type. /// </summary> /// <param name="random">The randomizer to use to generate the file.</param> /// <returns> /// A generate <see cref="IFile"/>. /// </returns> public static IFile NextFile(this Random random) { var data = random.NextBytes(); var contentType = random.Next(ContentTypes); var fileName = $"{random.NextString(1, 20)}.{MimeTypesMap.GetExtension(contentType)}"; return(new MemoryFile(new FileInfo(fileName, contentType), data)); }
private async Task <ApplicationFile> BuildApplicationFile(IFormFile file) { var content = await _fileToByteArrayConverter.Convert(file); var contentType = file.ContentType; var extension = MimeTypesMap.GetExtension(file.ContentType); return(new ApplicationFile(content, contentType, extension)); }
public void CoreOnDerive(ObjectOnDerive method) { this.Revision = Guid.NewGuid(); if (this.ExistInData || this.ExistInDataUri) { if (!this.ExistMediaContent) { this.MediaContent = new MediaContentBuilder(this.Strategy.Session).Build(); } } if (this.ExistInData) { this.MediaContent.Data = this.InData; this.MediaContent.Type = this.InType ?? MediaContents.Sniff(this.InData, this.InFileName); this.RemoveInType(); this.RemoveInData(); } if (this.ExistInFileName) { this.Name = Path.GetFileNameWithoutExtension(this.InFileName); this.RemoveInFileName(); } if (this.ExistInDataUri) { var dataUrl = new DataUrl(this.InDataUri); this.MediaContent.Data = Convert.FromBase64String(dataUrl.ReadAsBase64EncodedString()); this.MediaContent.Type = dataUrl.ContentType; this.RemoveInDataUri(); } this.Type = this.MediaContent?.Type; var name = !string.IsNullOrWhiteSpace(this.Name) ? this.Name : this.UniqueId.ToString(); var fileName = $"{name}.{MimeTypesMap.GetExtension(this.Type)}"; var safeFileName = new string(fileName.Where(ch => !InvalidFileNameChars.Contains(ch)).ToArray()); var uppercaseSafeFileName = safeFileName.ToUpperInvariant(); foreach (var invalidFileName in InvalidFileNames) { if (uppercaseSafeFileName.StartsWith(invalidFileName)) { safeFileName += "_" + safeFileName; break; } } this.FileName = safeFileName; }
public async Task <AbstractTarget> GetTargetAsync() { HttpWebRequest req = WebRequest.CreateHttp(Uri); req.Method = "HEAD"; req.KeepAlive = false; using (var resp = (HttpWebResponse)await req.GetResponseAsync()) { // abort the request if (req != null) { req.Abort(); } // get suggested name from url string suggestedName = Path.GetFileName(Uri.ToString()); if (!IsFileNameValid(suggestedName)) { suggestedName = Path.GetRandomFileName(); } string extension = Path.GetExtension(suggestedName); // guess the extension fron content type string contentType = (resp.ContentType ?? string.Empty) .Split(';', StringSplitOptions.None)[0]; if (contentType.Length == 0) { contentType = "text/html"; } // don't modify extension if content type is application/octet-stream if (!contentType.Equals("application/octet-stream")) { if (!MimeTypesMap.GetMimeType(extension).Equals(contentType)) { var suggestedExtension = MimeTypesMap.GetExtension(contentType); if (suggestedExtension.Length > 0 && !Path.GetExtension(suggestedName).Equals(suggestedExtension)) { suggestedName = suggestedName + "." + suggestedExtension; } } } // check if rangable AbstractTarget target = null; if (resp.ContentLength <= 0) { target = new HttpTarget(Uri, suggestedName); } else { target = new HttpRangableTarget(Uri, suggestedName, resp.ContentLength); } return(target); } }
public void GetExtension_with_unknown_mimeType() { // Arrange var expected = "bin"; // Act var extension = MimeTypesMap.GetExtension("notvalid/bogus"); // Assert extension.ShouldBe(expected); }
public void GetExtension_with_known_mimeType() { // Arrange var expected = "txt"; // Act var extension = MimeTypesMap.GetExtension("text/plain"); // Assert extension.ShouldBe(expected); }
/// <inheritdoc/> public async Task <AttachmentInfoDto> SaveAttachmentAsync(AttachmentDto attachmentDto, CancellationToken cancellationToken) { var fileName = $"{Guid.NewGuid()}.{MimeTypesMap.GetExtension(attachmentDto.ContentType)}"; var path = GetFullFilePath(fileName); await File.WriteAllBytesAsync(path, attachmentDto.Data, cancellationToken); return(new AttachmentInfoDto() { FileKey = path }); }
public void ReturnDefaultMimeType_GivenInvalidFilename() { // Arrange string filename = "test.test.test"; // Act string result = Common.GetMimeType(filename); // Assert Assert.NotNull(result); Assert.NotNull(MimeTypesMap.GetExtension(result)); }
public async Task <string> UploadImage() { var re = Request; var apiKey = re.Headers.FirstOrDefault(x => x.Key.ToLower() == "x-api-key").Value; if (apiKey.ToString() != _realKey) { throw new ArgumentException("Invalid or no API Key provided (x-api-key header)"); } var boundary = Request.GetMultipartBoundary(); var reader = new MultipartReader(boundary, Request.Body); var section = await reader.ReadNextSectionAsync(); var disposition = section.GetContentDispositionHeader(); if (disposition != null) { var fileSection = section.AsFileSection(); var contentType = section.ContentType; // Generate random filename string hash; using (var md5 = MD5.Create()) { hash = BitConverter.ToString(md5.ComputeHash(Encoding.ASCII.GetBytes(fileSection.FileName))).Replace("-", "").ToLower(); } var timestamp = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeMilliseconds().ToString(); var filename = _generateFilename(disposition.FileName.ToString()); filename += timestamp.Substring(timestamp.Length - 2); filename += hash.Substring(0, 2); var extension = MimeTypesMap.GetExtension(contentType); filename += $".{extension}"; string path = Path.Combine(_storagePath, $"{filename}"); using (var fileStream = new FileStream(path, FileMode.Create, FileAccess.Write)) { fileSection.FileStream.Position = 0; await fileSection.FileStream.CopyToAsync(fileStream); } return($"{_url}/{filename}"); } else { throw new ArgumentException("No Content-Disposition header"); } }
public static void AddVideoOutput(this WebDocument document, string outputPath, Presentation pres) { List <VideoFrame> videoFrames = ShapeHelper.GetListOfShapes <VideoFrame>(pres); for (int i = 0; i < videoFrames.Count; i++) { IVideo video = videoFrames[i].EmbeddedVideo; string ext = MimeTypesMap.GetExtension(videoFrames[i].EmbeddedVideo.ContentType); string path = Path.Combine(outputPath, string.Format("video{0}.{1}", i, ext)); var outputFile = document.Output.Add(path, video); document.Output.BindResource(outputFile, video); } }
public async Task <string> saveArtwork(TagLib.Tag tag, int id) { IPicture picture = tag.Pictures[0]; ByteVector vector = picture.Data; Byte[] bytes = vector.ToArray(); string extension = MimeTypesMap.GetExtension(picture.MimeType); System.IO.Directory.CreateDirectory(System.IO.Path.Combine(App.LocalStoragePath, "AlbumArt")); var filename = System.IO.Path.Combine(App.LocalStoragePath, "AlbumArt", id.ToString() + "." + extension); System.IO.File.WriteAllBytes(filename, bytes); return(id.ToString() + "." + extension); }
public static string GetFileName(Image image) { if (image.Id < 0) { throw new Exception("invalid Id"); } if (string.IsNullOrEmpty(image.MimeType)) { throw new Exception("invalid file mime type"); } string extension = MimeTypesMap.GetExtension(image.MimeType); return(image.Id + "." + extension); }
/// <summary> /// Downloads the highest bitrate file specified in a Media IEnumerable to a file specified by the title. /// File Extension is determined by the MimeType and should be guaranteed to be compatible as a result /// </summary> /// <param name="source">IEnumerable of Media Definitions retrieved from BiliBili page</param> /// <param name="title">The title of the video</param> /// <returns>A task representing the return of the absolute path of the downloaded file</returns> private static async Task <string> DownloadBest(IEnumerable <Media> source, string title) { //Grab highest bitrate source Console.WriteLine("Finding best media..."); Media bestMedia = source.OrderByDescending(a => a.Bandwidth).First(); Console.WriteLine("Url: " + bestMedia.BaseUrl); Console.WriteLine("MimeType: " + bestMedia.MimeType); //Find a free place to put the file FileInfo targetFile = FindFreeFile(DownloadPath, $"{title}.{MimeTypesMap.GetExtension(bestMedia.MimeType)}"); Console.WriteLine("Downloading media..."); await SafeDownload(bestMedia.BaseUrl, targetFile); Console.WriteLine($"{bestMedia.MimeType} downloaded to: " + targetFile.FullName); return(targetFile.FullName); }
private static void download_file3(string course, ChromeDriver driver, string path, IWebElement element) { string outline = element.GetAttribute("href"); using (WebClient client = new WebClient()) { client.Headers[HttpRequestHeader.Cookie] = cookieString(driver); var data = client.DownloadData(outline); var extension = MimeTypesMap.GetExtension(client.ResponseHeaders["Content-Type"]); string fileName = GetSafeFilename(element.Text); System.IO.Directory.CreateDirectory(path); string file_name = path + "\\" + System.IO.Path.GetFileNameWithoutExtension(fileName) + "." + extension; if (file_name.Length > 259) { Console.WriteLine("Warning: Course:" + course + " file:" + fileName + ". Please download manually"); return; } File.WriteAllBytes(file_name, data); } }
private void FileValidation(string propertyName, IFormFile file, CustomContext context, int maxFileLengthInMb, IEnumerable <string> allowedExtensions) { const int bytesInMegaByte = 1000000; var maxLengthInBytes = maxFileLengthInMb * bytesInMegaByte; if (file.Length == 0) { context.AddFailure(propertyName, "File cannot be empty"); return; } if (!allowedExtensions.Any(extension => extension.Equals(MimeTypesMap.GetExtension(file.ContentType), StringComparison.OrdinalIgnoreCase))) { context.AddFailure(propertyName, "Not supported file type"); return; } if (file.Length > maxLengthInBytes) { context.AddFailure(propertyName, "Too big file"); } }
private static string _getFilename(string url, string mimeType = null, string defaultMimeType = null) { var fileName = Path.GetFileName(new Uri(url).LocalPath); if (string.IsNullOrEmpty(fileName)) { fileName = "noname"; } if (!fileName.Contains(".")) { if (mimeType != null) { return($"{fileName}.{MimeTypesMap.GetExtension(mimeType)}"); } if (defaultMimeType != null) { return($"{fileName}.{MimeTypesMap.GetExtension(defaultMimeType)}"); } } return(fileName); }
public static void AddImagesOutput(this WebDocument document, string outputPath, Presentation pres) { for (int index = 0; index < pres.Images.Count; index++) { IPPImage image = pres.Images[index]; string path; string ext; if (image.ContentType == "image/x-emf" || image.ContentType == "image/x-wmf") // Output will convert metafiles to png { ext = "png"; } else { ext = MimeTypesMap.GetExtension(image.ContentType); } path = Path.Combine(outputPath, string.Format("image{0}.{1}", index, ext)); var outputFile = document.Output.Add(path, image); document.Output.BindResource(outputFile, image); } }
public async Task <string> DownloadToFile(string path, Uri uri, HttpMethod httpMethod, [AllowNull] string extension, [AllowNull] string data, CancellationToken token) { string tempPath = Path.ChangeExtension(path, "tmp"); try { string mediaType = null; using (var fileStream = new FileStream(tempPath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None, 1024 * 1024, true)) { mediaType = await DownloadToStream(fileStream, uri, httpMethod, data, token).ConfigureAwait(false); } string fileExtension = extension ?? MimeTypesMap.GetExtension(mediaType); string destFileName = Path.ChangeExtension(path, fileExtension); if (File.Exists(destFileName)) { string destFileNameOld = Path.ChangeExtension(destFileName, "old"); File.Move(destFileName, destFileNameOld); File.Delete(destFileNameOld); } File.Move(tempPath, destFileName); return(destFileName); } finally { // always delete the tmp file if (File.Exists(tempPath)) { File.Delete(tempPath); } } }
public async Task <IActionResult> UploadFile([FromQuery] int groupId, IFormFile file) { var size = file?.Length; var sizeInMB = (size / 1024f) / 1024f; if (size <= 0 || sizeInMB > appSettings.MaxFileSizeInMB) { return(BadRequest("Niepoprawny format pliku")); } var fileExtension = MimeTypesMap.GetExtension(file.ContentType); var availableFileFormats = new List <string> { "docx", "pdf", "jpeg", "png" }; if (!availableFileFormats.Any(a => a.Equals(fileExtension))) { return(BadRequest("Niepoprawny format pliku")); } var userId = ClaimsReader.GetUserId(Request); var groupRecord = await context.Set <Group>().Include(a => a.Users).FirstOrDefaultAsync(a => a.Id == groupId); var userRecord = await context.Set <User>().FindAsync(userId); if (groupRecord == null || userRecord == null) { return(NotFound()); } if (!groupRecord.Users.Any(a => a.UserId == userId)) { return(BadRequest()); } if (!Directory.Exists(appSettings.FilesPath)) { Directory.CreateDirectory(appSettings.FilesPath); } var filePath = Path.Combine(appSettings.FilesPath, Path.GetRandomFileName()); try { using var stream = System.IO.File.Create(filePath); await file.CopyToAsync(stream); var dbFile = new DBFile { DateAdded = DateTime.UtcNow, FilePath = filePath, FileName = file.FileName, User = userRecord, Group = groupRecord, Size = GetFileSizeAsString(size.Value), FileType = fileExtension.Equals(".pdf") || fileExtension.Equals(".docx") ? Enums.FileType.Document : Enums.FileType.Photo }; context.Set <DBFile>().Add(dbFile); await context.SaveChangesAsync(); return(Ok(new FileDto { Id = dbFile.Id, Owner = dbFile.User.Login, DateAdded = dbFile.DateAdded, FileName = dbFile.FileName, IsOwner = true })); } catch (ArgumentException ex) { Logger.Log($"{nameof(FilesController)} {nameof(UploadFile)}", ex.Message, NLog.LogLevel.Error, ex); return(BadRequest()); } catch (DbUpdateException ex) { System.IO.File.Delete(filePath); Logger.Log($"{nameof(FilesController)} {nameof(UploadFile)}", ex.Message, NLog.LogLevel.Error, ex); return(BadRequest()); } catch (Exception ex) { Logger.Log($"{nameof(FilesController)} {nameof(UploadFile)}", ex.Message, NLog.LogLevel.Error, ex); return(BadRequest()); } }
public static string GetExtension(string mime) => MimeTypesMap.GetExtension(mime);
/// <summary> /// Get file extension from stream /// </summary> /// <param name="stream"></param> /// <returns>Extension as string</returns> public static string GuessExtension(Stream stream, int size = 512) { return(MimeTypesMap.GetExtension(GuessMimeType(stream, size))); }
/// <summary> /// Get file extension from bytes buffer /// </summary> /// <param name="buffer"></param> /// <returns>Extension as string</returns> public static string GuessExtension(byte[] buffer, int size = 512) { return(MimeTypesMap.GetExtension(GuessMimeType(buffer, size))); }
/// <summary> /// Get file extension from path /// </summary> /// <param name="filePath"></param> /// <returns>Extension as string</returns> public static string GuessExtension(string filePath) { return(MimeTypesMap.GetExtension(GuessMimeType(filePath))); }
/// <summary> /// Get file extension from bytes buffer /// </summary> /// <param name="buffer"></param> /// <returns>Extension as string</returns> public static string GuessExtension(byte[] buffer) => MimeTypesMap.GetExtension(GuessMimeType(buffer));