public BasicResponseModel UploadFile(string sessionId, ImageUploadModel request) { if (!AllowOperates.Contains(request.ImageType)) { return(new GetFilesResponse() { Code = ImageErrorCode.InvalidOperation, Message = "非法操作" }); } try { var response = imageAgent.UploadImage(GetToken(sessionId).AccessToken, request.ToALCTUploadFileModel()); if (response.Code != "0") { return(new BasicResponseModel() { Code = ImageErrorCode.UploadImageFailed, Message = response.Message }); } return(new BasicResponseModel()); } catch (Exception ex) { logger.LogError(ex, "Upload file failed"); return(new GetFilesResponse() { Code = ImageErrorCode.UploadImageFailed, Message = "上传图片失败,请重试" }); } }
public JsonResult InvoiceImageUpload(ImageUploadModel modal) { AddSerialBL obj = new AddSerialBL(); ImageUpload entity = new ImageUpload(); if (ModelState.IsValid) { entity.ImageFile = modal.ImageFile; entity.ImageType = modal.ImageType; string imagepath = Path.Combine(Server.MapPath("~/Content/InvoiceImages")); entity.path = imagepath; if (!Directory.Exists(imagepath)) { Directory.CreateDirectory(imagepath); } if (modal.UploadImage != null) { string fileName = Path.GetFileName(modal.ImageFile); modal.UploadImage.SaveAs(imagepath + fileName); } } var result = obj.AddImageUpload(entity); return(Json(result, JsonRequestBehavior.AllowGet)); }
//[Authorize] public IActionResult Index(ImageUploadModel model) { //upload image after authorizing user return(RedirectToAction("Index")); }
public async Task <IActionResult> Upload([FromBody] ImageUploadModel img) { if (!Request.Headers.TryGetValue("authorization", out var key) || key != _config["authorization"]) { return(NotFound()); } if (img.ImageUrl == null || img.ImageUrl == "") { return(BadRequest("Url missing")); } string path = Path.Combine(_env.WebRootPath, "images", img.Path); CreateIfNotExists(path); if (Directory.Exists(Path.Combine(path, img.Name))) { return(BadRequest($"Image already exists at {Path.Combine(img.Path, img.Name)}")); } using WebClient client = new WebClient(); await client.DownloadFileTaskAsync(img.ImageUrl, Path.Combine(path, img.Name)); return(Ok()); }
public async Task <string> UploadImage([FromForm] ImageUploadModel model) { if (model == null) { return("Forma nav aizpildīta!"); } if (model.UploadedFile == null) { return("Attēls nav izvēlēts!"); } if (model.FileName == null) { return("Attēla nosaukums nav ievadīts!"); } var filePath = Path.Combine( Directory.GetCurrentDirectory(), "wwwroot\\static\\", model.FileName); using (var stream = new FileStream(filePath, FileMode.Create)) { await model.UploadedFile.CopyToAsync(stream); } return(filePath); }
public ActionResult CreateImages() { bool isSavedSuccessfully = true; string fName = ""; var imgName = ""; var saveThumnail = new ImageUploadModel(); var saveMainImage = new ImageUploadModel(); try { foreach (string fileName in Request.Files) { var guid = Guid.NewGuid().ToString(); HttpPostedFileBase file = Request.Files[fileName]; //Save file content goes here fName = file.FileName; if (file != null && file.ContentLength > 0) { //save Thumbnail var originalDirectory = new DirectoryInfo(string.Format("{0}\\Content\\Thumbnails", Server.MapPath(@"\"))); string pathString = System.IO.Path.Combine(originalDirectory.ToString(), ""); bool isExists = System.IO.Directory.Exists(pathString); if (!isExists) { System.IO.Directory.CreateDirectory(pathString); } saveThumnail = ResourseService.SaveImage(pathString, file, true); //saveMainImage var originalDirectory2 = new DirectoryInfo(string.Format("{0}\\Content\\Data", Server.MapPath(@"\"))); string pathString2 = System.IO.Path.Combine(originalDirectory2.ToString(), ""); bool isExists2 = System.IO.Directory.Exists(pathString2); if (!isExists) { System.IO.Directory.CreateDirectory(pathString2); } saveMainImage = ResourseService.SaveImage(pathString2, file, false); } } } catch (Exception ex) { isSavedSuccessfully = false; } if (isSavedSuccessfully) { return(Json(new { MainImage = saveMainImage.FullFileName, Thumbnail = saveThumnail.FullFileName })); } else { return(Json(new { Message = "Error in saving file" })); } }
public void UploadImage(ImageUploadModel imageUpload) { ImageUploadParams uploadParams = new ImageUploadParams() { File = new FileDescription(imageUpload.Name, new MemoryStream(imageUpload.Image)), }; ImageUploadResult uploadResult = this._cloudinary.Upload(uploadParams); }
public IActionResult UploadImage([FromForm] ImageUploadModel image) { if (!CheckSessionId()) { return(Unauthorized()); } return(Ok(imageBusinessLogic.UploadFile(GetSessionId(), image))); }
// GET: Test public JsonResult ImageUpload(ImageUploadModel iu) { var File = iu.ImageFile; if (File != null) { var filename = Path.GetFileName(File.FileName); File.SaveAs(Server.MapPath(iu.PathtoSave + filename)); } return(Json(File.FileName, JsonRequestBehavior.AllowGet)); }
public async Task <IActionResult> AnalyzeImage([FromBody] ImageUploadModel data) { var features = new VisualFeatureTypes[] { VisualFeatureTypes.Tags, VisualFeatureTypes.Description }; using (Stream imageStream = new MemoryStream(Convert.FromBase64String(data.value))) { ImageAnalysis analysis = await _computerVisionService.AnalyzeImageInStreamAsync(imageStream, features); return(Ok(analysis)); } }
public ActionResult UploadImage(ImageUploadModel img, HttpPostedFileBase file) { try { string UserName = User.Identity.Name; if (ModelState.IsValid) { if (file == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } if (file != null) { string path = Path.Combine(Server.MapPath("~/Content/Images"), Path.GetFileName(file.FileName)); file.SaveAs(path); img.ImagePath = file.FileName; } using (var context = new JustHallAtumationEntities()) { var user = context.Users.Where(x => x.UserName == UserName).FirstOrDefault(); var image = context.UserImages.Where(x => x.UserId == user.UserId).FirstOrDefault(); if (image == null) { UserImage userImage = new UserImage { UserId = user.UserId, Image = img.ImagePath }; context.UserImages.Add(userImage); context.SaveChanges(); } else { image.Image = img.ImagePath; context.SaveChanges(); } } return(RedirectToAction("Index", "Home")); } return(View(img)); } catch (Exception ex) { return(View(ex)); } }
public IActionResult Upload(ImageUploadModel model) { var imagePath = Path.Combine(he.WebRootPath, "images", model.FormFile.FileName); //Path.GetFileName(model.FormFile.FileName) using (var stream = new FileStream(imagePath, FileMode.Create)) { model.FormFile.CopyTo(stream); } var imagePathDB = $"/images/{model.FormFile.FileName}"; this.images.Save(model.Title, imagePathDB); return(RedirectToAction(nameof(GalleryController.Index), "Gallery")); }
public async Task <IActionResult> POSTAddNewsImgLarge(string NewsName, [FromForm] ImageUploadModel image) { if (!ModelState.IsValid) { return(BadRequest()); } if (image == null) { return(BadRequest()); } News news; if ((news = vinylContext.News.SingleOrDefault(n => n.TitleSmall == NewsName)) == null) { return(NoContent()); } string role = User.Claims.SingleOrDefault(u => u.Type == ClaimsRole).Value; if (role != Constants._RoleAdmin && role != Constants._RoleAdminOwner) { return(Unauthorized()); } if (!Directory.Exists(Constants._rootPathNews + "//" + NewsName + "//")) { Directory.CreateDirectory(Constants._rootPathNews + "//" + NewsName + "//"); Directory.CreateDirectory(Constants._rootPathNews + "//" + NewsName + "//" + "Small" + "//"); Directory.CreateDirectory(Constants._rootPathNews + "//" + NewsName + "//" + "Large" + "//"); } if (news.ImageLarge != null) { System.IO.File.Delete(Constants._rootPathNews + "//" + NewsName + "//" + "Large" + "//" + news.ImageLarge); } if (image.Image.Length > 0) { using (FileStream fs = System.IO.File.Create(Constants._rootPathNews + "//" + NewsName + "//" + "Large" + "//" + image.Image.FileName)) { await image.Image.CopyToAsync(fs); await fs.FlushAsync(); } news.ImageLarge = image.Image.FileName; vinylContext.News.Update(news); vinylContext.SaveChanges(); return(Ok()); } return(BadRequest()); }
public async Task <IActionResult> Index() { if (ModelState.IsValid) { FormValueProvider valueProvider = null; var viewModel = new ImageUploadModel(); bool updateResult = false; Image binary; binary = await _binaryRepository.InsertAsync( async (stream) => { valueProvider = await Request.StreamFile(stream); }, async() => { updateResult = await TryUpdateModelAsync( viewModel, prefix: "", valueProvider: valueProvider); if (updateResult) { // TODO: read image information from request // TODO: get image dimensions, etc binary = new Image(); binary.UserId = 4; binary.Checksum = viewModel.Checksum; binary.Width = 100; binary.Height = 200; return(binary); } else { return(null); } } ); //await _binaryRepository.ExportToFileAsync(img, "/home/sergey/Projects/crystalocean/image.tmp"); if (updateResult) { return(Ok(viewModel)); } } return(BadRequest(ModelState)); }
private async Task Delete(ImageUploadModel uploadDb) { try { this.logger.LogInformation($"Deleting a record with id {uploadDb.Id} and expiration date {uploadDb.ExpiresAt.Value}"); // Delete files this.fileService.Delete(uploadDb.GetAllFilePaths()); // Delete a DB record await this.imageUploadRepository.Delete(uploadDb.Id); } catch (Exception ex) { this.logger.LogError(ex, ex.Message); } }
public IActionResult UploadProfileImage(int userId, [FromForm] ImageUploadModel image) { try { if (!ModelState.IsValid) { return(BadRequest("")); } _service.UploadImage(userId, image); return(Ok(_service.GetUserById(userId))); } catch (Exception uploadImageError) { return(Conflict(uploadImageError.Message)); } }
public async Task <IActionResult> POSTAddRecordImg(string RecordName, [FromForm] ImageUploadModel image) { if (!ModelState.IsValid) { return(BadRequest()); } if (image == null) { return(BadRequest()); } Record record; if ((record = vinylContext.Records.SingleOrDefault(r => r.Name == RecordName)) == null) { return(NoContent()); } string role = User.Claims.SingleOrDefault(u => u.Type == ClaimsRole).Value; if (role != Constants._RoleAdmin && role != Constants._RoleAdminOwner) { return(Unauthorized()); } if (!Directory.Exists(Constants._rootPathRecords + "//" + RecordName + "//")) { Directory.CreateDirectory(Constants._rootPathRecords + "//" + RecordName + "//"); } if (record.DisplayImg != null) { System.IO.File.Delete(Constants._rootPathRecords + "//" + RecordName + "//" + record.DisplayImg); } if (image.Image.Length > 0) { using (FileStream fs = System.IO.File.Create(Constants._rootPathRecords + "//" + RecordName + "//" + image.Image.FileName)) { await image.Image.CopyToAsync(fs); await fs.FlushAsync(); } record.DisplayImg = image.Image.FileName; vinylContext.Records.Update(record); vinylContext.SaveChanges(); return(Ok()); } return(BadRequest()); }
public IActionResult ImagePost([FromForm] ImageUploadModel model) { string UniqueFileName = null; if (model != null) { string ImagePath = "lll\\src\\assets\\Images"; string uploadsFolder = Path.Combine(hostingEnvironment.WebRootPath, ImagePath); UniqueFileName += Guid.NewGuid().ToString() + "_" + model.Image.FileName; ImagePath = "assets\\Images\\"; ImagePath += UniqueFileName; string FilePath = Path.Combine(uploadsFolder, UniqueFileName); model.Image.CopyTo(new FileStream(FilePath, FileMode.Create)); _userManager.Users.FirstOrDefault(user => user.Id == model.UserId).ProfileImage = ImagePath; _appDbContext.SaveChanges(); } return(Ok()); }
public async Task <IActionResult> PostAddUserImg(string UserId, [FromForm] ImageUploadModel image) { if (!ModelState.IsValid) { return(BadRequest()); } if (image == null) { return(BadRequest()); } User user; if ((user = vinylContext.Users.Find(UserId)) == null) { return(NoContent()); } if (user.Username != User.Claims.SingleOrDefault(u => u.Type == ClaimsIdentifier).Value) { return(Unauthorized()); } if (!Directory.Exists(Constants._rootPathProfiles + "//" + UserId + "//")) { Directory.CreateDirectory(Constants._rootPathProfiles + "//" + UserId + "//"); } if (user.ProfileImg != null) { System.IO.File.Delete(Constants._rootPathProfiles + "//" + UserId + "//" + user.ProfileImg); } if (image.Image.Length > 0) { using (FileStream fs = System.IO.File.Create(Constants._rootPathProfiles + "//" + UserId + "//" + image.Image.FileName)) { await image.Image.CopyToAsync(fs); await fs.FlushAsync(); } user.ProfileImg = image.Image.FileName; vinylContext.Users.Update(user); vinylContext.SaveChanges(); return(Ok()); } return(BadRequest()); }
public async Task <IActionResult> POSTAddCaffeImg(string CaffeName, [FromForm] ImageUploadModel image) { if (!ModelState.IsValid) { return(BadRequest()); } if (image == null) { return(BadRequest()); } Caffe caffe; if ((caffe = vinylContext.Caffes.SingleOrDefault(c => c.Name == CaffeName)) == null) { return(NoContent()); } if (caffe.OwnerRef != User.Claims.SingleOrDefault(u => u.Type == ClaimsIdentifier).Value) { return(Unauthorized()); } if (!Directory.Exists(Constants._rootPathCaffes + "//" + CaffeName + "//")) { Directory.CreateDirectory(Constants._rootPathCaffes + "//" + CaffeName + "//"); } if (caffe.BackgroundImg != null) { System.IO.File.Delete(Constants._rootPathCaffes + "//" + CaffeName + "//" + caffe.BackgroundImg); } if (image.Image.Length > 0) { using (FileStream fs = System.IO.File.Create(Constants._rootPathCaffes + "//" + CaffeName + "//" + image.Image.FileName)) { await image.Image.CopyToAsync(fs); await fs.FlushAsync(); } caffe.BackgroundImg = image.Image.FileName; vinylContext.Caffes.Update(caffe); vinylContext.SaveChanges(); return(Ok()); } return(BadRequest()); }
public async Task <string> AddAsync(ImageUploadModel model) { var dbModel = _mapper.Map <DBModel>(model); dbModel.Id = Guid.NewGuid().ToString(); dbModel.CreationDateTime = DateTime.UtcNow; dbModel.Status = ImageUploaderStatus.Pending; using (var client = new AmazonDynamoDBClient(RegionEndpoint.APSouth1)) { var table = await client.DescribeTableAsync("ImageMetaData"); using (var context = new DynamoDBContext(client)) { await context.SaveAsync(dbModel); } } return(dbModel.Id); }
public async Task <IActionResult> Create(ImageUploadModel model) { string recordId; try { recordId = await _imageMetadataStorageService.AddAsync(model); } catch (KeyNotFoundException) { return(new NotFoundResult()); } catch (Exception exception) { return(StatusCode(500, exception.Message)); } return(StatusCode(201, new CreateResponse { Id = recordId })); }
public async Task <IActionResult> UploadImage(ImageUploadModel model) { try { MemoryStream memoryStream = new(model.ImageFileBytes); await this.AzureBlobStorageService.UploadFileAsync(containerName : DataStorageConfiguration.ImagesContainerName, $"{model.Name}{model.FileExtension}", memoryStream); return(Ok()); } catch (Azure.RequestFailedException ex) { if (ex.ErrorCode == "BlobAlreadyExists") { return(Problem(detail: "A file with the same name already exists")); } else { return(Problem(detail: ex.Message)); } } }
public IActionResult ImageUpload(int id) { var estauary = dbContext.Estuaries.Include(i => i.Images).FirstOrDefault(i => i.Id == id); if (estauary is null) { return(NotFound()); } var model = new ImageUploadModel { EstuaryId = estauary.Id, EstuaryName = estauary.Name, Types = ListItems.SelectListFrom(dbContext.Images.Where(i => !string.IsNullOrWhiteSpace(i.Type)).Select(i => new StringListItem { Text = i.Type }).Distinct(), false, true), SubTypes = ListItems.SelectListFrom(dbContext.Images.Where(i => !string.IsNullOrWhiteSpace(i.SubType)).Select(i => new StringListItem { Text = i.SubType }).Distinct(), false, true), }; //SAEONLogs.Verbose("Model: {@Model}", model); return(View(model)); }
//[Authorize] public async Task <IActionResult> Index(ImageUploadModel model) { //upload image after authorizing user var containerClient = new BlobContainerClient( config["BlobCNN"], "m3globoimages"); var blobClient = containerClient.GetBlobClient( model.ImageFile.FileName); // USE a temporary file name var result = await blobClient.UploadAsync(model.ImageFile.OpenReadStream(), new BlobHttpHeaders { ContentType = model.ImageFile.ContentType, CacheControl = "public" }, new Dictionary <string, string> { { "customName", model.Name } } ); return(RedirectToAction("Index")); }
protected bool DoUploadImage(object id, ImageUploadModel model, HttpPostedFileBase image, out string imagePath) { string thumbPath; if (DoUploadImage(id, model, image, out imagePath, out thumbPath, true)) { if (!string.IsNullOrEmpty(thumbPath)) imagePath = thumbPath; return true; } else return false; }
public async Task <IActionResult> UploadFile(ImageUploadModel upload) { var bucket = "ignorama"; var maxFileMB = 10; var allowedTypes = new[] { "image/gif", "image/jpeg", "image/jpg", "image/pjpeg", "image/x-png", "image/png", "video/webm" }; var allowedExts = new[] { ".gif", ".jpeg", ".jpg", ".png", ".webm" }; if (upload.File.Length > maxFileMB * 1000000) { return(new ContentResult { Content = "<script>error = 'Could not upload file: File must be smaller than " + maxFileMB + " MB.';</script>", ContentType = "text/html", }); } var ext = Path.GetExtension(upload.File.FileName).ToLower(); var path = "uploads/" + System.Guid.NewGuid().ToString().Replace("-", string.Empty) + ext; if (upload.File.Length > 0 && allowedTypes.Contains(upload.File.ContentType.ToLower()) && allowedExts.Contains(ext)) { try { var fileTransferUtility = new TransferUtility(_s3Client); await fileTransferUtility.UploadAsync(upload.File.OpenReadStream(), bucket, path); return(new ContentResult { Content = $"<script>error = 'none'; fileUri = 'https://{bucket}.s3.amazonaws.com/{path}';</script>", ContentType = "text/html", }); } catch (AmazonS3Exception e) { return(new ContentResult { Content = $"<script>error = 'Error encountered on server. Message:\"{e.Message}\" when writing an object';</script>", ContentType = "text/html", }); } catch (Exception e) { return(new ContentResult { Content = $"<script>error = 'Unknown encountered on server. Message:\"{e.Message}\" when writing an object';</script>", ContentType = "text/html", }); } } return(new ContentResult { Content = "<script>error = 'Could not upload file: Unsupported file type.';</script>", ContentType = "text/html", }); }
protected bool DoUploadImage(object id, ImageUploadModel model, HttpPostedFileBase image, out string imagePath, out string thumbPath, bool createThumb) { imagePath = thumbPath = null; if (!ImageUtility.IsImageExtension(Path.GetExtension(image.FileName))) return false; string tmpModDir = model.ImagePath; string tmpThumbDir = model.ThumbPath; string fileName = NormalizeFileName(Path.GetFileName(image.FileName), id); TryCreatePath(tmpModDir); string tmpFilePath = Globals.MapPath(tmpModDir.CombineWPath("temp_" + fileName)); string tmpImageFile = Globals.MapPath(tmpModDir.CombineWPath(fileName)); SaveFile(image, ref tmpFilePath); int width = model.ImageWidth, height = model.ImageHeight; if (!model.AutoResize) { using (var img = System.Drawing.Image.FromFile(tmpFilePath)) { width = img.Width; height = img.Height; } } ResizeImage(tmpFilePath, ref tmpImageFile, width, height, defaultBackground, model.Quality); imagePath = tmpModDir.CombineWPath(Path.GetFileName(tmpImageFile)).TrimStart('~'); if (model.AllowThumb) { TryCreatePath(tmpThumbDir); string tmpThumbFile = Globals.MapPath(Globals.ThumbPath(model.Folder, Path.GetFileName(tmpImageFile))); CreateImageThumb(tmpFilePath, ref tmpThumbFile, model.ThumbWidth, model.ThumbHeight, defaultBackground, model.Quality); thumbPath = tmpThumbDir.CombineWPath(Path.GetFileName(tmpThumbFile)).TrimStart('~'); } TryDeleteFile(tmpFilePath); return true; }
public Task <ServiceResult> Upload(ImageUploadModel model) { return(_imageService.SaveAsync(model.File, model.Path)); }
public IActionResult Upload() { var model = new ImageUploadModel(); return(View(model)); }