public async Task <bool> AddProfileImage(int userID, IFormFile profileImage) { bool success; try { var image = new tbl_ProfileImage { ProfileImage = await profileImage.GetBytes(), AlternativeText = $"{CurrentUser.Details(userID).Name}'s Profile Image", CreatedDate = DateTime.Now }; int profileImageID = db.SaveProfileImage(image); db.UpdateUserProfileImage(userID, profileImageID); CurrentUser.UpdateProfileImage(userID, profileImageID); success = true; } catch (Exception e) { throw e; } return(success); }
public virtual async Task <UploadInfo> UploadImageAsync(IFormFile formFile, bool avatar) { if (formFile == null) { throw new Exception("上传文件为空"); } string oldName = formFile.FileName; //原始文件名 string extName = Path.GetExtension(oldName); // 获取扩展名 string newName = StringHelper.GetGuidString() + extName; //构建新的文件名 string webRootPath = this.environment.WebRootPath; if (extName != ".jpg" && extName != ".png" && extName != ".gif" && extName != ".jpeg") { throw new Exception("上传图片仅支持jpg,png,gif格式"); } byte[] bytes = await formFile.GetBytes(); ImageWrapper image = new ImageWrapper(bytes); if (!image.IsReallyImage()) { throw new Exception("上传文件不是真实图片"); } if (avatar) { // 上传头像 string updateMark = "avatar"; string diskPath = Path.Combine(webRootPath, UploadDirectory, updateMark); if (!Directory.Exists(diskPath)) { Directory.CreateDirectory(diskPath); } string filePath = Path.Combine(diskPath, newName); image.Resize(128, 128).SaveToFile(filePath); return(new UploadInfo { DiskPath = filePath, FileName = newName, UrlPath = $"/{UploadDirectory}/{updateMark}/{newName}" }); } else { // 上传图片 string updateMark = "image"; string diskPath = Path.Combine(webRootPath, UploadDirectory, updateMark); if (!Directory.Exists(diskPath)) { Directory.CreateDirectory(diskPath); } string filePath = Path.Combine(diskPath, newName); image.SaveToFile(filePath); return(new UploadInfo { DiskPath = filePath, FileName = newName, UrlPath = $"/{UploadDirectory}/{updateMark}/{newName}" }); } }
public async Task <string> Upload(IFormFile image) { string fileName = Guid.NewGuid().ToString() + "_" + image.FileName; ImagekitResponse response = imagekit.FileName(fileName).Upload(await image.GetBytes()); return(Keys.UrlEndpoint + response.FilePath); }
public static async Task <FileUpload> ToFileUpload(this IFormFile formFile) { return(new FileUpload { Filename = formFile.FileName, Data = await formFile.GetBytes(), ContentType = formFile.ContentType }); }
public async Task <IActionResult> UploadAvatarImage(string userid, [FromForm(Name = "avatardata")] IFormFile avatarpayload) { var result = await _avatarManager.UploadAvatar(userid, await avatarpayload.GetBytes()); if (!result.Succeeded) { return(CreateBadRequestError(result.Errors)); } return(StatusCode(201)); }
public async Task <IActionResult> UploadAsync(IFormFile file) { if (!BlobMethods.IsImage(file)) { return(BadRequest()); } string fileName = await _storage.UploadAsync(file.FileName, await file.GetBytes(), file.ContentType); return(Ok(new { File = fileName })); }
public async Task <IActionResult> UploadFile(IFormFile file) { if (file is null) { return(Content("error")); } var bytes = await file.GetBytes(); return(Content(System.Text.Encoding.UTF8.GetString(bytes))); }
private async Task <MultipartFormDataContent> GetMultipartFormDataContentFromUploadSingleFileAsFormDataRequest(IFormFile request) { var formDataContent = new MultipartFormDataContent(); if (request is not null) { var bytesContent = new ByteArrayContent(await request.GetBytes()); formDataContent.Add(bytesContent, "Request", request.FileName); } return(formDataContent); }
public async Task <JsonResult> UploadProfileImage(Guid personId, IFormFile file) { var person = await _unitOfWork.People.GetOneAsync(x => x.Id == personId); person.ProfileImage = await file.GetBytes(); _unitOfWork.People.Update(person); await _unitOfWork.SaveAsync(); var base64String = Convert.ToBase64String(person.ProfileImage); string resultString = $"data:{file.ContentType};base64,{base64String}"; return(Json(new JsonMessage { Color = "#ff6849", Message = "Logo uploaded", Header = "Success", Icon = "success", AdditionalData = new { src = resultString } })); }
private async Task <NodeEntry> CreateComponentByPath(string documentId, string componentPath, IFormFile component, string ownerId) { var componentPID = await GenerateComponentPID(documentId, "/", GeneratePIDComponentType.Component); return(await _alfrescoHttpClient.CreateNode(AlfrescoNames.Aliases.Root, new FormDataParam( await component.GetBytes(), $"{IdGenerator.GenerateId()}{ System.IO.Path.GetExtension(component.FileName) }" ), ImmutableList <Parameter> .Empty .Add(new Parameter(SpisumNames.Properties.Pid, componentPID, ParameterType.GetOrPost)) .Add(new Parameter(SpisumNames.Properties.Ref, documentId, ParameterType.GetOrPost)) .Add(new Parameter(AlfrescoNames.Headers.NodeType, SpisumNames.NodeTypes.Component, ParameterType.GetOrPost)) .Add(new Parameter(AlfrescoNames.Headers.RelativePath, componentPath ?? SpisumNames.Paths.MailRoomUnfinished, ParameterType.GetOrPost)) .Add(new Parameter(SpisumNames.Properties.FileName, component.FileName, ParameterType.GetOrPost)) .Add(new Parameter(AlfrescoNames.ContentModel.Owner, ownerId, ParameterType.GetOrPost)) .Add(new Parameter(SpisumNames.Properties.Group, _identityUser.RequestGroup, ParameterType.GetOrPost)))); }
public ActionResult <List <(string, double)> > ClasifySong([FromForm] IFormFile file) { if (file.ContentType != "audio/wav" && file.ContentType != "audio/wave") { return(BadRequest()); } try { var results = _songService.ClasifySong(file.GetBytes(), HostingEnvironment.WebRootPath); return(results); } catch (Exception e) { return(BadRequest(e.Message)); } }
public static FileInfo Create(IFormFile file, string createdById, EnumFileType fileType, Guid?personId = null, Guid?organizationId = null, Guid?classId = null) { var result = new FileInfo() { CreatedById = createdById, PersonId = personId, ClassId = classId, OrganizationId = organizationId, Extention = file.ContentType, Name = file.FileName, RealName = Guid.NewGuid().ToString(), Data = file.GetBytes(), FileType = fileType }; return(result); }
public async Task <ServiceResponse <PictureDto> > AddPictureToPostAsync(int postId, IFormFile file) { ServiceResponse <PictureDto> response = new ServiceResponse <PictureDto>(); try { var post = await _db.Posts.FirstOrDefaultAsync(x => x.Id == postId && x.User.Id == int.Parse(_httpContext.HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier))); var exist = await _db.Pictures.Include(x => x.Posts) .Where(c => c.Posts.Select(x => x.Id).Contains(postId)).ToListAsync(); if (post is null) { response.Success = false; response.Message = "Post not found"; } else { var picture = new Picture() { Posts = new List <Post> { post }, Name = file.FileName, Image = file.GetBytes(), Main = exist.Count() == 0 ? true : false }; await _db.Pictures.AddAsync(picture); await _db.SaveChangesAsync(); response.Data = _mapper.Map <PictureDto>(picture); } } catch (Exception ex) { response.Success = false; response.Message = ex.Message; } return(response); }
public async Task <IActionResult> AddImage(IFormFile image) { var tolga = await _newsDal.GetAsync(x => x.Id == 1); tolga.Image = await image.GetBytes(); //var result = _newsDal.UpdateAsync(tolga); //News news = new News //{ // Title = "Deneme", // SubTitle = "Deneme", // Description = "Deneme", // Image = image.GetBytes().Result //}; //_newsDal.AddAsync(news); return(Content("Ok")); }
public async Task <string> UploadImageBlobStorage(string folder, IFormFile file) { ////var fileName = file.GetFilename();' string fileName = $"{Guid.NewGuid().ToString()}{Path.GetExtension(file.FileName)}"; byte[] imageBytes = await file.GetBytes(); //// The parameter to the GetBlockBlobReference method will be the name //// of the image (the blob) as it appears on the storage server. //// You can name it anything you like; in this example, I am just using //// the actual filename of the uploaded image. CloudBlockBlob blockBlob = this.blobContainer.GetBlockBlobReference(this.GetImagePrefix(folder) + fileName); ////blockBlob.Properties.ContentType = "image/" + image.ImageFormat; ////blockBlob.Properties.ContentType = "image/" + file.ContentType; blockBlob.Properties.ContentType = file.ContentType; await blockBlob.UploadFromByteArrayAsync(imageBytes, 0, imageBytes.Length); return(fileName); }
public async Task <PictureDto> AddPictureToPostAsync(int postId, IFormFile file) { var post = await _postRepository.GetByIDAsync(postId); var existingPictures = await _pictureRepository.GetByPostIdAsync(postId); var picture = new Picture() { Posts = new List <Post> { post }, Name = file.FileName, Image = file.GetBytes(), Main = existingPictures.Count() == 0 ? true : false }; var result = await _pictureRepository.AddAsync(picture); return(_mapper.Map <PictureDto>(result)); }
public ActionResult <SongInfoModel> SongAnalyze([FromForm] IFormFile file) { if (file.ContentType != "audio/wav" && file.ContentType != "audio/wave" || file.Length < 1) { return(BadRequest()); } try { var song = _songService.AnalyzeAudioFile(file.GetBytes(), HostingEnvironment.WebRootPath); if (song == null) { return(NotFound("Song not found")); } return(song); } catch (Exception e) { return(BadRequest(e.Message)); } }
private async Task<IActionResult> CreateFile(IFormFile uploadedFile, Guid? flowId = null) { Guid _flowId = flowId == null ? new Guid() : (Guid)flowId; if (uploadedFile != null) { byte[] content = await uploadedFile.GetBytes(); NoSQLFile p = new NoSQLFile(); p.Content = new byte[content.Length]; content.CopyTo(p.Content, 0); p.Name = uploadedFile.FileName; p.BaseEntityGuid = _flowId; await _fileService.Create(p); return Ok(p.Id); } return BadRequest("File was not transferred!"); }
public async Task <bool> UpdateProfileImage(int userID, int profileImageID, IFormFile profileImage) { bool success; try { var image = db.GetProfileImage <tbl_ProfileImage>(profileImageID); image.ProfileImage = await profileImage.GetBytes(); image.CreatedDate = DateTime.Now; db.SaveProfileImage(image); CurrentUser.UpdateProfileImage(userID, profileImageID); success = true; } catch (Exception e) { throw e; } return(success); }
public async Task <IActionResult> AsyncUpload(IFormFile myFile) { // Specifies the target location for the uploaded files string targetLocation = Path.Combine(_hostingEnvironment.WebRootPath, "uploads"); try { if (!Directory.Exists(targetLocation)) { Directory.CreateDirectory(targetLocation); } using (var fileStream = System.IO.File.Create(Path.Combine(targetLocation, myFile.FileName))) { myFile.CopyTo(fileStream); } } catch { Response.StatusCode = 400; } byte[] fileBytes = await myFile.GetBytes(); return(new ContentResult() { Content = Convert.ToBase64String(fileBytes) }); }
/// <summary> Checks if a file is an image. </summary> public static bool IsImage(this IFormFile file) { return(file.GetBytes().IsImage()); }
/// <summary> Converts a file to an image. </summary> public static Image <Rgb24> ToImage(this IFormFile file) { return(file.GetBytes().ToImage()); }
public async Task <NodeEntry> UploadNewVersionComponent(string nodeId, string componentId, IFormFile component) { return(await UploadNewVersionComponent(nodeId, componentId, await component.GetBytes(), component.FileName, component.ContentType)); }
public async Task <IActionResult> ChangeTaskWithFile(IFormFile file, string framework) { if (file != null) { var isAlive = await CheckIfAlive(_config.CompilerServicesOrchestrator); if (isAlive) { var req = new CompilationRequest { File = await file.GetBytes(), Framework = framework }; string url = _config.CompilerServicesOrchestrator.GetFullTaskLinkFrom(_config.FrontEnd); using var httpClient = new HttpClient(); using var form = JsonContent.Create(req); HttpResponseMessage response = await httpClient.PostAsync(url, form); string apiResponse = await response.Content.ReadAsStringAsync(); if (response.IsSuccessStatusCode) { CompilationResponse compResponse = JsonConvert.DeserializeObject <CompilationResponse>(apiResponse); if (compResponse.OK) { string dirPath = "c:/TemporaryTaskDownloads"; dirPath += "/" + Guid.NewGuid().ToString(); while (Directory.Exists(dirPath)) { dirPath += "/" + Guid.NewGuid().ToString(); } var dir = Directory.CreateDirectory(dirPath); string fullPath = dirPath + "/" + file.Name; System.IO.File.WriteAllBytes(fullPath, compResponse.File); ZipFile.ExtractToDirectory(fullPath, dirPath, true); var pathToDll = FindAssemblyFile(dir, ".dll"); if (pathToDll == null) { pathToDll = FindAssemblyFile(dir, ".exe"); } List <ClassDefinition> result = null; if (pathToDll != null) { result = ConvertProject(pathToDll); } dir.Delete(true); if (result != null) { var response1 = new { status = "success", data = result }; return(Json(response1)); } else { var response2 = new { status = "error", data = "No dll or exe file found!" }; return(Json(response2)); } } var response3 = new { status = "error", data = "Compilation container returned error with message: " + compResponse.Message }; return(Json(response3)); } var response4 = new { status = "error", data = "Compilation container returned " + response.StatusCode + " !" }; return(Json(response4)); } var response5 = new { status = "error", data = "Compilation serviec is dead!" }; return(Json(response5)); } var response6 = new { status = "error", data = "No file uploaded!" }; return(Json(response6)); }
public async Task <NodeEntry> CheckOutputFormat(string nodeId, IFormFile componentFile) => await CheckOutputFormat(nodeId, await componentFile.GetBytes(), componentFile.ContentType);