public IActionResult UploadImageResize(Microsoft.AspNetCore.Http.IFormFile file) { string fileRoute = "wwwroot/uploads/"; var fileMimeType = file.ContentType; string[] ImageMimeTypes = new string[] { "image/gif", "image/jpeg", "audio/mpeg", "image/png", "image/webp" }; if (!ImageMimeTypes.Contains(fileMimeType.ToString())) { return(Json(new Exception("Invalid contentType. It must be Image"))); } MagickGeometry resizeGeometry = new MagickGeometry(300, 300); resizeGeometry.IgnoreAspectRatio = true; FroalaEditor.ImageOptions options = new FroalaEditor.ImageOptions { ResizeGeometry = resizeGeometry }; try { return(Json(FroalaEditor.Image.Upload(HttpContext, fileRoute, options))); } catch (Exception e) { return(Json(e)); } }
public static async Task <byte[]> GetBytes(this Microsoft.AspNetCore.Http.IFormFile formFile) { using (var memoryStream = new MemoryStream()) { await formFile.CopyToAsync(memoryStream); return(memoryStream.ToArray()); } }
public static void CreateLangProfile(HttpContext ctx, Models.Owner owner) { var prof = owner.langProfiles[0]; var path = System.IO.Path.Combine(owner.Path, $"{prof.ProfileName}_{DateTime.Now.ToString("yyyyMMMddHHmmss")}"); var fpath = System.IO.Path.Combine(path, "_langprofile.json"); System.IO.Directory.CreateDirectory(path); string keyidx = ctx.Request.Form["keyidxs"]; var lst = Newtonsoft.Json.JsonConvert.DeserializeObject <List <int> >(keyidx); lst.ForEach(t => { string inputtype = ctx.Request.Form["inptdata" + t.ToString()]; string inputlabel = ctx.Request.Form["inptlabel" + t.ToString()]; if (inputtype == "filesrc") { Microsoft.AspNetCore.Http.IFormFile fll = ctx.Request.Form.Files["uplfile" + t.ToString()]; string llpath = System.IO.Path.Combine(path, "LangData", "upl_File_" + (inputlabel ?? "") + "_" + fll.FileName); if (!System.IO.Directory.Exists(System.IO.Path.GetDirectoryName(llpath))) { System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(llpath)); } using (var stream = new System.IO.FileStream(llpath, System.IO.FileMode.Create)) { fll.CopyTo(stream); } prof.Files.Add(new Models.LabelInput() { Label = inputlabel, FilePath = llpath }); } else if (inputtype == "textsrc") { string txt = ctx.Request.Form["upltext" + t.ToString()]; string llpath = System.IO.Path.Combine(path, "LangData", "upl_Text_" + (inputlabel ?? "") + "_" + Guid.NewGuid().ToString("n").Substring(0, 4) + ".txt"); if (!System.IO.Directory.Exists(System.IO.Path.GetDirectoryName(llpath))) { System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(llpath)); } System.IO.File.WriteAllText(llpath, txt); prof.Files.Add(new Models.LabelInput() { Label = inputlabel, FilePath = llpath }); } }); prof.Path = path; prof.ProfileFilePath = System.IO.Path.Combine(prof.Path, prof.ProfileName + ".bin.gz"); prof.CreatedAt = DateTime.UtcNow; prof.AccessedAt = DateTime.UtcNow; System.IO.File.WriteAllText(fpath, Newtonsoft.Json.JsonConvert.SerializeObject(prof)); }
public string Upload(Microsoft.AspNetCore.Http.IFormFile file, string path = "wwwroot/uploads") { var fileName = DateTime.Now.ToString("yyyyMMddHHmmssff") + Path.GetExtension(file.FileName); var uploadPath = Path.Combine(Directory.GetCurrentDirectory(), path, fileName); using (var stream = new FileStream(uploadPath, FileMode.Create)) { file.CopyTo(stream); } return(fileName); }
public IActionResult AddMultipleUsers(Microsoft.AspNetCore.Http.IFormFile files) { Spreadsheet document = new Spreadsheet(); document.LoadFromFile(files.FileName); Worksheet worksheet = document.Workbook.Worksheets.ByName("Taul1"); int STARTING_ROW = 2; List <UserModel> usersToBeAddedList = new List <UserModel>(); Cell username, password, nimi, sukunimi, osoite, email, employeetype, enabled; while (true) { // Set current cell username = worksheet.Cell(STARTING_ROW, 0); password = worksheet.Cell(STARTING_ROW, 1); nimi = worksheet.Cell(STARTING_ROW, 2); sukunimi = worksheet.Cell(STARTING_ROW, 3); osoite = worksheet.Cell(STARTING_ROW, 4); email = worksheet.Cell(STARTING_ROW, 5); employeetype = worksheet.Cell(STARTING_ROW, 6); enabled = worksheet.Cell(STARTING_ROW, 7); if (username.ValueAsString.Equals("")) { break; } UserModel userModel = new UserModel { Username = username.ValueAsString, Nimi = nimi.ValueAsString, Sukunimi = sukunimi.ValueAsString, Password = password.ValueAsString, Osoite = osoite.ValueAsString, Email = email.ValueAsString, EmployeeType = employeetype.ValueAsString, Enabled = enabled.ValueAsBoolean }; usersToBeAddedList.Add(userModel); STARTING_ROW += 1;//next line } // Close document document.Close(); HttpContext.Session.Set("NewUsersList", usersToBeAddedList); return(View(usersToBeAddedList)); }
public IActionResult UploadFilesManagerValidation(Microsoft.AspNetCore.Http.IFormFile file) { string fileRoute = "wwwroot/"; var fileMimeType = file.ContentType; string[] ImageMimeTypes = new string[] { "image/gif", "image/jpeg", "audio/mpeg", "image/png", "image/webp" }; if (!ImageMimeTypes.Contains(fileMimeType.ToString())) { return(Json(new Exception("Invalid contentType. It must be Image"))); } Func <string, string, bool> validationFunction = (filePath, mimeType) => { long size = new System.IO.FileInfo(filePath).Length; if (size > 10 * 1024 * 1024) { return(false); } MagickImageInfo info = new MagickImageInfo(filePath); if (info.Width != info.Height) { return(false); } return(true); }; FroalaEditor.FileOptions options = new FroalaEditor.FileOptions { Fieldname = "file", Validation = new FroalaEditor.FileValidation(validationFunction) }; try { return(Json(FroalaEditor.Image.Upload(HttpContext, fileRoute, options))); } catch (Exception e) { return(Json(e)); } }
public IActionResult Create(urun urun, IFormFile photo) { urun.eklemetarihi = DateTime.Now; if (photo != null) { var path = Path.Combine(_environment.WebRootPath, "images", photo.FileName); var stream = new FileStream(path, FileMode.Create); photo.CopyTo(stream); resim pht = new resim() { resimAdi = photo.FileName, urunId = urun.urunId }; //urunRepo.saveImage(pht); urun.Resimyolu = photo.FileName; ViewBag.photo = photo.FileName; } urunRepo.Save(urun); return(RedirectToAction("Index", "urun")); }
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Private methods */ /// <summary> /// Execute the configured action for the upload /// </summary> /// <param name="id">Primary key value</param> /// <param name="upload">Posted file</param> /// <returns>File identifier - typically the primary key</returns> private dynamic _actionExec(dynamic id, IFormFile upload) { if (_actionStr == null) { // Custom function return(_actionFn != null? _actionFn(upload, id) : null); } // Default action - move the file to the location specified by the // action string string to = _path(_actionStr, upload.FileName, id); try { #if NETCOREAPP2_1 using (var readStream = upload.OpenReadStream()) { using (var writeStream = new StreamWriter(to)) { readStream.CopyTo(writeStream.BaseStream); } } #else upload.SaveAs(to); #endif } catch (Exception e) { _error = "Error saving file. " + e.Message; return(false); } return(id ?? to); }
/// <summary> /// Add a record to the database for a newly uploaded file /// </summary> /// <param name="editor">Host editor</param> /// <param name="upload">Uploaded file</param> /// <returns>Primary key value for the newly uploaded file</returns> private dynamic _dbExec(Editor editor, IFormFile upload) { var db = editor.Db(); var pathFields = new Dictionary <string, string>(); // Insert the details requested, for the columns requested var q = db.Query("insert") .Table(_dbTable) .Pkey(new [] { _dbPKey }); foreach (var pair in _dbFields) { var column = pair.Key; var prop = pair.Value; #if NETCOREAPP2_1 var contentLength = (int)upload.Length; #else var contentLength = upload.ContentLength; #endif if (prop is DbType) { var propType = (DbType)prop; switch (propType) { case DbType.ReadOnly: break; case DbType.Content: q.Set(column, upload.ToString()); break; case DbType.ContentBinary: byte[] fileData = null; #if NETCOREAPP2_1 var stream = upload.OpenReadStream(); #else var stream = upload.InputStream; #endif using (var binaryReader = new BinaryReader(stream)) { fileData = binaryReader.ReadBytes(contentLength); q.Set(column, fileData); } break; case DbType.ContentType: case DbType.MimeType: q.Set(column, upload.ContentType); break; case DbType.Extn: q.Set(column, Path.GetExtension(upload.FileName)); break; case DbType.FileName: q.Set(column, Path.GetFileName(upload.FileName)); break; case DbType.FileSize: q.Set(column, contentLength); break; case DbType.SystemPath: pathFields.Add(column, "__SYSTEM_PATH__"); q.Set(column, "-"); // Use a temporary value to avoid cases break; // where the db will reject empty values case DbType.WebPath: pathFields.Add(column, "__WEB_PATH__"); q.Set(column, "-"); // Use a temporary value (as above) break; default: throw new Exception("Unknown database type"); } } else { try { // Callable function - execute to get the value var propFn = (Func <Database, IFormFile, dynamic>)prop; pathFields.Add(column, propFn(db, upload)); q.Set(column, "-"); // Use a temporary value (as above) } catch (Exception) { // Not a function, so use the value as it is given pathFields.Add(column, prop.ToString()); q.Set(column, "-"); // Use a temporary value (as above) } } } var res = q.Exec(); var id = res.InsertId(); // Update the newly inserted row with the path information. We have to // use a second statement here as we don't know in advance what the // database schema is and don't want to prescribe that certain triggers // etc be created. It makes it a bit less efficient but much more // compatible if (pathFields.Any()) { // For this to operate the action must be a string, which is // validated in the `exec` method var path = _path(_actionStr, upload.FileName, id); #if NETCOREAPP2_1 var physicalPath = Directory.GetCurrentDirectory() ?? ""; var webPath = physicalPath.Length != 0 ? path.Replace(physicalPath, "") : ""; #else var physicalPath = editor.Request().PhysicalApplicationPath ?? ""; var webPath = physicalPath.Length != 0 ? path.Replace(physicalPath, Path.DirectorySeparatorChar.ToString()) : ""; #endif var pathQ = db .Query("update") .Table(_dbTable) .Where(_dbPKey, id); foreach (var pathField in pathFields) { var val = _path(pathField.Value, upload.FileName, id) .Replace("__SYSTEM_PATH__", path) .Replace("__WEB_PATH__", webPath); pathQ.Set(pathField.Key, val); } pathQ.Exec(); } return(id); }
public ActionResult <DocProof> PutProofDoc(Microsoft.AspNetCore.Http.IFormFile proofDoc, string bindingId, string citizenIdentifier) { var retrunObject = _storage.PutProof(bindingId, citizenIdentifier, proofDoc); return(retrunObject.Result); }
public static async Task <string> ProcessFormFile(Microsoft.AspNetCore.Http.IFormFile formFile, ModelStateDictionary modelState) { var fieldDisplayName = string.Empty; // Use reflection to obtain the display name for the model // property associated with this IFormFile. If a display // name isn't found, error messages simply won't show // a display name. MemberInfo property = typeof(FileUpload).GetProperty( formFile.Name.Substring(formFile.Name.IndexOf(".") + 1)); if (property != null) { var displayAttribute = property.GetCustomAttribute(typeof(DisplayAttribute)) as DisplayAttribute; if (displayAttribute != null) { fieldDisplayName = $"{displayAttribute.Name} "; } } // Use Path.GetFileName to obtain the file name, which will // strip any path information passed as part of the // FileName property. HtmlEncode the result in case it must // be returned in an error message. var fileName = WebUtility.HtmlEncode( Path.GetFileName(formFile.FileName)); if (formFile.ContentType.ToLower() != "text/plain") { modelState.AddModelError(formFile.Name, $"The {fieldDisplayName}file ({fileName}) must be a text file."); } // Check the file length and don't bother attempting to // read it if the file contains no content. This check // doesn't catch files that only have a BOM as their // content, so a content length check is made later after // reading the file's content to catch a file that only // contains a BOM. if (formFile.Length == 0) { modelState.AddModelError(formFile.Name, $"The {fieldDisplayName}file ({fileName}) is empty."); } else if (formFile.Length > 1048576) { modelState.AddModelError(formFile.Name, $"The {fieldDisplayName}file ({fileName}) exceeds 1 MB."); } else { try { string fileContents; // The StreamReader is created to read files that are UTF-8 encoded. // If uploads require some other encoding, provide the encoding in the // using statement. To change to 32-bit encoding, change // new UTF8Encoding(...) to new UTF32Encoding(). using ( var reader = new StreamReader( formFile.OpenReadStream(), new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true), detectEncodingFromByteOrderMarks: true)) { fileContents = await reader.ReadToEndAsync(); // Check the content length in case the file's only // content was a BOM and the content is actually // empty after removing the BOM. if (fileContents.Length > 0) { return(fileContents); } else { modelState.AddModelError(formFile.Name, $"The {fieldDisplayName}file ({fileName}) is empty."); } } } catch (Exception ex) { modelState.AddModelError(formFile.Name, $"The {fieldDisplayName}file ({fileName}) upload failed. " + $"Please contact the Help Desk for support. Error: {ex.Message}"); // Log the exception } } return(string.Empty); }
async public Task <DocProof> PutProof(string bindingId, string citizenIdentifier, Microsoft.AspNetCore.Http.IFormFile proofDocs = null) { //create storage container and set permissions CloudBlobContainer container = blobClient.GetContainerReference(bindingId); await container.CreateIfNotExistsAsync(); BlobContainerPermissions permissions = new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Off }; await container.SetPermissionsAsync(permissions); CloudBlockBlob blockBlob = container.GetBlockBlobReference(citizenIdentifier); // string fileString = ""; byte[] fileHash = null; using (var fileStream = proofDocs.OpenReadStream()) { await blockBlob.UploadFromStreamAsync(fileStream); fileStream.Seek(0, SeekOrigin.Begin); using (var md5 = MD5.Create()) { fileHash = md5.ComputeHash(fileStream); } } var storedProofDocs = new DocProof() { Container = bindingId, ContentType = proofDocs.ContentType, FileName = citizenIdentifier, Hash = GetHash(bindingId, Encoding.UTF8.GetString(fileHash)), StorageSharding = "none" }; //Update profile with proof document info //Should be controlled by Application -- Commented by DB //await UpdateProofDocument(bindingId, storedProofDocs, "The Proof document was proven and stored"); return(await Task.Run(() => storedProofDocs)); }
public void Post([FromForm] string value, Microsoft.AspNetCore.Http.IFormFile file) { }