public static (string extension, string data) GetBase64StringContents(this string input) { input = input.Replace("data:", ""); var parts = input.Split(';').ToList <string>(); return(MimeTypeMap.GetExtension(parts[0]), parts[1].Replace("base64,", "")); }
public void GetExtension_throws_when_mimeType_is_null() { Should.Throw <ArgumentNullException>(() => { var extension = MimeTypeMap.GetExtension(null); }); }
public void GetExtension_throws_when_mimeType_is_malformed() { Should.Throw <ArgumentException>(() => { var extension = MimeTypeMap.GetExtension(".blablabla"); }); }
public void GetExtension_with_unknown_mimeType() { Should.Throw <ArgumentException>(() => { var extension = MimeTypeMap.GetExtension("blablabla"); }); }
public HttpResponseMessage Post() { var httpRequest = HttpContext.Current.Request; String finalFileName = ""; if (httpRequest.Files.Count < 1) { return(Request.CreateResponse(HttpStatusCode.BadRequest)); } foreach (string file in httpRequest.Files) { var postedFile = httpRequest.Files[file]; var fileName = DateTime.Now.ToFileTime(); var fileExt = MimeTypeMap.GetExtension(postedFile.ContentType); if (!fileExt.ToString().Contains(".jp") && !fileExt.ToString().Equals(".png") && !fileExt.ToString().Equals(".gif")) { return(Request.CreateResponse(HttpStatusCode.BadRequest, "extensión inválida")); } finalFileName = fileName + fileExt; var filePath = HttpContext.Current.Server.MapPath("~/App_Data/Uploads/" + finalFileName); postedFile.SaveAs(filePath); // NOTE: To store in memory use postedFile.InputStream } return(Request.CreateResponse(HttpStatusCode.Created, (finalFileName))); }
static void Main(string[] args) { // demo one extension have only one mime Console.WriteLine("txt -> "); foreach (string mime in MimeTypeMap.GetMimeType("txt")) { Console.WriteLine(mime); } // demo one extension have multipule mime Console.WriteLine(); Console.WriteLine("zip -> "); foreach (string mime in MimeTypeMap.GetMimeType("zip")) { Console.WriteLine(mime); } // demo get extension from mime type Console.WriteLine(); Console.WriteLine("audio/wav -> "); foreach (string mime in MimeTypeMap.GetExtension("audio/wav")) { Console.WriteLine(mime); } }
public static async Task <string> UploadAsync(Stream file, string mime) { string ext = ""; try { ext = MimeTypeMap.GetExtension(mime); } catch { return(null); } string name = Guid.NewGuid().ToString(); string prefix = $"{name[0]}/{name[1]}/{name[2]}"; string path = Startup.StoragePath + "/" + prefix; if (!(TryExistOrCreate(path))) { return(null); } path += ('/' + name + ext); try { using var fileStream = new FileStream(path, FileMode.Create); await file.CopyToAsync(fileStream); } catch { return(null); } return("/storage/" + prefix + '/' + name + ext); }
public IActionResult UploadImage() { try { var file = Request.Form.Files[0]; if (file.Length > 0) { string fileName = Guid.NewGuid().ToString() + MimeTypeMap.GetExtension(file.ContentType); string outputPath = _hostingEnvironment.ContentRootPath + "\\wwwroot\\temp\\" + fileName; Directory.CreateDirectory(_hostingEnvironment.ContentRootPath + "\\wwwroot\\temp\\"); using (var output = new FileStream(outputPath, FileMode.Create)) { file.CopyTo(output); } Logger.WriteInfo("Image uploaded to temporary location."); return(Ok(fileName)); } else { Logger.WriteWarning("The bad uploaded request is sent from client."); return(BadRequest()); } } catch (Exception ex) { Logger.WriteError(ex); return(StatusCode(500, ex.Message)); } }
public async Task <ActionResult <FileModel> > Get(string name) { FileModel savedfile = new FileModel(); //Json var pathTemp = Path.GetTempPath(); var jsonfileName = name + ".json"; var jsonfullPath = Path.Combine(pathTemp, jsonfileName); Task TaskGetFile = new Task(() => { using (StreamReader reader = System.IO.File.OpenText(jsonfullPath)) { JObject o = (JObject)JToken.ReadFrom(new JsonTextReader(reader)); var fileName = name + MimeTypeMap.GetExtension((string)o["MimeType"]); var fullPath = Path.Combine(pathTemp, fileName); savedfile.FileName = name; savedfile.MimeType = (string)o["MimeType"]; } }); TaskGetFile.Start(); try { // we wait for complete all tasks await Task.WhenAll(TaskGetFile); } catch (Exception) { return(StatusCode(500, "Internal server error")); } return(Ok(savedfile)); }
private string SaveImageFromBase64(string base64String) { Int32 unixTimestamp = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds; var rootPath = this.HostingEnvironment.WebRootPath; var uploadsDir = "uploads"; var uploadsPath = Path.Combine(rootPath, uploadsDir); if (!Directory.Exists(uploadsPath)) { Directory.CreateDirectory(uploadsPath); } var header = Regex.Match(base64String, "^data:image/[a-zA-Z]+;base64,").Value; var content = Regex.Replace(base64String, "^data:image/[a-zA-Z]+;base64,", String.Empty); var mimeType = this.Base64MimeType(header); var extension = MimeTypeMap.GetExtension(mimeType); var fileName = $"{unixTimestamp}_{Guid.NewGuid()}{extension}"; var filePath = Path.Combine(uploadsPath, fileName); var bytes = Convert.FromBase64String(content); using (var imageFile = new FileStream(filePath, FileMode.Create)) { imageFile.Write(bytes, 0, bytes.Length); imageFile.Flush(); } var relativePath = Path.Combine(uploadsDir, fileName); relativePath = relativePath.Replace(Path.DirectorySeparatorChar, '/'); // use Unix style path return(relativePath); }
public async Task <Uri> UploadFile(string containerName, string contentType, Stream stream, CancellationToken cancellationToken = default !) { try { var headers = new BlobHttpHeaders { ContentType = contentType }; var blobName = Guid.NewGuid() + MimeTypeMap.GetExtension(contentType); var blobContainerClient = _blobServiceClient.GetBlobContainerClient(containerName); await blobContainerClient.CreateIfNotExistsAsync(PublicAccessType.Blob, _metadata, cancellationToken); var blobClient = blobContainerClient.GetBlobClient(blobName); await blobClient.UploadAsync( stream, headers, conditions : BlobRequestConditions, cancellationToken : cancellationToken); return(blobClient.Uri); } catch (Exception e) { _logger.Error(e, "Uploading file to Azure Blob Storage failed"); throw; } }
/// <summary> /// Gets the extension from. /// </summary> /// <param name="wc">The wc.</param> /// <returns></returns> public static string GetExtensionFrom(this WebClient wc) { var contentType = wc.ResponseHeaders["Content-Type"]; // Debug.Log("Content-Type: " + contentType); return(MimeTypeMap.GetExtension(contentType)); }
private void ValidateMimeType(string mimeType) { IEnumerable <string> extensions = MimeTypeMap.GetExtension(mimeType).Intersect(_supportedMimeTypes); if (!extensions.Any()) { throw new NotSupportedException($"File type is not supported."); } }
private BinaryFile BinaryFileResponseMethod(Stream stream, string contentType) { string filename = RandomStringBuilder.RandomString(10) + MimeTypeMap.GetExtension(contentType); return(new BinaryFile( filename, BinaryResponseMethod(stream, contentType) )); }
/// <summary> /// Gets the extension from. /// </summary> /// <param name="wc">The wc.</param> /// <param name="url">The URL.</param> /// <param name="data">The data.</param> /// <returns></returns> public static string GetExtensionFrom(this WebClient wc, string url, out byte[] data) { data = wc.DownloadData(url); var contentType = wc.ResponseHeaders["Content-Type"]; // Debug.Log("Content-Type: " + contentType); return(MimeTypeMap.GetExtension(contentType)); }
public void GetMultiExtensionTest() { var result = MimeTypeMap.GetExtension("audio/wav").ToList(); CollectionAssert.AreEqual(result, new List <string>() { ".wav", ".wave" }); }
public DirectoryEntry UploadFile(string parentPath, FileUpload file) { var parentAbsolutePath = Path.Join(RootPath, parentPath); parentAbsolutePath = Path.GetFullPath(parentAbsolutePath); if (!Directory.Exists(parentAbsolutePath)) { throw new ArgumentException("Directory does not exist!"); } if (string.IsNullOrWhiteSpace(file.Name)) { throw new ArgumentException("Name is empty!"); } if (string.IsNullOrWhiteSpace(file.ContentType)) { throw new ArgumentException("Content type is empty!"); } if (string.IsNullOrWhiteSpace(file.FileBase64)) { throw new ArgumentException("Data is empty!"); } string fileName; try { fileName = file.Name + $"{MimeTypeMap.GetExtension(file.ContentType)}"; } catch (Exception e) { throw new ArgumentException("Content type is incorrect!"); } var fileAbsolutePath = Path.Combine(parentAbsolutePath, fileName); if (File.Exists(fileAbsolutePath)) { throw new ArgumentException("File already exists!"); } using var createdFile = new FileStream(fileAbsolutePath, FileMode.Create); createdFile.Write(Convert.FromBase64String(file.FileBase64)); return(new DirectoryEntry { Type = DirectoryEntryType.File, Name = fileName, Path = Normalize(Path.GetRelativePath(RootPath, fileAbsolutePath)), Size = createdFile.Length, LastModified = DateTime.Now, }); }
protected void Register_Business(object sender, EventArgs e) { string name = HttpUtility.HtmlEncode(tb_businessName.Text.Trim()); string registrationNumber = HttpUtility.HtmlEncode(tb_businessRegNum.Text.Trim()); string url = HttpUtility.HtmlEncode(tb_businessUrl.Text.Trim()); string type = HttpUtility.HtmlEncode(tb_businessType.Text.Trim()); string logoId, acraCertificate = null; List <String> errors = Validate_Submission(); if (errors.Count > 0) { lv_feedback.Visible = true; lv_feedback.DataSource = errors; lv_feedback.DataBind(); return; } string docDir = Server.MapPath(@"\assets\Documents"); if (!Directory.Exists(docDir)) { Directory.CreateDirectory(docDir); } string logoDir = Server.MapPath(@"\assets\Logos"); if (!Directory.Exists(logoDir)) { Directory.CreateDirectory(logoDir); } acraCertificate = Guid.NewGuid().ToString(); file_acraRegistration.SaveAs(Path.Combine(docDir, acraCertificate + ".pdf")); if (file_logoId.HasFile) { logoId = Guid.NewGuid().ToString(); file_acraRegistration.SaveAs(Path.Combine(logoDir, logoId + MimeTypeMap.GetExtension(file_logoId.PostedFile.ContentType))); } else { logoId = null; } if (Session["userId"] != null) { Service1Client client = new Service1Client(); if (client.CreateBusiness(name, registrationNumber, url, type, acraCertificate, logoId, Session["userId"].ToString())) { Response.Redirect("/BDBusinesses.aspx", false); } } }
public void GetExtension_with_known_mimeType() { // Arrange var expected = ".txt"; // Act var mimeType = MimeTypeMap.GetExtension("text/plain"); // Assert mimeType.ShouldBe(expected); }
public static async Task <StorageFile> CreateTemporaryFileAsync(IRandomAccessStream stream, string contentType) { stream.Seek(0); var filename = $"{Guid.NewGuid()}{MimeTypeMap.GetExtension(contentType)}"; var file = await ApplicationData.Current.TemporaryFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting); using (var fileStream = await file.OpenStreamForWriteAsync()) await stream.AsStream().CopyToAsync(fileStream); return(file); }
public async Task <ActionResult <FileModel> > Post([FromBody] FileModel item) { var pathTemp = Path.GetTempPath(); var fileName = item.FileName + MimeTypeMap.GetExtension(item.MimeType); var fullPath = Path.Combine(pathTemp, fileName); // Create the file. Task TaskSaveFile1 = new Task(async() => { using (FileStream fs = System.IO.File.Create(fullPath)) { await fs.WriteAsync(item.Content, 0, item.Content.Length); } } ); // Create json file. var jsonfileName = item.FileName + ".json"; var jsonfullPath = Path.Combine(pathTemp, jsonfileName); JObject newJsonObject = new JObject( new JProperty("fileName", item.FileName), new JProperty("Content", item.Content), new JProperty("MimeType", item.MimeType)); JObject newJsonObject1 = (JObject)JToken.FromObject(item); Task TaskSaveFile2 = new Task(async() => { using (StreamWriter file = System.IO.File.CreateText(jsonfullPath)) using (JsonTextWriter writer = new JsonTextWriter(file)) { await newJsonObject1.WriteToAsync(writer); } } ); TaskSaveFile1.Start(); TaskSaveFile2.Start(); try { // we wait for complete all tasks await Task.WhenAll(TaskSaveFile1, TaskSaveFile2); } catch (Exception) { return(StatusCode(500, "Internal server error")); } return(Ok()); }
/// <summary> /// Maps the MediaType header in the <see cref="HttpRequestMessage"/> to a known list of file extensions. /// </summary> /// <param name="request"></param> /// <returns></returns> public static string GetFileExtensionString(HttpRequestMessage request) { if (request == null) { throw new ArgumentNullException(nameof(request)); } // get the acceptable content types specified by the request message var acceptHeaders = request.Headers?.Accept; return(MimeTypeMap.GetExtension(acceptHeaders.FirstOrDefault()?.MediaType)); }
/// <summary> /// Gets the loaded picture binary /// </summary> /// <param name="pictureId"></param> /// <param name="mimeType"></param> /// <returns></returns> protected virtual byte[] LoadPictureFromFile(int pictureId, string mimeType) { string fileName = string.Format(PictureFileNameFormat, pictureId, MimeTypeMap.GetExtension(mimeType)); var filePath = GetPictureLocalPath(fileName); if (!File.Exists(filePath)) { return(new byte[0]); } return(File.ReadAllBytes(filePath)); }
public byte[] GetThumbnailForMimeType(string mimeType, Thumbnails.Size pxSize = Thumbnails.Size.Px32) { try { var extension = MimeTypeMap.GetExtension(mimeType).Replace(".", ""); return(iconsStorage.GetIcon(extension, pxSize)); } catch (Exception) { return(iconsStorage.GetIcon("_blank", pxSize)); } }
/// <summary> /// GetArchiveBase64. /// </summary> /// <param name="archiveId"></param> /// <returns></returns> public async Task <ArchiveBase64ViewModel> GetArchiveBase64(String archiveId) { ArchiveBase64ViewModel result = null; ArchiveModel archive = (await _archiveRepository.FindOneArchive(archiveId)); String extension = MimeTypeMap.GetExtension(archive?.ContentType); String archivePath = String.Format(ConstantsConfiguration.PATH_IMAGES, archiveId, extension); if (!(File.ReadAllBytes(archivePath) is null) && (!(archive is null))) { result = new ArchiveBase64ViewModel(archive.ArchiveName, archive.ContentType, archivePath); } return(result); }
/// <summary> /// Save picture binary to file system /// </summary> /// <param name="pictureId"></param> /// <param name="pictureBinary"></param> /// <param name="mimeType"></param> protected virtual void SavePictureToFile(int pictureId, byte[] pictureBinary, string mimeType) { //ensure content/images directory exists var picturesDirectoryPath = _fileProvider.MapContentPath(PictureFolderPath); if (!Directory.Exists(picturesDirectoryPath)) { Directory.CreateDirectory(picturesDirectoryPath); } string fileName = string.Format(PictureFileNameFormat, pictureId, MimeTypeMap.GetExtension(mimeType)); var filePath = GetPictureLocalPath(fileName); File.WriteAllBytes(filePath, pictureBinary); }
/// <summary> /// Delete picture on file system /// </summary> /// <param name="picture"></param> protected virtual void DeletePictureOnFile(Picture picture) { if (picture == null) { throw new ArgumentNullException(nameof(picture)); } string fileName = string.Format(PictureFileNameFormat, picture.Id, MimeTypeMap.GetExtension(picture.MimeType)); var filePath = GetPictureLocalPath(fileName); if (File.Exists(filePath)) { File.Delete(filePath); } }
private string GetExtensionFromMimeType(string mimeType) { try { return(MimeTypeMap.GetExtension(mimeType).Intersect(_supportedMimeTypes).First()); } catch (ArgumentNullException ex) { throw new InvalidOperationException($"Mime type is required", ex); } catch (ArgumentException) { throw new NotSupportedException($"file type {mimeType ?? "NULL"} is not supported."); } }
private string GetExtensionFromMimeType(string dataFile) { int intPosition = dataFile.IndexOf(":"); int endPosition = dataFile.IndexOf(C_BASE64); if (endPosition > 0 && intPosition > 0) { string contentType = dataFile.Substring(intPosition + 1, (endPosition - intPosition) - 1); return(MimeTypeMap.GetExtension(contentType)); } else { return(string.Empty); } }
/// <inheritdoc/> public async Task <string> ImageDownloadAndSaveAsync(string?url, string name) { if (string.IsNullOrWhiteSpace(url) || !Uri.IsWellFormedUriString(url, UriKind.Absolute)) { return(""); } HttpResponseMessage response = await _client.GetAsync(url); var contentType = response.Content.Headers.ContentType.MediaType; var nameWithExt = name + MimeTypeMap.GetExtension(contentType); using var stream = await response.Content.ReadAsStreamAsync(); return(await _fileWriter.WriteImageAsync(stream, nameWithExt)); }