private static async Task ReturnFile(HttpContext context, DatabaseFile databaseFile) { string Extension = databaseFile.FileName.FromLast("."); string MimeType = MimeMappings.GetMimeType(Extension); context.Response.StatusCode = (int)HttpStatusCode.OK; context.Response.ContentType = MimeType; if (string.IsNullOrEmpty(context.Request.Headers["Range"])) { byte[] fileData; if (databaseFile.Data.Length != 0) { fileData = databaseFile.Data; } else { fileData = File.ReadAllBytes(databaseFile.FullName); } context.Response.ContentLength = fileData.Length; using (Stream stream = context.Response.Body) { await stream.WriteAsync(fileData, 0, fileData.Length); await stream.FlushAsync(); } } else { await RangeDownload(databaseFile.FullName, context); } }
private ActionResult Download(DatabaseFile thisFile) { if (thisFile is null) { throw new ArgumentNullException(nameof(thisFile)); } string Extension = thisFile.FileName.FromLast("."); string MimeType = MimeMappings.GetMimeType(Extension); if (thisFile.Data.Length == 0) { if (MimeType.StartsWith("text/", StringComparison.OrdinalIgnoreCase)) { return(this.Content(System.IO.File.ReadAllText(thisFile.FullName))); } else { FileStream fileStream = new FileStream(thisFile.FullName, FileMode.Open, FileAccess.Read); FileStreamResult fsResult = new FileStreamResult(fileStream, MimeType) { EnableRangeProcessing = true, FileDownloadName = Path.GetFileName(thisFile.FullName) }; return(fsResult); } } else { return(this.File(thisFile.Data, MimeType, thisFile.FileName)); } }
public ActionResult Download(DatabaseFile thisFile) { if (thisFile is null) { throw new ArgumentNullException(nameof(thisFile)); } if (!this.SecurityProvider.CheckAccess(thisFile, PermissionTypes.Read)) { throw new UnauthorizedAccessException(); } string Extension = thisFile.FileName.FromLast("."); string MimeType = MimeMappings.GetMimeType(Extension); if (thisFile.Data.Length == 0) { if (MimeType.StartsWith("text/", StringComparison.OrdinalIgnoreCase)) { return(this.Content(System.IO.File.ReadAllText(thisFile.FullName))); } else { return(this.File(System.IO.File.ReadAllBytes(thisFile.FullName), MimeType)); } } else { return(this.File(thisFile.Data, MimeType, thisFile.FileName)); } }
public async Task <IActionResult> RemoteDownloadItem([FromBody] RemoteDownloadRequest model) { HttpClient client = new(); client.DefaultRequestHeaders.UserAgent.Clear(); client.DefaultRequestHeaders.UserAgent.ParseAdd("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36"); using var resp = await client.GetAsync(model.Url); if (!resp.IsSuccessStatusCode) { throw new MemzException(MemzErrorCode.DownloadFailed, $"Cannot download image [{resp.StatusCode}] {model.Url}"); } var mime = resp.Content.Headers.ContentType.MediaType ?? string.Empty; if (!MimeMappings.IsSupportedMime(mime)) { throw new MemzException(MemzErrorCode.InvalidFileType, $"Invalid file type {mime}"); } var stream = await resp.Content.ReadAsStreamAsync(); var id = Guid.NewGuid().ToString(); var name = Path.ChangeExtension(id, MimeMappings.MimeToFileExtension(mime)); var meta = new StoredItemMetadata(0x01, name, mime, name, Array.Empty <string>(), null); await repo.StoreItem(GetRepository(), GetPassphrase(), id, meta, stream); var(info, _) = (await repo.ListRepositoryAsync(GetRepository(), GetPassphrase(), 0, 1, null, inf => inf.ItemId == id)); return(Ok(ApiResponse.FromData(info.FirstOrDefault()))); }
public static string MapFilePath(string path) { var extension = Path.GetExtension(path); if (MimeMappings.ContainsKey(extension)) { return(MimeMappings[extension]); } else { return("text/plain"); } }
public static string GetMimeType(string fileExtension) { if (fileExtension == null) { throw new ArgumentNullException(nameof(fileExtension), "Extension cannot be null"); } if (!fileExtension.StartsWith(".")) { fileExtension = "." + fileExtension; } if (!MimeMappings.ContainsKey(fileExtension)) { return("application/octet-stream"); } return(MimeMappings[fileExtension]); }
/// <summary> /// Returns the MIME mapping for the specified file name. /// </summary> /// <param name="fileName">The file name that is used to determine the MIME type.</param> /// <returns></returns> public static string GetMimeType(string fileName) { string mimeType = "application/octet-stream"; if (!String.IsNullOrEmpty(fileName)) { // the file name may include the assembly name, truncate it before the comma. int pos = fileName.IndexOf(','); if (pos > -1) { fileName = fileName.Substring(0, pos); } if (!MimeMappings.TryGetValue(Path.GetExtension(fileName), out mimeType)) { mimeType = "application/octet-stream"; } } return(mimeType); }
public void ImportImage(DatabaseFile target) { if (target is null) { throw new System.ArgumentNullException(nameof(target)); } if (this.DatabaseFileRepository is null) { return; } if (MimeMappings.GetMimeType(System.IO.Path.GetExtension(target.FullName)).StartsWith("image/", System.StringComparison.OrdinalIgnoreCase)) { Image newImage = this.ImageRepository.GetByUri(target.FullName).FirstOrDefault() ?? new Image(target.FullName); newImage.Refresh(); this.SecurityProvider.ClonePermissions(target, newImage); this.ImageRepository.AddOrUpdate(newImage); } }
private string BuildAcceptMediaHeader(MimeType mimeType, DicomTransferSyntax[] transferSyntaxes) { if (transferSyntaxes == null || transferSyntaxes.Length == 0 || transferSyntaxes[0].UID.UID == "*") { return($@"{MimeMappings.MultiPartRelated}; type=""{MimeMappings.MimeTypeMappings[MimeType.Dicom]}"""); } var acceptHeaders = new List <string>(); foreach (var mediaType in transferSyntaxes) { if (!MimeMappings.IsValidMediaType(mediaType)) { throw new ArgumentException($"invalid media type: {mediaType}"); } acceptHeaders.Add($@"{MimeMappings.MultiPartRelated}; type=""{MimeMappings.MimeTypeMappings[mimeType]}""; transfer-syntax={mediaType.UID.UID}"); } var headers = string.Join(", ", acceptHeaders); _logger?.Log(LogLevel.Debug, $"Generated headers: {headers}"); return(headers); }
public ResponseObject(string filename, Stream stream) { Content = stream; ContentType = MimeMappings.TryGetValue(Path.GetExtension(filename), out string mime) ? mime : "application/octet-stream"; }
/// <summary> /// Returns if the file extension corresponds to a known mime type. /// </summary> /// <param name="extension">The file extension to check.</param> /// <returns></returns> public static bool IsKnownType(string extension) { return(MimeMappings.ContainsKey(extension)); }
public List <string> ScrapeImages(string FilePath) { if (this.DatabaseFileRepository is null) { return(new List <string>()); } List <string> output = new List <string>(); DirectoryInfo TargetPath = new DirectoryInfo(FilePath); using (IWriteContext context = this.DatabaseFileRepository.WriteContext()) { output.Add($"Directory: {TargetPath}"); if (!TargetPath.Exists) { TargetPath.Create(); } List <DatabaseFile> imageFiles = this.DatabaseFileRepository.Where(f => f.FilePath == FilePath && !f.IsDirectory && MimeMappings.GetType(f.FileName) == MimeMappings.FileType.Image).ToList(); output.Add($"Total Images: {imageFiles.Count}"); List <Image> databaseImages = this.ImageRepository.Get().ToList(); output.Add($"Total Saved Images: {databaseImages.Count}"); foreach (Image thisImage in databaseImages) { DatabaseFile match = imageFiles.Where(f => string.Equals(f.FullName, thisImage.Uri, StringComparison.OrdinalIgnoreCase)).FirstOrDefault(); if (match == null) { output.Add($"Deleting Missing Image: {thisImage.Uri}"); this.ImageRepository.Delete(thisImage); } else { if (thisImage.IsDeleted == true) { output.Add($"Re-adding Image: {match.FullName}"); } this.ImageRepository.Delete(thisImage); imageFiles.Remove(match); } } foreach (DatabaseFile thisFile in imageFiles) { try { output.Add($"Adding New Image: {thisFile.FullName}"); this.ImageService.ImportImage(thisFile); } catch (Exception ex) { this.ErrorRepository.TryAdd(ex); output.Add($"Error adding image: {thisFile.FullName}"); } } } return(output); }