public string UploadAvatar(IFormFile file, string key) { if (file.Length >= 300000) throw new Exception("Uploaded image may not exceed 300 kb, please upload a smaller image."); try { using (var readStream = file.OpenReadStream()) { using (var img = Image.FromStream(readStream)) { if (!img.RawFormat.Equals(ImageFormat.Jpeg) && !img.RawFormat.Equals(ImageFormat.Png)) throw new Exception("Uploaded file is not recognized as an image."); var tempFile = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); try { ImageBuilder.Current.Build(img, tempFile, new Instructions { Width = 150, Height = 150, Format = "jpg", Mode = FitMode.Max }); var avatar = _avatarDirectoryInfo.GetFile(key + ".jpg"); if (avatar.Exists) avatar.Delete(); avatar.Open(FileMode.Create, stream => { using (var imageStream = File.OpenRead(tempFile)) imageStream.CopyTo(stream); }); } catch (Exception ex) { throw new Exception("Uploaded file is not recognized as a valid image.", ex); } finally { if (File.Exists(tempFile)) File.Delete(tempFile); } return key; } } } catch (Exception) { throw new Exception("Uploaded file is not recognized as an image."); } }
public async Task<IActionResult> Index(IFormFile photo, string query, string lat, string lng) { if (photo != null) { Notez note = new Notez { Found = true, Timestamp = DateTimeOffset.Now, UserAgent = Request.Headers["User-Agent"], HostAddress = Context.GetFeature<IHttpConnectionFeature>().RemoteIpAddress.ToString(), LocationRaw = query, }; if (!string.IsNullOrWhiteSpace(query) && (string.IsNullOrWhiteSpace(lat) || string.IsNullOrWhiteSpace(lng))) { using (HttpClient http = new HttpClient()) { Stream response = await http.GetStreamAsync("http://maps.googleapis.com/maps/api/geocode/xml?address=" + Uri.EscapeDataString(query)); XDocument xml = XDocument.Load(response); if (xml.Root.Element("status")?.Value == "OK") { XElement location = xml.Root.Element("result")?.Element("geometry")?.Element("location"); lat = location?.Element("lat")?.Value; lng = location?.Element("lng")?.Value; } } } double value; if (double.TryParse(lat, NumberStyles.Float, CultureInfo.InvariantCulture, out value)) note.Latitude = value; if (double.TryParse(lng, NumberStyles.Float, CultureInfo.InvariantCulture, out value)) note.Longitude = value; _context.Notez.Add(note); await _context.SaveChangesAsync(); string root = Path.Combine(_environment.MapPath("n")); await photo.SaveAsAsync(Path.Combine(root, note.ID + ".jpg")); try { using (Stream s = photo.OpenReadStream()) Helper.GenerateThumbnail(s, Path.Combine(root, "t" + note.ID + ".jpg")); } catch { note.FlagStatus = FlagStatus.Invalid; await _context.SaveChangesAsync(); } return RedirectToAction(nameof(Thanks), new { noteID = note.ID }); } return RedirectToAction(nameof(Index)); }
public async Task<ImageUploadResult> SaveImage(IFormFile file) { IImage image; using (var fileStram = file.OpenReadStream()) { var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Replace("\"", string.Empty); string imageName = Guid.NewGuid() + Path.GetExtension(fileName); image = _imageFactory.CreateImage(imageName, fileStram); } await _imageRespository.SaveImageAsync(image); string imageUrl = _imageUrlProvider.GetImageUrl(image.Name); return new ImageUploadResult(imageUrl, image.Name); }
public async Task StoreFileAsync(string fileName, IFormFile formFile, bool overwrite = false) { var filePath = GetAbsoluteFilePath(fileName); if (File.Exists(filePath) && !overwrite) { throw new Exception("File already exists"); } await formFile.SaveAsAsync(filePath); }
public IActionResult Import(IFormFile file) { var src = new List<RxLevPoint>(); var fname = Guid.NewGuid().ToString().Replace("-", "") + System.IO.Path.GetExtension(file.GetFileName()); var path = System.IO.Path.Combine(System.IO.Path.GetTempPath(), fname); file.SaveAs(path); string connStr; if (System.IO.Path.GetExtension(path) == ".xls") connStr = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + path + ";" + ";Extended Properties=\"Excel 8.0;HDR=NO;IMEX=1\""; else connStr = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + path + ";" + ";Extended Properties=\"Excel 12.0;HDR=NO;IMEX=1\""; using (var conn = new OleDbConnection(connStr)) { conn.Open(); var schemaTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" }); var rows = schemaTable.Rows; foreach (System.Data.DataRow r in rows) { if (r["TABLE_NAME"].ToString() == "_xlnm#_FilterDatabase") continue; var cmd = new OleDbCommand($"select * from [{r["TABLE_NAME"].ToString()}]", conn); var reader = cmd.ExecuteReader(); var flag = reader.Read(); var cities = User.Claims.Where(x => x.Type == "有权限访问地市数据").Select(x => x.Value).ToList(); if (flag) { while (reader.Read()) { try { src.Add(new RxLevPoint { Lon = Convert.ToDouble(reader[0]), Lat = Convert.ToDouble(reader[1]), Signal = Convert.ToInt32(reader[2]) }); } catch { } } } } } var ret = Algorithms.p2l.Handle(src); DB.RxLevLines.AddRange(ret); DB.SaveChanges(); return Prompt(x => { x.Title = "导入成功"; x.Details = "RxLev信息导入成功"; }); }
public IActionResult Upload(IFormFile file) { if (!User.IsSignedIn()) return Json(new { code = 403, msg = "Forbidden" }); if (file == null) return Json(new { code = 400, msg = "File not found" }); var _file = new Blob(); _file.FileName = file.GetFileName(); _file.Time = DateTime.Now; _file.Id = Guid.NewGuid(); _file.ContentLength = file.Length; _file.ContentType = file.ContentType; _file.File = file.ReadAllBytes(); DB.Blobs.Add(_file); DB.SaveChanges(); return Json(new { code = 200, fileId = _file.Id.ToString() }); }
public async Task<IActionResult> Create(News news, IFormFile uploadFile) { if (ModelState.IsValid) { string fileName = Configurations.DefaultFileName; if (uploadFile != null) { //Image uploading string uploads = Path.Combine(_environment.WebRootPath, Configurations.NewsImageStockagePath); fileName = Guid.NewGuid().ToString() + "_" + ContentDispositionHeaderValue.Parse(uploadFile.ContentDisposition).FileName.Trim('"'); await uploadFile.SaveImageAsAsync(Path.Combine(uploads, fileName)); } //Setting value for creation news.Id = Guid.NewGuid(); news.DateOfPublication = DateTime.Now; news.ImageLink = Path.Combine(Configurations.NewsImageStockagePath,fileName); //TODO Get logged in User and add it to the news StolonsUser user = await GetCurrentStolonsUserAsync(); news.User = user; _context.News.Add(news); _context.SaveChanges(); return RedirectToAction("Index"); } return View(news); }
public async Task UploadDocumentAsync(IFormFile file) { using (var fileStream = new FileStream(Path.Combine(_documentUploadConfiguration.UploadPath, file.FileName), FileMode.Create)) { await file.CopyToAsync(fileStream); } }
public async Task<IActionResult> Create([Bind] Participant partner, IFormFile image) { if (this.ModelState.IsValid) { var uploads = Path.Combine(this.environment.WebRootPath, "uploads/participants"); if (!Directory.Exists(uploads)) { Directory.CreateDirectory(uploads); } if (image.Length > 0) { var fileName = $"{Guid.NewGuid()}.{image.FileName}"; using (var fileStream = new FileStream(Path.Combine(uploads, fileName), FileMode.Create)) { await image.CopyToAsync(fileStream); partner.ImgPath = $"/uploads/participants/{fileName}"; } } this.context.Add(partner); await this.context.SaveChangesAsync(); return this.RedirectToAction("Index"); } return this.View(partner); }
public async Task<IActionResult> Create(IFormFile croppedImage1, IFormFile croppedImage2, int distance) { var uploads = Path.Combine(_environment.WebRootPath, "Uploads"); if (croppedImage1.Length > 0 && croppedImage2.Length > 0) { var puzzleImageId = Guid.NewGuid().ToString(); var fileName = string.Format("{0}.jpg", puzzleImageId); await croppedImage1.SaveAsAsync(Path.Combine(uploads, fileName)); ImageResizer.ImageJob img1 = new ImageResizer.ImageJob(Path.Combine(uploads, fileName), Path.Combine(uploads, "16-9", "400", fileName), new ImageResizer.Instructions("maxheight=400;&scale=both;format=jpg;mode=max")); img1.Build(); ImageResizer.ImageJob img2 = new ImageResizer.ImageJob(Path.Combine(uploads, fileName), Path.Combine(uploads, "16-9", "1065", fileName), new ImageResizer.Instructions("maxheight=1065;&scale=both;format=jpg;mode=max")); img2.Build(); if (ModelState.IsValid) { await _puzzleRepository.AddPuzzleAsync(User, puzzleImageId, distance, _shopRepository.GetUserShop(User).ID); } } return View(); }
public async Task<string> UpdateLogoAsync(int? clubId, IFormFile file) { string path = string.Empty; if (clubId.HasValue) { path = await _clubService.GetNameAsync(clubId.Value); } var relativePath = path; if (string.IsNullOrEmpty(path) || !path.Contains(LogoPath)) { var newName = (string.IsNullOrWhiteSpace(path) ? GenerateNewName() : path) + "." + file.FileName.Split('.').Last(); var newPath = GenerateNewPath(LogoPath); relativePath = Path.Combine(newPath, newName); path = GetFullPath(relativePath); } else { path = GetFullPath(path); } file.CopyTo(new FileStream(path, FileMode.Create)); relativePath = Regex.Replace(relativePath, "\\\\", "/"); if (clubId.HasValue) { await _clubService.UpdateLogoAsync(clubId.Value, relativePath); } return relativePath; }
public async Task<IActionResult> Upload(IFormFile file, string userId) { var fileId = await _fileHandler.HandleUpload(file); await _userHandler.AddFileToUserMapping(userId, fileId); return View(); }
public async Task<ActionResult> CkeditorUploadImage(IFormFile upload, string CKEditorFuncNum, string CKEditor) { string fileName = ContentDispositionHeaderValue.Parse(upload.ContentDisposition).FileName.Trim('"'); string format = fileName.Split(".".ToCharArray())[1]; string newFileName = DateTime.Now.ToString("ddMMyyyyhhmmssffff") + "." + format; string path = this._environment.WebRootPath + @"\img\" + newFileName; await upload.SaveAsAsync(path); string baseUrl = Request.Scheme+"://"+Request.Host.Value; return this.Content("<script language='javascript' type = 'text/javascript'> window.parent.CKEDITOR.tools.callFunction(" + CKEditorFuncNum + ", '" + baseUrl + @"/img/" + newFileName + "', '');</script>", "text/html"); }
public static string GetImageExtension(IFormFile imageFile) { switch (imageFile.ContentType)// Accept only png, bmp, jpeg, jpg file { case "image/png": return ".png"; case "image/bmp": return ".bmp"; case "image/jpeg": return ".jpg"; } return null; }
public async Task<IActionResult> Create(int campaignId, ActivityDetailModel activity, IFormFile fileUpload) { if (activity.EndDateTime < activity.StartDateTime) { ModelState.AddModelError(nameof(activity.EndDateTime), "End date cannot be earlier than the start date"); } CampaignSummaryModel campaign = _bus.Send(new CampaignSummaryQuery { CampaignId = campaignId }); if (campaign == null || !User.IsOrganizationAdmin(campaign.OrganizationId)) { return HttpUnauthorized(); } if (activity.StartDateTime < campaign.StartDate) { ModelState.AddModelError(nameof(activity.StartDateTime), "Start date cannot be earlier than the campaign start date " + campaign.StartDate.ToString("d")); } if (activity.EndDateTime > campaign.EndDate) { ModelState.AddModelError(nameof(activity.EndDateTime), "End date cannot be later than the campaign end date " + campaign.EndDate.ToString("d")); } if (ModelState.IsValid) { if (fileUpload != null) { if (!fileUpload.IsAcceptableImageContentType()) { ModelState.AddModelError("ImageUrl", "You must upload a valid image file for the logo (.jpg, .png, .gif)"); return View("Edit", activity); } } activity.OrganizationId = campaign.OrganizationId; var id = _bus.Send(new EditActivityCommand { Activity = activity }); if (fileUpload != null) { // resave now that activty has the ImageUrl activity.Id = id; activity.ImageUrl = await _imageService.UploadActivityImageAsync(campaign.OrganizationId, id, fileUpload); _bus.Send(new EditActivityCommand { Activity = activity }); } return RedirectToAction("Details", "Activity", new { area = "Admin", id = id }); } return View("Edit", activity); }
private async Task<string> UploadImageAsync(string blobPath, IFormFile image) { //Get filename var fileName = (ContentDispositionHeaderValue.Parse(image.ContentDisposition).FileName).Trim('"').ToLower(); Debug.WriteLine(string.Format("BlobPath={0}, fileName={1}, image length={2}", blobPath, fileName, image.Length.ToString())); if (fileName.EndsWith(".jpg") || fileName.EndsWith(".jpeg") || fileName.EndsWith(".png")) { string storageConnectionString = _config["Data:Storage:AzureStorage"]; CloudStorageAccount account = CloudStorageAccount.Parse(storageConnectionString); CloudBlobContainer container = account.CreateCloudBlobClient().GetContainerReference(CONTAINER_NAME); //Create container if it doesn't exist wiht public access await container.CreateIfNotExistsAsync(BlobContainerPublicAccessType.Container, new BlobRequestOptions(), new OperationContext()); string blob = blobPath + "/" + fileName; Debug.WriteLine("blob" + blob); CloudBlockBlob blockBlob = container.GetBlockBlobReference(blob); blockBlob.Properties.ContentType = image.ContentType; using (var imageStream = image.OpenReadStream()) { //Option #1 byte[] contents = new byte[image.Length]; for (int i = 0; i < image.Length; i++) { contents[i] = (byte)imageStream.ReadByte(); } await blockBlob.UploadFromByteArrayAsync(contents, 0, (int)image.Length); //Option #2 //await blockBlob.UploadFromStreamAsync(imageStream); } Debug.WriteLine("Image uploaded to URI: " + blockBlob.Uri.ToString()); return blockBlob.Uri.ToString(); } else { throw new Exception("Invalid file extension: " + fileName + "You can only upload images with the extension: jpg, jpeg, or png"); } }
public GenericResponseVM PerformContentCheck(string clientUrl, string folderUrl, IFormFile uploadedFile, string fileName) { GenericResponseVM genericResponse = null; ClientContext clientContext = spoAuthorization.GetClientContext(clientUrl); using (MemoryStream targetStream = new MemoryStream()) { Stream sourceStream = uploadedFile.OpenReadStream(); try { byte[] buffer = new byte[sourceStream.Length + 1]; int read = 0; while ((read = sourceStream.Read(buffer, 0, buffer.Length)) > 0) { targetStream.Write(buffer, 0, read); } string serverFileUrl = folderUrl + ServiceConstants.FORWARD_SLASH + fileName; bool isMatched = documentRepository.PerformContentCheck(clientContext, targetStream, serverFileUrl); if (isMatched) { //listResponse.Add(string.Format(CultureInfo.InvariantCulture, "{0}{1}{1}{1}{2}", ConstantStrings.FoundIdenticalContent, ConstantStrings.Pipe, ConstantStrings.TRUE)); genericResponse = new GenericResponseVM() { IsError = true, Code = UploadEnums.IdenticalContent.ToString(), Value = string.Format(CultureInfo.InvariantCulture, errorSettings.FoundIdenticalContent) }; } else { genericResponse = new GenericResponseVM() { IsError = true, Code = UploadEnums.NonIdenticalContent.ToString(), Value = string.Format(CultureInfo.InvariantCulture, errorSettings.FoundNonIdenticalContent) }; } } catch (Exception exception) { //Logger.LogError(exception, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, UIConstantStrings.LogTableName); //response = string.Format(CultureInfo.InvariantCulture, "{0}{1}{1}{1}{2}", ConstantStrings.ContentCheckFailed, ConstantStrings.Pipe, ConstantStrings.TRUE); } finally { sourceStream.Dispose(); } } return genericResponse; }
public IActionResult UpdateDocumentAndStatus(IFormFile document) { try { if (document == null) { return HttpBadRequest(); } return Ok(); } catch (Exception ex) { return HttpBadRequest(); } }
public async Task Post(string name, IFormFile file) { var beer = new Beer { Name = name }; if (file != null) { var filename = ContentDispositionHeaderValue .Parse(file.ContentDisposition) .FileName .Trim('"'); beer.Picture = "http://localhost:5000/Images/" + filename; await file.SaveAsAsync("C:\\Code\\personal\\app-to-app-uwp\\Inventory.API\\wwwroot\\Images\\" + filename); } beers.Add(beer); }
internal string StoreXmlInCloud(SINner chummerFile, IFormFile uploadedFile) { string url = "default"; try { _logger.LogTrace("Storing " + uploadedFile.FileName + " to GDrive..."); UserCredential creds = AuthorizeGoogleUser(); if (creds == null) { throw new Exception("Invalid Google User"); } // Create Drive API service. BaseClientService.Initializer initializer = new BaseClientService.Initializer() { HttpClientInitializer = (IConfigurableHttpClientInitializer)creds, ApplicationName = "SINners", GZipEnabled = true, }; CancellationToken cancellationToken = new CancellationToken(); // Create Drive API service. var service = new DriveService(initializer); if (String.IsNullOrEmpty(_folderId)) { Google.Apis.Drive.v3.Data.File fileMetadata = new Google.Apis.Drive.v3.Data.File(); fileMetadata.Name = "Chummer"; fileMetadata.MimeType = "application/vnd.google-apps.folder"; var folderid = service.Files.Create(fileMetadata).Execute(); string msg = "ChummerFolderId: " + folderid.Id; _logger.LogCritical(msg); throw new HubException("HubException: " + msg); } if (String.IsNullOrEmpty(chummerFile.GoogleDriveFileId)) { chummerFile.DownloadUrl = UploadFileToDrive(service, uploadedFile, _contentType, chummerFile); } else { chummerFile.DownloadUrl = UpdateFileToDrive(service, uploadedFile, _contentType, chummerFile); } // Define parameters of request. FilesResource.ListRequest listRequest = service.Files.List(); listRequest.PageSize = 10; listRequest.Q = "'" + _folderId + "' in parents"; listRequest.Fields = "nextPageToken, files(id, name, webContentLink)"; // List files. IList <Google.Apis.Drive.v3.Data.File> files = listRequest.Execute() .Files; url = "Folder " + _folderId + ":" + Environment.NewLine; if (files != null && files.Count > 0) { foreach (var file in files) { url += String.Format("{0} ({1}): {2}", file.Name, file.Id, file.WebContentLink) + Environment.NewLine; } } else { url += " No files found."; } // Define parameters of request. listRequest = service.Files.List(); listRequest.PageSize = 10; listRequest.Fields = "nextPageToken, files(id, name, webContentLink)"; // List files. files = listRequest.Execute() .Files; url = "ParentFolder: " + Environment.NewLine; if (files != null && files.Count > 0) { foreach (var file in files) { url += String.Format("{0} ({1}): {2}", file.Name, file.Id, file.WebContentLink) + Environment.NewLine; } } else { url += "No files found."; } //_logger.LogError("ParentUrl: " + url); } catch (Exception e) { _logger.LogError("Could not store file on GDrive: " + e.ToString()); throw; } return(chummerFile.DownloadUrl); }
// Upload Image,File To Existing Folder public static string SaveFile(IFormFile formFile, string FristName) { Dictionary <string, string> temp = new Dictionary <string, string>(); List <string> _extentions = new List <string>() { ".PNG", ".JPG", ".JPEG", ".BMP", ".GIF", //etc ".WAV", ".MID", ".MIDI", ".WMA", ".MP3", ".OGG", ".RMA", //etc ".AVI", ".MP4", ".DIVX", ".WMV" }; try { var file = formFile; var folderName = Path.Combine("UploadFiles"); // Check if directory exist or not if (!Directory.Exists(folderName)) { Directory.CreateDirectory(folderName); } var pathToSave = Path.Combine(Directory.GetCurrentDirectory(), folderName); if (file.Length > 0) { string fileName = Path.GetFileNameWithoutExtension(file.FileName); //var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"'); var _imgname = FristName + DateTime.Now.Ticks; // check valid extension //#region check size string extension = Path.GetExtension(file.FileName); ////extension= extension.Substring(1, extension.Length-1); //var size = file.Length; //if (!_extentions.Contains(extension.ToUpper())) //{ // temp.Add("dbPath", ""); // temp.Add("_ext", ""); // temp.Add("stat", "File extension is not valid."); // //return new {path="",extention="",state= "File extension is not valid." }; // return "!!امتداد الملف غير صحيح"; //} ////if (size > (1000 * 1024 * 1024)) //// return "حجم الملف اكبر من 5 ميجا بايت" ; //#endregion // Updated To GetFileName By Elgendy var _ext = Path.GetFileNameWithoutExtension(file.FileName); // var fullPath = Path.Combine(pathToSave, _imgname +_ext); var filepath = Path.Combine(folderName, _imgname + extension); using (var stream = new FileStream(filepath, FileMode.Create)) { file.CopyTo(stream); } //string dbPath = "http://localhost:52023/UploadFiles/" + _imgname + extension; string dbPath = "http://lookandgo-001-site1.dtempurl.com/UploadFiles/" + _imgname + extension; temp.Add("dbPath", dbPath); temp.Add("_ext", _ext); temp.Add("stat", "done"); //return new { path = dbPath, extention = _ext, state = "done." }; return(dbPath); } else { temp.Add("dbPath", ""); temp.Add("_ext", ""); temp.Add("stat", "BadRequest"); //return new { path = "", extention = "", state = "BadRequest" }; return("BadRequest"); } } catch (Exception ex) { temp.Add("dbPath", ""); temp.Add("_ext", ""); temp.Add("stat", "Internal server error" + ex.ToString()); //return new { path = "", extention = "", state = "Internal server error" + ex.ToString() }; return($"خطا في السيرفر : {ex.Message}"); } }
public ActionResult FileUpload(IFormFile files) { String FileExt = System.IO.Path.GetExtension(files.FileName).ToUpper(); if (FileExt == ".PDF") { if (string.IsNullOrWhiteSpace(_environment.WebRootPath)) { _environment.WebRootPath = System.IO.Path.Combine(Directory.GetCurrentDirectory(), "wwwroot"); } var uploads = System.IO.Path.Combine(_environment.WebRootPath, "Files"); if (!System.IO.Directory.Exists(uploads)) { System.IO.Directory.CreateDirectory(uploads); } if (files.Length > 0) { var filePath = System.IO.Path.Combine(uploads, files.FileName); using (var FileStremUploaded = new FileStream(filePath, FileMode.Create)) { files.CopyTo(FileStremUploaded); } } Stream fileStream = files.OpenReadStream(); var mStreamer = new MemoryStream(1000 * 1024); mStreamer.SetLength(fileStream.Length); fileStream.Read(mStreamer.GetBuffer(), 0, (int)fileStream.Length); mStreamer.Seek(0, SeekOrigin.Begin); byte[] bytes = mStreamer.GetBuffer(); FileStream fs = new FileStream(files.FileName, FileMode.Append, FileAccess.Write); using (MemoryStream inputData = new MemoryStream(bytes)) { using (MemoryStream outputData = new MemoryStream()) { iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(bytes, password); var font = BaseFont.CreateFont(BaseFont.TIMES_BOLD, BaseFont.WINANSI, BaseFont.EMBEDDED); byte[] watemarkedbytes = AddWatermark(bytes, font); iTextSharp.text.pdf.PdfReader awatemarkreader = new iTextSharp.text.pdf.PdfReader(watemarkedbytes, password); FileDetailsModel Fd = new Models.FileDetailsModel(); PdfEncryptor.Encrypt(awatemarkreader, outputData, true, "123456", "123456", PdfWriter.ALLOW_MODIFY_CONTENTS); bytes = outputData.ToArray(); return(File(bytes, "application/pdf")); } } } else { ViewBag.FileStatus = "Invalid file format."; return(View()); } }
private async Task <string> SaveFileGeneral(IFormFile file, string bucket, string folder, bool isPublic) { //Your code here; throw new NotImplementedException(); }
public async Task <bool> CreatePost(string title, string content, IFormFile img, int UserId) { try { string folderRoot = "temp"; string nameImg = ""; string routeImg = ""; int validateFolder = 0; while (validateFolder == 0) { if (!Directory.Exists(folderRoot)) { DirectoryInfo di = Directory.CreateDirectory(folderRoot); DirectoryInfo dInfo = new DirectoryInfo(folderRoot); DirectorySecurity dSecurity = dInfo.GetAccessControl(); dSecurity.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), FileSystemRights.FullControl, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.NoPropagateInherit, AccessControlType.Allow)); dInfo.SetAccessControl(dSecurity); validateFolder = 0; } else { string folderUser = Path.Combine(folderRoot, UserId.ToString()); int validateFolder2 = 0; while (validateFolder2 == 0) { if (!Directory.Exists(folderUser)) { DirectoryInfo di = Directory.CreateDirectory(folderUser); DirectoryInfo dInfo = new DirectoryInfo(folderUser); DirectorySecurity dSecurity = dInfo.GetAccessControl(); dSecurity.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), FileSystemRights.FullControl, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.NoPropagateInherit, AccessControlType.Allow)); dInfo.SetAccessControl(dSecurity); validateFolder2 = 0; } else { validateFolder2 = 1; } } int countPosts = usersContext_.Posts.Where(i => i.UserId == UserId).Count(); nameImg = "id" + countPosts + "-" + img.FileName; routeImg = Path.Combine(folderRoot, UserId.ToString(), nameImg); using (var stream = new FileStream(routeImg, FileMode.Create, FileAccess.ReadWrite)) { img.CopyTo(stream); } validateFolder = 1; } } byte[] imgArray = File.ReadAllBytes(routeImg); string base64 = Convert.ToBase64String(imgArray); string extImg = Path.GetExtension(routeImg); Posts post = new Posts(); post.Title = title; post.Content = content; post.CreationDate = DateTime.Now; post.UserId = UserId; post.Img = routeImg; post.BytesImg = base64; post.ExtImg = extImg; string bucketName = "bucketuserid" + UserId; var putRequest = new PutObjectRequest() { BucketName = bucketName, Key = nameImg, InputStream = img.OpenReadStream(), ContentType = img.ContentType }; var result = await client_.PutObjectAsync(putRequest); usersContext_.Posts.Add(post); int response = usersContext_.SaveChanges(); if (response > 0) { return(true); } else { return(false); } } catch (Exception ex) { return(false); } }
public async Task <CommandResult> ExecuteAsync(int storeId, IFormFile file) { try { if (file == null) { return(CommandResult.Failed(new CommandResultError() { Code = (int)HttpStatusCode.NotAcceptable, Description = "File is null" })); } if (file.Length > 4000000) { return(CommandResult.Failed(new CommandResultError() { Code = (int)HttpStatusCode.NotAcceptable, Description = "File size must less than 4Mb" })); } if (!file.ContentType.Contains("image/")) { return(CommandResult.Failed(new CommandResultError() { Code = (int)HttpStatusCode.NotAcceptable, Description = "File not support" })); } var names = file.FileName.Split('.'); var fileExtend = names[names.Length - 1]; byte[] fileContent; using (Stream stream = file.OpenReadStream()) { using (var binaryReader = new BinaryReader(stream)) { fileContent = binaryReader.ReadBytes((int)file.Length); } } CsmsStore entity = await _storeRepository.GetByIdAsync(storeId) ?? new CsmsStore(); entity.PhotoSize = file.Length.ToString(); entity.PhotoType = file.ContentType; entity.Photo = fileContent; entity.PhotoName = DateTime.Now.ToString(DateFormat.DateTimeFormatyyyyMMdd_hhmmss) + "." + fileExtend; if (entity.StoreId == 0) { entity.StoreId = storeId; await _storeRepository.InsertAsync(entity); } else { await _storeRepository.UpdateAsync(entity); } return(CommandResult.Success); } catch (Exception) { return(CommandResult.Failed(new CommandResultError() { Code = (int)HttpStatusCode.InternalServerError, Description = Message.InternalServerError })); } }
public async Task <IActionResult> Create([Bind("Id,Name,Surname,Phone,Phone2,Email,Address,Agency,Description,FacebookLink,InstagramLink,TwitterLink,ImagePath,CreatedDate")] Agent agent, IFormFile image) { if (ModelState.IsValid) { var ext = Path.GetExtension(image.FileName); string purePath = $"agent-{Guid.NewGuid()}{ext}"; string fileName = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "uploads", purePath); using (var fs = new FileStream(fileName, FileMode.CreateNew, FileAccess.Write)) { image.CopyTo(fs); } agent.ImagePath = purePath; _context.Add(agent); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } return(View(agent)); }
//[Route("{controller}/products/edit")] public async Task <IActionResult> EditProduct([Bind("ProductID,ProductName,Quantity,Price,Category,Description,ProductImage")] Product product, IFormFile ProductImage) { if (ModelState.IsValid) { if (product.ProductID == 0) { if (ProductImage != null) { if (ProductImage.Length > 0) //Convert Image to byte and save to database { byte[] p1 = null; using (var fs1 = ProductImage.OpenReadStream()) using (var ms1 = new MemoryStream()) { fs1.CopyTo(ms1); p1 = ms1.ToArray(); } product.ProductImage = p1; } await _productsRepository.Add(product); return(RedirectToAction("Products", "Admin")); } } else if (product.ProductID != 0) { if (ProductImage != null) { if (ProductImage.Length > 0) //Convert Image to byte and save to database { byte[] p1 = null; using (var fs1 = ProductImage.OpenReadStream()) using (var ms1 = new MemoryStream()) { fs1.CopyTo(ms1); p1 = ms1.ToArray(); } product.ProductImage = p1; } } await _productsRepository.Update(product); return(RedirectToAction("Products", "Admin")); } else { return(RedirectToAction("Products", "Admin")); } return(RedirectToAction("Products", "Admin")); } return(RedirectToAction("Products", "Admin")); }
public IActionResult Post(IFormFile file) { IEnumerable <MetricsEntryResult> results = _metricService.RunMetricsCheck(file.OpenReadStream()); return(Ok(results)); }
public async Task <IActionResult> UploadOneFile([FromForm] IFormFile file) { FileDetailVO detail = await _fileBusiness.SaveFileToDisk(file); return(new OkObjectResult(detail)); }
public static bool IsImage(this IFormFile Image) { return(Image == null || Image.ContentType.Contains("image/") || Image.Length / 1024 / 1024 > 2); }
public Uri ArmazenarFotoDoPost(IFormFile foto) { throw new NotImplementedException(); }
public Task <Uri> ArmazenarFotoDePerfil(IFormFile foto) { throw new NotImplementedException(); }
public ActionResult Import() { IFormFile file = Request.Form.Files[0]; string folderName = "UploadExcel"; string webRootPath = _hostingEnvironment.WebRootPath; string newPath = Path.Combine(webRootPath, folderName); StringBuilder sb = new StringBuilder(); if (!Directory.Exists(newPath)) { Directory.CreateDirectory(newPath); } if (file.Length > 0) { string sFileExtension = Path.GetExtension(file.FileName).ToLower(); ISheet sheet; string fullPath = Path.Combine(newPath, file.FileName); using (var stream = new FileStream(fullPath, FileMode.Create)) { file.CopyTo(stream); stream.Position = 0; if (sFileExtension == ".xls") { HSSFWorkbook hssfwb = new HSSFWorkbook(stream); //This will read the Excel 97-2000 formats sheet = hssfwb.GetSheetAt(0); //get first sheet from workbook for (int r = 0; r < sheet.LastRowNum; r++) { var row = sheet.GetRow(r); var employee = new Employee(); employee.ID = int.Parse(row.GetCell(0).ToString()); employee.ProjectID = int.Parse(row.GetCell(1).ToString()); employee.DateFrom = DateTime.Parse(row.GetCell(2).ToString()); employee.DateTo = DateTime.Parse(row.GetCell(3).ToString()); employees.Add(employee); } } else { XSSFWorkbook hssfwb = new XSSFWorkbook(stream); //This will read 2007 Excel format sheet = hssfwb.GetSheetAt(0); //get first sheet from workbook for (int r = 0; r < sheet.LastRowNum; r++) { var row = sheet.GetRow(r); var employee = new Employee(); employee.ID = int.Parse(row.GetCell(0).ToString()); employee.ProjectID = int.Parse(row.GetCell(1).ToString()); employee.DateFrom = DateTime.Parse(row.GetCell(2).ToString()); employee.DateTo = DateTime.Parse(row.GetCell(3).ToString()); employees.Add(employee); } } IRow headerRow = sheet.GetRow(0); //Get Header Row int cellCount = headerRow.LastCellNum; sb.Append("<table class='table table-bordered'><tr>"); for (int j = 0; j < cellCount; j++) { NPOI.SS.UserModel.ICell cell = headerRow.GetCell(j); if (cell == null || string.IsNullOrWhiteSpace(cell.ToString())) { continue; } sb.Append("<th>" + cell.ToString() + "</th>"); } sb.Append("</tr>"); sb.AppendLine("<tr>"); for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++) //Read Excel File { IRow row = sheet.GetRow(i); if (row == null) { continue; } if (row.Cells.All(d => d.CellType == CellType.Blank)) { continue; } for (int j = row.FirstCellNum; j < cellCount; j++) { if (row.GetCell(j) != null) { sb.Append("<td>" + row.GetCell(j).ToString() + "</td>"); } } sb.AppendLine("</tr>"); } sb.Append("</table>"); } } return(this.Content(sb.ToString())); }
//private string CheckCustomerCode(string customer_type) //{ // QueryParam Query = new QueryParam // { // Fields = "*", // Table = "tbl_customer_type", // Where = new List<ConditionParameter> // { // Condition("customer_type",customer_type) // } // }; // CustomerType CustomerTypeModel = NewRepo.Find<CustomerType>(Query); // if (CustomerTypeModel.customer_type== "VENDOR") { } //} public IActionResult Upload(IFormFile File, int rate_type) { Data = new List <ModelParameter>(); if (Path.GetExtension(File.FileName).ToLower() != ".csv") { return(new CustomResult("success", new CustomResponse { key_code = "0", status = "300", msg = "error:Only Csv File Allowed" })); } string[] param = File.FileName.Split('_'); if (param.Count() != 2) { return(new CustomResult("success", new CustomResponse { key_code = "0", status = "300", msg = "error:Wrong FileName Format" })); } string DirectoryPath = FileHelper.FileServerPath(); FileHelper.CreateDirectory(FileHelper.FileServerPath()); ImportFile ImportFileModel = new ImportFile { file_name = File.FileName, process_name = "purchase_rate", new_file_path = FileHelper.NewFileName(DirectoryPath, "purchase_rate", "csv") }; Data.Add(new ModelParameter { ValidateModel = new ImportFileValidator(), SaveModel = ImportFileModel }); using (var fileStream = new FileStream(ImportFileModel.new_file_path, FileMode.Create)) { File.CopyTo(fileStream); SaveData(Data); } string rate = NewRepo.Find <string>(new QueryParam { Fields = "purchase_rate_code", Table = "tbl_purchase_rate", Where = new List <ConditionParameter> { Condition("purchase_rate_code", param[0].Trim()) } }); if (rate == param[0].Trim()) { return(new CustomResult("success", new CustomResponse { key_code = param[0], status = "300", msg = "error:Rate already Exist" })); } string tablename = NumericHelper.RandomNumber().ToString() + "tmp"; string DirectQuery = $"create table {tablename}(id int not null AUTO_INCREMENT PRIMARY KEY,fat decimal(18,2),snf decimal(18,2),milk_type varchar(5),rtpl decimal(18,2),class varchar(5) null default '0',milk_type_code int null); LOAD DATA LOCAL INFILE '{ImportFileModel.new_file_path.Replace('\\', '/')}' INTO TABLE {tablename} FIELDS TERMINATED BY ';' IGNORE 1 ROWS (fat,snf,milk_type,rtpl); "; if (rate_type != 0) { DirectQuery = $"create table {tablename}(id int not null AUTO_INCREMENT PRIMARY KEY,fat decimal(18,2),snf decimal(18,2),milk_type varchar(5),rtpl decimal(18,2),class varchar(5) null default '0',milk_type_code int null); LOAD DATA LOCAL INFILE '{ImportFileModel.new_file_path.Replace('\\', '/')}' INTO TABLE {tablename} FIELDS TERMINATED BY ';' IGNORE 1 ROWS (fat,snf,milk_type,rtpl,class); "; } NewRepo.Add(new QueryParam { DirectQuery = DirectQuery }); string value = NewRepo.Find <string>(new QueryParam { Sp = "import_rate", Where = new List <ConditionParameter> { Condition("p_rate_code", param[0].Trim()), Condition("p_rate_date", $"{param[1].Substring(4,4)}-{param[1].Substring(2,2)}-{param[1].Substring(0,2)}"), Condition("p_table_name", tablename), Condition("p_usercode", UserData.user_code), } }); if (value == "1") { return(new CustomResult("success", new CustomResponse { key_code = param[0], status = "200", msg = "success" })); } else { return(new CustomResult("success", new CustomResponse { key_code = param[0], status = "300", msg = "error" })); } }
public static string GetFilename(this IFormFile file) { return(ContentDispositionHeaderValue.Parse( file.ContentDisposition).FileName.ToString().Trim('"')); }
public IActionResult UAVImport(IFormFile excelfile) { var response = ResponseModelFactory.CreateInstance; using (_dbContext) { DateTime beginTime = DateTime.Now; string sWebRootFolder = _hostingEnvironment.WebRootPath + "\\UploadFiles\\ImportEmergencyExcel"; //var schoolinfo = _dbContext.SchoolInforManagement.AsQueryable(); string uploadtitle = "无人机信息导入" + DateTime.Now.ToString("yyyyMMddHHmmss"); string sFileName = $"{uploadtitle}.xlsx"; FileInfo file = new FileInfo(Path.Combine(sWebRootFolder, sFileName)); //string conStr = ConnectionStrings.DefaultConnection; string responsemsgsuccess = ""; string responsemsgrepeat = ""; string responsemsgdefault = ""; int successcount = 0; int repeatcount = 0; int defaultcount = 0; //string today = DateTime.Now.ToString("yyyy-MM-dd"); try { //把excelfile中的数据复制到file中 using (FileStream fs = new FileStream(file.ToString(), FileMode.Create)) //初始化一个指定路径和创建模式的FileStream { excelfile.CopyTo(fs); fs.Flush(); //清空stream的缓存,并且把缓存中的数据输出到file } DataTable dt = Haikan3.Utils.ExcelTools.ExcelToDataTable(file.ToString(), "Sheet1", true); if (dt == null || dt.Rows.Count == 0) { response.SetFailed("表格无数据"); return(Ok(response)); } else { if (!dt.Columns.Contains("无人机名称")) { response.SetFailed("无‘无人机名称’列"); return(Ok(response)); } if (!dt.Columns.Contains("无人机编号")) { response.SetFailed("无‘无人机编号’列"); return(Ok(response)); } if (!dt.Columns.Contains("链接地址")) { response.SetFailed("无‘链接地址’列"); return(Ok(response)); } if (!dt.Columns.Contains("无人机监控地址")) { response.SetFailed("无‘无人机监控地址’列"); return(Ok(response)); } for (int i = 0; i < dt.Rows.Count; i++) { var entity = new Uav(); entity.Uavuuid = Guid.NewGuid(); if (!string.IsNullOrEmpty(dt.Rows[i]["无人机名称"].ToString())) { entity.Uavname = dt.Rows[i]["无人机名称"].ToString(); } else { responsemsgdefault += "<p style='color:red'>" + "第" + (i + 2) + "行无人机名称为空" + "</p></br>"; defaultcount++; continue; } if (!string.IsNullOrEmpty(dt.Rows[i]["无人机编号"].ToString())) { entity.Uavnumber = dt.Rows[i]["无人机编号"].ToString(); } else { responsemsgdefault += "<p style='color:red'>" + "第" + (i + 2) + "行无人机编号为空" + "</p></br>"; defaultcount++; continue; } if (!string.IsNullOrEmpty(dt.Rows[i]["链接地址"].ToString())) { entity.Uavurl = dt.Rows[i]["链接地址"].ToString(); } else { responsemsgdefault += "<p style='color:red'>" + "第" + (i + 2) + "行链接地址为空" + "</p></br>"; defaultcount++; continue; } if (!string.IsNullOrEmpty(dt.Rows[i]["无人机监控地址"].ToString())) { entity.Uavaddress = dt.Rows[i]["无人机监控地址"].ToString(); } else { responsemsgdefault += "<p style='color:red'>" + "第" + (i + 2) + "行无人机监控地址为空" + "</p></br>"; defaultcount++; continue; } entity.IsDeleted = 0; _dbContext.Uav.Add(entity); _dbContext.SaveChanges(); successcount++; } } responsemsgsuccess = "<p style='color:green'>导入成功:" + successcount + "条</p></br>" + responsemsgsuccess; responsemsgrepeat = "<p style='color:orange'>重复需手动修改数据:" + repeatcount + "条</p></br>" + responsemsgrepeat; responsemsgdefault = "<p style='color:red'>导入失败:" + defaultcount + "条</p></br>" + responsemsgdefault; ToLog.AddLog("导入", "成功:导入:无人机信息数据", _dbContext); //DateTime endTime = DateTime.Now; //TimeSpan useTime = endTime - beginTime; //string taketime = "导入时间" + useTime.TotalSeconds.ToString() + "秒 "; response.SetData(JsonConvert.DeserializeObject(JsonConvert.SerializeObject(new { //time = taketime, successmsg = responsemsgsuccess , repeatmsg = responsemsgrepeat, defaultmsg = responsemsgdefault }))); return(Ok(response)); } catch (Exception ex) { response.SetFailed(ex.Message); return(Ok(response)); } } }
public FormFile(IFormFile formFile) { this.formFile = formFile; }
/// <summary> /// 上传单个文件 /// </summary> /// <param name="fileModule"></param> /// <param name="fileCollection"></param> /// <returns></returns> public async static Task <TData <string> > UploadFile(int fileModule, IFormFileCollection files) { string dirModule = string.Empty; TData <string> obj = new TData <string>(); if (files == null || files.Count == 0) { obj.Message = "请先选择文件!"; return(obj); } if (files.Count > 1) { obj.Message = "一次只能上传一个文件!"; return(obj); } TData objCheck = null; IFormFile file = files[0]; switch (fileModule) { case (int)UploadFileType.Portrait: objCheck = CheckFileExtension(Path.GetExtension(file.FileName), ".jpg|.jpeg|.gif|.png"); if (objCheck.Tag != 1) { obj.Message = objCheck.Message; return(obj); } dirModule = UploadFileType.Portrait.ToString(); break; case (int)UploadFileType.News: if (file.Length > 5 * 1024 * 1024) // 5MB { obj.Message = "文件最大限制为 5MB"; return(obj); } objCheck = CheckFileExtension(Path.GetExtension(file.FileName), ".jpg|.jpeg|.gif|.png"); if (objCheck.Tag != 1) { obj.Message = objCheck.Message; return(obj); } dirModule = UploadFileType.News.ToString(); break; case (int)UploadFileType.Import: objCheck = CheckFileExtension(Path.GetExtension(file.FileName), ".xls|.xlsx"); if (objCheck.Tag != 1) { obj.Message = objCheck.Message; return(obj); } dirModule = UploadFileType.Import.ToString(); break; default: obj.Message = "请指定上传到的模块"; return(obj); } string fileExtension = TextHelper.GetCustomValue(Path.GetExtension(file.FileName), ".png"); string newFileName = SecurityHelper.GetGuid(true) + fileExtension; string dir = "Resource" + Path.DirectorySeparatorChar + dirModule + Path.DirectorySeparatorChar + DateTime.Now.ToString("yyyy-MM-dd").Replace('-', Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar; string absoluteDir = Path.Combine(GlobalContext.HostingEnvironment.ContentRootPath, dir); string absoluteFileName = string.Empty; if (!Directory.Exists(absoluteDir)) { Directory.CreateDirectory(absoluteDir); } absoluteFileName = absoluteDir + newFileName; try { using (FileStream fs = File.Create(absoluteFileName)) { await file.CopyToAsync(fs); fs.Flush(); } obj.Data = Path.AltDirectorySeparatorChar + ConvertDirectoryToHttp(dir) + newFileName; obj.Message = Path.GetFileNameWithoutExtension(TextHelper.GetCustomValue(file.FileName, newFileName)); obj.Description = (file.Length / 1024).ToString(); // KB obj.Tag = 1; } catch (Exception ex) { obj.Message = ex.Message; } return(obj); }
public static bool MaxLength(this IFormFile file, int kb) { return(file.Length / 1024 > kb); }
public virtual Task <IEnumerable <ItemResult> > CsvUpload( IFormFile file, IDataSource <Coalesce.Domain.Case> dataSource, IBehaviors <Coalesce.Domain.Case> behaviors, bool hasHeader = true) => CsvUploadImplementation(file, dataSource, behaviors, hasHeader);
public async Task <ActionResult <string> > UploadLogoImage([FromRoute] Guid merchantGuid, IFormFile imageFile) { // Step 1: Get the merchant var dbMerchant = await _dbContext.GetMerchantAsync(merchantGuid); // if we did not find a matching merchant if (dbMerchant == null) { return(BadRequest(new ArgumentException($"MerchantID: [{merchantGuid}] not found", nameof(merchantGuid)))); } // Step 2: Validate supported image type and that image format in the file matches the extension (byte[] fileContents, string errorMessage) = ImageFileHelpers.ProcessFormFile(imageFile, _permittedExtensions, _fileSizeLimit); if (fileContents.Length == 0) { return(BadRequest(new ArgumentException(errorMessage, nameof(imageFile)))); } // Step 3: Store in local folder string imageFileName = $"{merchantGuid}-logo{System.IO.Path.GetExtension(imageFile.FileName)}"; // use Path.Combine to deal with O/S differences re Linux: "/" vs Windows: "\" string imageFilePathName = System.IO.Path.Combine(_environment.ContentRootPath, GeneralConstants.LOGO_IMAGES_FOLDER_NAME, imageFileName); using (var fileStream = System.IO.File.Create(imageFilePathName)) { fileStream.Write(fileContents); } // Step 4: Update the merchant dbMerchant.LogoFileName = imageFileName; await _dbContext.UpdateMerchantAsync(dbMerchant); // Step 5: Return results https://localhost:44318/LogoImages/f8c6f5b6-533e-455f-87a1-ced552898e1d.png var imageUri = HttpHelpers.BuildFullURL(this.Request, imageFileName); return(Ok(imageUri)); }
public JsonResult GetUploadedFileDetails(IFormFile file) { var request = _bulkUploadService.GetSheetsRecords(file); return(Json(request)); }
public async Task <UploadResult> ProcessFile( IFormFile formFile, ImageProcessingOptions options, bool?resizeImages, int?maxWidth, int?maxHeight, string requestedVirtualPath = "", string newFileName = "", bool allowRootPath = true ) { await EnsureProjectSettings().ConfigureAwait(false); string currentFsPath = rootPath.RootFileSystemPath; string currentVirtualPath = rootPath.RootVirtualPath; string[] virtualSegments = options.ImageDefaultVirtualSubPath.Split('/'); bool doResize = resizeImages.HasValue ? resizeImages.Value : options.AutoResize; if ((!string.IsNullOrEmpty(requestedVirtualPath)) && (requestedVirtualPath.StartsWith(rootPath.RootVirtualPath))) { var virtualSubPath = requestedVirtualPath.Substring(rootPath.RootVirtualPath.Length); var segments = virtualSubPath.Split('/'); if (segments.Length > 0) { var requestedFsPath = Path.Combine(rootPath.RootFileSystemPath, Path.Combine(segments)); if (!Directory.Exists(requestedFsPath)) { log.LogError("directory not found for currentPath " + requestedFsPath); } else { currentVirtualPath = requestedVirtualPath; virtualSegments = segments; currentFsPath = Path.Combine(currentFsPath, Path.Combine(virtualSegments)); } } } else { // only ensure the folders if no currentDir provided, // if it is provided it must be an existing path // options.ImageDefaultVirtualSubPath might not exist on first upload so need to ensure it if (!allowRootPath) { currentVirtualPath = currentVirtualPath + options.ImageDefaultVirtualSubPath; currentFsPath = Path.Combine(currentFsPath, Path.Combine(virtualSegments)); EnsureSubFolders(rootPath.RootFileSystemPath, virtualSegments); } } string newName; if (!string.IsNullOrEmpty(newFileName)) { newName = nameRules.GetCleanFileName(newFileName); } else { newName = nameRules.GetCleanFileName(Path.GetFileName(formFile.FileName)); } var newUrl = currentVirtualPath + "/" + newName; var fsPath = Path.Combine(currentFsPath, newName); var ext = Path.GetExtension(newName); var webSizeName = Path.GetFileNameWithoutExtension(newName) + "-ws" + ext; var webFsPath = Path.Combine(currentFsPath, webSizeName); string webUrl = string.Empty; var didResize = false; try { using (var stream = new FileStream(fsPath, FileMode.Create)) { await formFile.CopyToAsync(stream); } if ((doResize) && IsWebImageFile(ext)) { var mimeType = GetMimeType(ext); webUrl = currentVirtualPath + "/" + webSizeName; int resizeWidth = GetMaxWidth(maxWidth, options); int resizeHeight = GetMaxWidth(maxHeight, options); didResize = imageResizer.ResizeImage( fsPath, currentFsPath, webSizeName, mimeType, resizeWidth, resizeHeight, options.AllowEnlargement ); } return(new UploadResult { OriginalUrl = newUrl, ResizedUrl = didResize? webUrl : string.Empty, Name = newName, Length = formFile.Length, Type = formFile.ContentType }); } catch (Exception ex) { log.LogError(MediaLoggingEvents.FILE_PROCCESSING, ex, ex.StackTrace); return(new UploadResult { ErrorMessage = sr["There was an error logged during file processing"] }); } }
public async Task <ActionResult> ScheduleMessage(string message, string profileId, long userId, string imagePath, string link, string scheduledatetime, IFormFile files) { var filename = ""; string postmessage = ""; var uploads = _appEnv.WebRootPath + "\\wwwwroot\\upload\\" + profileId; if (files != null) { if (files.Length > 0) { var fileName = Microsoft.Net.Http.Headers.ContentDispositionHeaderValue.Parse(files.ContentDisposition).FileName.Trim('"'); // await file.s(Path.Combine(uploads, fileName)); filename = Microsoft.Net.Http.Headers.ContentDispositionHeaderValue .Parse(files.ContentDisposition) .FileName .Trim('"'); //apiimgPath = _appSettings.ApiDomain + "/api/Media/get?id=" + $@"{Domain.Socioboard.Helpers.SBHelper.RandomString(10) + '.' + fileName.Split('.')[1]}"; var tempName = Domain.Socioboard.Helpers.SBHelper.RandomString(10) + '.' + fileName.Split('.')[1]; filename = _appEnv.WebRootPath + "\\upload" + $@"\{tempName}"; uploads = _appSettings.ApiDomain + "/api/Media/get?id=" + $@"{tempName}"; // size += file.Length; using (FileStream fs = System.IO.File.Create(filename)) { files.CopyTo(fs); fs.Flush(); } filename = uploads; } } else if (!string.IsNullOrEmpty(imagePath)) { filename = imagePath; } string[] updatedmessgae = Regex.Split(message, "<br>"); foreach (var item in updatedmessgae) { if (!string.IsNullOrEmpty(item)) { if (item.Contains("https://") || item.Contains("http://")) { link = item; } if (item.Contains("hhh") || item.Contains("nnn")) { if (item.Contains("hhh")) { postmessage = postmessage + "\n\r" + item.Replace("hhh", "#"); } } else { postmessage = postmessage + "\n\r" + item; } } } message = postmessage; DatabaseRepository dbr = new DatabaseRepository(_logger, _appEnv); string[] lstProfileIds = null; if (profileId != null) { lstProfileIds = profileId.Split(','); profileId = lstProfileIds[0]; } else { return(Ok("profileId required")); } string retunMsg = string.Empty; foreach (var item in lstProfileIds) { if (item.StartsWith("fb")) { try { string prId = item.Substring(3, item.Length - 3); Domain.Socioboard.Models.Facebookaccounts objFacebookaccounts = Api.Socioboard.Repositories.FacebookRepository.getFacebookAccount(prId, _redisCache, dbr); Helper.ScheduleMessageHelper.ScheduleMessage(prId, objFacebookaccounts.FbUserName, message, Domain.Socioboard.Enum.SocialProfileType.Facebook, userId, filename, "https://graph.facebook.com/" + prId + "/picture?type=small", scheduledatetime, _appSettings, _redisCache, dbr, _logger); } catch (System.Exception ex) { _logger.LogError(ex.StackTrace); //return Ok("Issue With Facebook schedulers"); } } if (item.StartsWith("page")) { try { string prId = item.Substring(5, item.Length - 5); Domain.Socioboard.Models.Facebookaccounts objFacebookaccounts = Api.Socioboard.Repositories.FacebookRepository.getFacebookAccount(prId, _redisCache, dbr); Helper.ScheduleMessageHelper.ScheduleMessage(prId, objFacebookaccounts.FbUserName, message, Domain.Socioboard.Enum.SocialProfileType.FacebookFanPage, userId, filename, "https://graph.facebook.com/" + prId + "/picture?type=small", scheduledatetime, _appSettings, _redisCache, dbr, _logger); } catch (System.Exception ex) { _logger.LogError(ex.StackTrace); // return Ok("Issue With Facebook Page schedulers"); } } if (item.StartsWith("tw")) { try { string prId = item.Substring(3, item.Length - 3); Domain.Socioboard.Models.TwitterAccount objTwitterAccount = Api.Socioboard.Repositories.TwitterRepository.getTwitterAccount(prId, _redisCache, dbr); Helper.ScheduleMessageHelper.ScheduleMessage(prId, objTwitterAccount.twitterScreenName, message, Domain.Socioboard.Enum.SocialProfileType.Twitter, userId, filename, objTwitterAccount.profileImageUrl, scheduledatetime, _appSettings, _redisCache, dbr, _logger); } catch (System.Exception ex) { _logger.LogError(ex.StackTrace); // return Ok("Issue With Twitter schedulers"); } } if (item.StartsWith("lin")) { try { string prId = item.Substring(4, item.Length - 4); Domain.Socioboard.Models.LinkedInAccount objLinkedInAccount = Api.Socioboard.Repositories.LinkedInAccountRepository.getLinkedInAccount(prId, _redisCache, dbr); Helper.ScheduleMessageHelper.ScheduleMessage(prId, objLinkedInAccount.LinkedinUserName, message, Domain.Socioboard.Enum.SocialProfileType.LinkedIn, userId, filename, objLinkedInAccount.ProfileImageUrl, scheduledatetime, _appSettings, _redisCache, dbr, _logger); } catch (System.Exception ex) { _logger.LogError(ex.StackTrace); // return Ok("Issue With Linkedin schedulers"); } } if (item.StartsWith("Cmpylinpage")) { try { string prId = item.Substring(12, item.Length - 12); Domain.Socioboard.Models.LinkedinCompanyPage objLinkedinCompanyPage = Api.Socioboard.Repositories.LinkedInAccountRepository.getLinkedinCompanyPage(prId, _redisCache, dbr); Helper.ScheduleMessageHelper.ScheduleMessage(prId, objLinkedinCompanyPage.LinkedinPageName, message, Domain.Socioboard.Enum.SocialProfileType.LinkedInComapanyPage, userId, filename, objLinkedinCompanyPage.LogoUrl, scheduledatetime, _appSettings, _redisCache, dbr, _logger); } catch (System.Exception ex) { _logger.LogError(ex.StackTrace); // return Ok("Issue With Linkedin Page schedulers"); } } } return(Ok("scheduled")); }
public async Task <string> UploadImage(IFormFile file) { var result = await _imageWriter.UploadImage(file); return(result); }
public JsonResult UploadFile(IFormFile file) { if (file == null) { return(Json(false)); } if (file.FileName.EndsWith(".xlsx") || file.FileName.EndsWith(".xls")) { var fileName = Path.Combine(_env.WebRootPath, "Content", "TempUploads", Guid.NewGuid().ToString().Replace("-", "") + Path.GetExtension(file.FileName)); try { using (var fileStream = new FileStream(fileName, FileMode.Create)) { var task = file.CopyToAsync(fileStream); task.Wait(); } Workbook workbook = new Workbook(); workbook.LoadFromFile(fileName); Worksheet sheet = workbook.Worksheets[0]; var dt = sheet.ExportDataTable(); foreach (DataRow dr in dt.Rows) { var companyCode = dr["Şirket Kodu"].ToString(); var companyDescription = dr["Şirket"].ToString().Trim(); var mobileCount = dr["Mobil Sayısı"].ToString().Trim(); var address1 = dr["Adres 1"].ToString().Trim(); var address2 = dr["Adres 2"].ToString().Trim(); var phone = dr["Telefon"].ToString().Trim(); var fax = dr["Fax"].ToString().Trim(); var personInCharge = dr["Yetkili Kişi"].ToString().Trim(); var companyPartner = dr["İş Ortağı"].ToString().Trim(); var distributorName = dr["Bayi Adı"].ToString().Trim(); var platform = dr["Platform"].ToString().Trim(); var sector = dr["Sektör"].ToString().Trim(); var loginUrl = dr["Login Url"].ToString().Trim(); var baseMap = dr["BaseMap"].ToString().Trim(); var technicalReport = dr["Teknik Rapor"].ToString().Trim(); var companyStatus = dr["Kullanım Durumu"].ToString().Trim(); var taxAdministration = dr["Vergi Dairesi"].ToString().Trim(); var taxNumber = dr["Vergi No"].ToString().Trim(); var entranceDate = dr["Giriş Zamanı"].ToString().Trim(); var exitDate = dr["Çıkış Zamanı"].ToString().Trim(); var alarmSms = dr["Alarm Sms"].ToString().Trim(); var passwordControl = dr["Şifre Kontrol"].ToString().Trim(); var infoSense = dr["InfoSense"].ToString().Trim(); var accountingCode = dr["Muhasebe Hes Kodu"].ToString().Trim(); //USER INFORMATİONSS NEEDED??????????? var company = new Company() { CompanyCode = companyCode, CompanyDescription = companyDescription, MobileCount = Convert.ToInt32(mobileCount), Address1 = address1, Address2 = address2, Phone = phone, Fax = fax, //PersonInCharge = personInCharge, //buradaki yetkili kişi userdaki yetkili kişi ?? CompanyPartnerId = CompanyPartnerDB.GetInstance().GetCompanyPartnerByNameOrInsert(companyPartner).Id, DistributorId = DistributorDB.GetInstance().GetDistributorIdByName(distributorName), PlatformId = PlatformDB.GetInstance().GetPlatformByNameOrInsert(platform).Id, SectorId = SectorDB.GetInstance().GetSectorByNameOrInsert(sector).Id, LoginUrl = loginUrl, BaseMap = baseMap, TechnicalReport = technicalReport == "Aktif" ? true : false, CompanyStatus = companyStatus == "Aktif" ? true : false, TaxAdministration = taxAdministration, TaxNumber = taxNumber, EntranceDate = GetExcelDateTime(entranceDate), ExitDate = GetExcelDateTime(exitDate), AlarmSms = alarmSms == "Aktif" ? true : false, PasswordControl = passwordControl == "Aktif" ? true : false, InfoSense = infoSense == "Aktif" ? true : false, AccountingCode = accountingCode }; var result = CompanyDB.GetInstance().AddNewCompany(company); } if (System.IO.File.Exists(fileName)) { System.IO.File.Delete(fileName); } return(Json(true)); } catch (Exception exc) { if (System.IO.File.Exists(fileName)) { System.IO.File.Delete(fileName); } return(Json(exc.Message)); } } else { return(Json(false)); } }
public async Task <ActionResult> DraftScheduleMessage(string message, long userId, string scheduledatetime, long groupId, IFormFile files) { var uploads = _appEnv.WebRootPath + "\\wwwwroot\\upload\\"; var filename = ""; string postmessage = ""; if (files != null) { if (files.Length > 0) { var fileName = Microsoft.Net.Http.Headers.ContentDispositionHeaderValue.Parse(files.ContentDisposition).FileName.Trim('"'); // await file.s(Path.Combine(uploads, fileName)); filename = Microsoft.Net.Http.Headers.ContentDispositionHeaderValue .Parse(files.ContentDisposition) .FileName .Trim('"'); var tempName = Domain.Socioboard.Helpers.SBHelper.RandomString(10) + '.' + fileName.Split('.')[1]; //filename = _appEnv.WebRootPath + $@"\{tempName}"; filename = _appEnv.WebRootPath + "\\upload" + $@"\{tempName}"; uploads = _appSettings.ApiDomain + "/api/Media/get?id=" + $@"{tempName}"; // size += file.Length; using (FileStream fs = System.IO.File.Create(filename)) { files.CopyTo(fs); fs.Flush(); } filename = uploads; } } string[] updatedmessgae = Regex.Split(message, "<br>"); foreach (var item in updatedmessgae) { if (!string.IsNullOrEmpty(item)) { if (item.Contains("hhh") || item.Contains("nnn")) { if (item.Contains("hhh")) { postmessage = postmessage + "\n\r" + item.Replace("hhh", "#"); } } else { postmessage = postmessage + "\n\r" + item; } } } if (scheduledatetime == null) { scheduledatetime = DateTime.UtcNow.ToString(); } message = postmessage; DatabaseRepository dbr = new DatabaseRepository(_logger, _appEnv); Helper.ScheduleMessageHelper.DraftScheduleMessage(message, userId, groupId, filename, scheduledatetime, _appSettings, _redisCache, dbr, _logger); return(Ok()); }
public Task<string> UploadImage(IFormFile uFile) { return _alphahomeRepo.UploadImage(uFile); }
public async Task <IActionResult> ComposeMessage(string message, string profileId, long userId, string imagePath, string link, IFormFile files) { var filename = ""; var apiimgPath = ""; var uploads = string.Empty; string postmessage = ""; if (files != null) { if (files.Length > 0) { var fileName = Microsoft.Net.Http.Headers.ContentDispositionHeaderValue.Parse(files.ContentDisposition).FileName.Trim('"'); // await file.s(Path.Combine(uploads, fileName)); filename = Microsoft.Net.Http.Headers.ContentDispositionHeaderValue .Parse(files.ContentDisposition) .FileName .Trim('"'); var tempName = Domain.Socioboard.Helpers.SBHelper.RandomString(10) + '.' + fileName.Split('.')[1]; //apiimgPath = _appSettings.ApiDomain + "/api/Media/get?id=" + $@"{tempName}"; filename = _appEnv.WebRootPath + "\\upload" + $@"\{tempName}"; uploads = _appSettings.ApiDomain + "/api/Media/get?id=" + $@"{tempName}"; // size += file.Length; try { using (FileStream fs = System.IO.File.Create(filename)) { files.CopyTo(fs); fs.Flush(); } filename = uploads; } catch (System.Exception ex) { if (!string.IsNullOrEmpty(imagePath)) { uploads = imagePath; } } } } else if (!string.IsNullOrEmpty(imagePath)) { uploads = imagePath; } //string[] updatedmessgae = Regex.Split(message, "<br>"); //message = postmessage; DatabaseRepository dbr = new DatabaseRepository(_logger, _appEnv); string[] lstProfileIds = null; if (profileId != null) { lstProfileIds = profileId.Split(','); profileId = lstProfileIds[0]; } else { return(Ok("profileId required")); } foreach (var item in lstProfileIds) { if (item.StartsWith("fb")) { try { new Thread(delegate() { string prId = item.Substring(3, item.Length - 3); Domain.Socioboard.Models.Facebookaccounts objFacebookAccount = Api.Socioboard.Repositories.FacebookRepository.getFacebookAccount(prId, _redisCache, dbr); string ret = Helper.FacebookHelper.ComposeMessage(objFacebookAccount.FbProfileType, objFacebookAccount.AccessToken, objFacebookAccount.FbUserId, message, prId, userId, uploads, link, dbr, _logger); }).Start(); } catch (Exception ex) { } } if (item.StartsWith("tw")) { try { new Thread(delegate() { string prId = item.Substring(3, item.Length - 3); string ret = Helper.TwitterHelper.PostTwitterMessage(_appSettings, _redisCache, message, prId, userId, uploads, true, dbr, _logger); }).Start(); } catch (Exception ex) { } } if (item.StartsWith("lin")) { try { new Thread(delegate() { string prId = item.Substring(4, item.Length - 4); string ret = Helper.LinkedInHelper.PostLinkedInMessage(uploads, userId, message, prId, filename, _redisCache, _appSettings, dbr); }).Start(); } catch (Exception ex) { } } if (item.StartsWith("Cmpylinpage")) { try { new Thread(delegate() { string prId = item.Substring(12, item.Length - 12); string ret = Helper.LinkedInHelper.PostLinkedInCompanyPagePost(uploads, userId, message, prId, _redisCache, dbr, _appSettings); }).Start(); } catch (Exception ex) { } } } return(Ok("Posted")); }
public static bool CheckUploadedImageIsCorrect(IFormFile imageFile, string forceExtName=null) { if (imageFile != null) { // Treat upload image double fileSizeKo = imageFile.Length / (double)1024; if (fileSizeKo <= 2000) { // Accept little file image <= 2Mo if (string.IsNullOrWhiteSpace(forceExtName)) { switch (imageFile.ContentType)// Accept only png, bmp, jpeg, jpg file { case "image/png": case "image/bmp": case "image/jpeg": return true; } } else { if (imageFile.ContentType == "image/png" && forceExtName == "png") return true; else if (imageFile.ContentType == "image/bmp" && forceExtName == "bmp") return true; else if (imageFile.ContentType == "image/jpeg" && (forceExtName == "jpeg" || forceExtName == "jpg")) return true; } } } return false; }
public async Task<IActionResult> Create(TestEnvironment testEnvironment, IFormFile file) { if (ModelState.IsValid) { _context.TestEnvironment.Add(testEnvironment); testEnvironment.ContentType = file.ContentType; _context.SaveChanges(); } var uploads = Path.Combine(strUploadsDirectory, testEnvironment.TestEnvironmentID.ToString()); if (!Directory.Exists(uploads)) { Directory.CreateDirectory(uploads); } if (file.Length > 0) { string fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"'); await file.SaveAsAsync(Path.Combine(uploads, fileName)); _context.Update(testEnvironment); testEnvironment.XMLFilePath = fileName; _context.SaveChanges(); } HttpContext.Session.SetString("Message", "Environment: " + testEnvironment.Name + " successfully created"); return RedirectToAction("Index"); }
public async Task<IActionResult> Edit(CampaignSummaryModel campaign, IFormFile fileUpload) { if (campaign == null) { return HttpBadRequest(); } if (!User.IsTenantAdmin(campaign.TenantId)) { return HttpUnauthorized(); } if (ModelState.IsValid) { if (fileUpload != null) { if (fileUpload.IsAcceptableImageContentType()) { campaign.ImageUrl = await _imageService.UploadCampaignImageAsync(campaign.TenantId, campaign.Id, fileUpload); } else { ModelState.AddModelError("ImageUrl", "You must upload a valid image file for the logo (.jpg, .png, .gif)"); return View(campaign); } } int id = _bus.Send(new EditCampaignCommand { Campaign = campaign }); return RedirectToAction("Details", new { area = "Admin", id = id }); } return View(campaign); }
private static string GetFileName(IFormFile file) { return ContentDispositionHeaderValue .Parse(file.ContentDisposition) .FileName .Trim('"'); }
public IActionResult Upload(IFormFile arquivo) { //Cria um blob client CloudBlobClient blobClient = _storageAccount.CreateCloudBlobClient(); //Recupera a referencia do container documentos CloudBlobContainer container = blobClient.GetContainerReference("documentos"); //Caso não exista, ele cria container.CreateIfNotExists(); //Setar permissão de acesso para 'público' container.SetPermissions( new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob } ); //Recupera a referência de um blob chamado 'cliente01' CloudBlockBlob blockBlob = container.GetBlockBlobReference("cliente01.pdf"); Stream streamFile = arquivo.OpenReadStream(); //Cria ou substitui o blob com o conteúdo do upload blockBlob.UploadFromStream(streamFile); return RedirectToAction("VerArquivos"); }
//Need Binding. public async Task<IActionResult> Create(Photo photo, IFormFile files, int id) { if (files == null) { ModelState.AddModelError(string.Empty, "Please select a file to upload."); } else if (ModelState.IsValid) { photo.UploadDate = DateTime.Now; photo.UserFolderId = id; var folderName = _context.UserFolder.Where(q => q.UserFolderID == id).First().Name; //TODO: Check for image types var fileName = Guid.NewGuid() + ContentDispositionHeaderValue.Parse(files.ContentDisposition).FileName.Trim('"'); var filePath = Path.Combine("Photos", User.GetUserName(), folderName, fileName); await files.SaveAsAsync(filePath); photo.Url = "~/" + filePath; _context.Add(photo); _context.SaveChanges(); return ViewFolderContents(id); } return View(photo); }
public IActionResult Index(IFormFile file) { // todo: - proper view model //- more complete result type/info if (file == null) { _logger.LogInformation($"User {User.Identity.Name} attempted a file upload without specifying a file."); return RedirectToAction(nameof(Index)); } using (var stream = file.OpenReadStream()) { using (var reader = new StreamReader(stream)) { var csvReader = new CsvReader(reader); csvReader.Configuration.WillThrowOnMissingField = false; csvReader.Configuration.RegisterClassMap<RedCrossRequestMap>(); var requests = csvReader.GetRecords<Request>().ToList(); var errors = _mediator.Send(new ImportRequestsCommand { Requests = requests }); } } _logger.LogDebug($"{User.Identity.Name} imported file {file.Name}"); ViewBag.ImportSuccess = true; return View(); }
public ActionResult Edit(Product product, IFormFile image) { if (ModelState.IsValid) { if (image != null) { FileDetails fileDetails; using (var reader = new StreamReader(image.OpenReadStream())) { var fileContent = reader.ReadToEnd(); var parsedContentDisposition = ContentDispositionHeaderValue.Parse(image.ContentDisposition); fileDetails = new FileDetails { Filename = parsedContentDisposition.FileName, Content = fileContent, ContentType=image.ContentType }; } //product.ImageMimeType = image.ContentType; product.ImageData = fileDetails.Content; } _productRepository.AddOrUpdate(product); TempData["message"] = string.Format("{0} has been saved successfully", product.Title); return RedirectToAction("Index"); } return View(product); }
public async Task Upload(IFormFile file) { if (file == null || file.Length == 0) Exceptions.ServerError("Invalid file."); var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"'); using (var stream = file.OpenReadStream()) await DeployManager.Upload(stream, fileName); }
public CarNumberResult ProcessImage(IFormFile file) { var result = new CarNumberResult(); var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Replace("\"", string.Empty); using (var fileStram = file.OpenReadStream()) { var image = _imageFactory.CreateImage(fileName, fileStram); var processResult = _identifyService.IdentifyAsync(image).Result; processResult.ProcessedImage.Name = Guid.NewGuid() + Path.GetExtension(processResult.ProcessedImage.Name); _imageRepository.SaveImageAsync(processResult.ProcessedImage).Wait(); result.ImageUrl = _imageUrlProvider.GetImageUrl(processResult.ProcessedImage.Name); } return result; }
public async Task<string> HandleUpload(IFormFile file) { var data = await _streamHandler.CopyStreamToByteBuffer(file.OpenReadStream()); var encryptedData = await _streamHandler.EncryptData(data); var uniqueFileName = Guid.NewGuid().ToString(); await _streamHandler.WriteBufferToFile(encryptedData, _hostingEnvironment.WebRootPath + "uploads/" + uniqueFileName); return uniqueFileName; }