public dynamic Upload(IFormCollection form) { try { //Map từ formcollection sang Loai var lo = new Loai(); if (form.Any()) { if (form.Keys.Contains("tenLoai")) { lo.TenLoai = form["tenLoai"]; } if (form.Keys.Contains("moTa")) { lo.TenLoai = form["moTa"]; } } //xử lý uplaod hình foreach (var file in form.Files) { UploadFile(file); } //lo.Hinh = form.Files[0].FileName; //a.png;b.png;c.jpg lo.Hinh = string.Join(";", form.Files.Select(p => p.FileName)); _context.Add(lo); _context.SaveChanges(); return(new { Success = true }); } catch (Exception ex) { return(new { Success = false, ex.Message }); } }
public async Task <IActionResult> UpdatePicture(UserPicturePostRequest model) { try { if (!ModelState.IsValid) { throw new Exception("Petición de subir imagen inválida"); } IFormCollection formCollection = await Request.ReadFormAsync(); if (formCollection == null || !formCollection.Any()) { throw new Exception("No se ha encontrado la imagen en la llamada"); } IFormFile file = formCollection.Files.First(); if (file == null || file.Length == 0) { throw new Exception("No se ha encontrado la imagen en la llamada"); } return(Ok(await _userService.UpdatePictureAsync(file, model.UserId, _configuration, _userManager))); } catch (Exception e) { return(StatusCode(500, e.Message)); } }
private static Person MapFormCollectionToPerson(IFormCollection form) { var person = new Person(); string firstNameKey = "firstName"; string lastNameKey = "lastName"; string phoneNumberKey = "phoneNumber"; if (form.Any()) { if (form.Keys.Contains(firstNameKey)) { person.FirstName = form[firstNameKey]; } if (form.Keys.Contains(lastNameKey)) { person.LastName = form[lastNameKey]; } if (form.Keys.Contains(phoneNumberKey)) { person.PhoneNumber = form[phoneNumberKey]; } } return(person); }
public async Task <IActionResult> DeleteRole(DeleteRoleModel model, IFormCollection collection) { if (model == null) { throw new ArgumentNullException(nameof(model)); } if (ModelState.IsValid) { if (collection.Any(x => string.Equals(x.Key, "delete", StringComparison.OrdinalIgnoreCase))) { var r = await _roleMgr.FindByNameAsync(model.Role); model.Result = await _roleMgr.DeleteAsync(r); return(RedirectToAction(nameof(ManageRoles))); } else { return(RedirectToAction(nameof(ManageRoles))); } } else { model.Result = IdentityResult.Failed(); LogValidationErrors(); } return(View(model)); }
public Task BindModelAsync(ModelBindingContext bindingContext) { GateWayModel model = null; HttpRequest req = bindingContext.ActionContext.HttpContext.Request; if (req.HasFormContentType) { IFormCollection form = req.Form; if (form != null && (form.Any() || form.Files.Any())) { if (form.Files.Any()) { List <FileData> list = new List <FileData>(); foreach (IFormFile file in form.Files) { using (Stream sr = file.OpenReadStream()) { byte[] bytes = new byte[sr.Length]; sr.ReadAsync(bytes, 0, bytes.Length); FileData thisFile = new FileData { FileName = file.FileName, Data = Convert.ToBase64String(bytes) }; list.Add(thisFile); } } Dictionary <string, object> data = new Dictionary <string, object> { { "files", list } }; model = new GateWayModel(data); } else { model = new GateWayModel(form); } } } else { Stream body = req.Body; if (body != null) { try { model = new GateWayModel(body); } catch (Exception) { throw; } } } bindingContext.ModelState.SetModelValue("model", model, null); bindingContext.Result = ModelBindingResult.Success(model); return(Task.CompletedTask); }
private static IFormCollection GetParameters(IFormCollection parameters) { if (!parameters.Any()) { throw new ArgumentException($"{parameters.GetType().Name} does not contain any parameter."); } return(parameters); }
public ActionResult Start(IFormCollection form) { if (!form.Any()) { return(RedirectToAction("Index")); } string selectedCategory = Convert.ToString(form.First().Value); logger.Event(selectedCategory); return(RedirectToAction("Index", "Question", new { category = selectedCategory })); }
/// <summary> /// 发送内容 /// </summary> /// <param name="authorization"></param> /// <param name="files"></param> /// <returns></returns> public async Task <string> SendContentAsync(string authorization, IFormCollection files) { if (files.Any(f => f.Value.Count == 0)) { return("不存在内容"); } //var uid = files["Uid"].FirstOrDefault(); var user = await GetUserAsync(authorization); if (user == null) { return("不存在此用户"); } return(await SendContentAsync(user, files)); }
public async Task <IActionResult> Post(IFormCollection form) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (Auth.Credentials != null && Tweetinvi.User.GetAuthenticatedUser(Auth.Credentials) != null) { try { string strTweet = string.Empty; if (form.Any() && form.Keys.Contains("TweetString")) { strTweet = form["TweetString"]; } IFormFile file = form.Files.FirstOrDefault(); if (!string.IsNullOrEmpty(strTweet)) { ITweet publishedTweet = Auth.ExecuteOperationWithCredentials(Auth.Credentials, () => { var publishOptions = new PublishTweetOptionalParameters(); if (file != null) { var fileBytes = GetByteArrayFromFile(file); publishOptions.MediaBinaries.Add(fileBytes); } return(Tweetinvi.Tweet.PublishTweet(strTweet, publishOptions)); }); bool success = publishedTweet != null; var routeValueParameters = new Dictionary <string, object>(); routeValueParameters.Add("id", publishedTweet == null ? (Nullable <long>)null : publishedTweet.Id); routeValueParameters.Add("actionPerformed", "Publish"); routeValueParameters.Add("success", success); return(Ok()); } } catch (Exception e) { throw; } } return(StatusCode(StatusCodes.Status500InternalServerError)); }
//load output properties from request (sorting field and sorting direction) public OutputProperties MapFormCollectionToOutputProperties(IFormCollection form) { OutputProperties outProps = null; string SortFieldKey = "SortField"; string SortDirectionKey = "SortDirection"; if (form.Any()) { if (form.Keys.Contains(SortFieldKey)) { outProps = new OutputProperties(); outProps.SortField = form[SortFieldKey]; if (form.Keys.Contains(SortDirectionKey)) { outProps.SortDirection = form[SortDirectionKey]; } } } return(outProps); }
//[AllowAnonymous] public async Task <IActionResult> SendContent(IFormCollection files) { /* * var fss = files.Files.Select(f => new { f.Name, f.Length }); * var dic = new Dictionary<string, string[]>(); * for (int i = 0; i < files.Keys.Count; i++) * { * dic.Add(files.Keys.ElementAt(i), files[files.Keys.ElementAt(i)]); * Console.WriteLine($"{files.Keys.ElementAt(i)}, {files[files.Keys.ElementAt(i)].FirstOrDefault()}"); * } * //var title = dic["title"].FirstOrDefault(); * return await Task.FromResult(Json(new {dic, dic.Count, fss })); */ if (files.Any(f => f.Value.Count == 0)) { return(BadRequest("模型验证失败")); } //var uid = files["Uid"].FirstOrDefault(); var tokendec = GetTokenDec(); if (tokendec == null) { return(BadRequest("token 验证失败")); } var content = files["Content"].FirstOrDefault(); var title = files["Title"].FirstOrDefault(); var label = files["Label"].FirstOrDefault(); //创建keypairs var res = await _contentRepository.SendContentAsync(await FindIdByName(tokendec.sub), content, title, label, -1, files.Files.Select(f => new FormFileModel(f))); if (res != null) { return(BadRequest(res)); } return(Ok()); }
public async Task <IActionResult> DeleteUser(DeleteUserModel model, IFormCollection collection) { if (model == null) { throw new ArgumentNullException(nameof(model)); } if (ModelState.IsValid) { if (collection.Any(x => string.Equals(x.Key, "delete", StringComparison.OrdinalIgnoreCase))) { var user = await _userMgr.FindByNameAsync(model.Username); try { model.Result = await _userMgr.DeleteAsync(user); return(RedirectToAction(nameof(ManageUsers))); } catch (Exception ex) { _log.LogError(ex, "there was an error deleting the user"); } } else { return(RedirectToAction(nameof(ManageUsers))); } } else { model.Result = IdentityResult.Failed(); LogValidationErrors(); } return(View(model)); }
public async Task <IActionResult> Index(IFormFile file, IFormCollection form) { MeshResultModel model = new MeshResultModel(); model.Original = new MeshDetailModel(); model.Result = new MeshDetailModel(); string webRootPath = _env.WebRootPath; string randomFilePath = Path.GetRandomFileName().Replace(".", ""); string relativeFolderPath = Path.Combine("models", "obj", randomFilePath); string newPath = Path.Combine(webRootPath, relativeFolderPath); if (!Directory.Exists(newPath)) { Directory.CreateDirectory(newPath); } var urlPath = relativeFolderPath.Replace("\\", "/"); model.Original.RelativeFolderPath = urlPath; model.Result.RelativeFolderPath = urlPath; List <ScriptParameterFilter> lstScriptParams = new List <ScriptParameterFilter>(); if (form != null && form.Any()) { foreach (var keyValuePair in form.ToList()) { var kp = keyValuePair.Key.Split("#"); if (kp.Length == 2) { var sp = lstScriptParams.FirstOrDefault(a => a.FilterName == kp[0]); if (sp == null) { sp = new ScriptParameterFilter(); sp.FilterName = kp[0]; lstScriptParams.Add(sp); } if (sp.FilterParameter == null) { sp.FilterParameter = new Dictionary <string, string>(); } sp.FilterParameter.Add(kp[1], keyValuePair.Value); } } } if (file?.Length > 0) { model.Original.Filename = file.FileName; var originalFilePath = await saveOriginalFile(file, newPath); HttpClient hc = new HttpClient(); hc.Timeout = TimeSpan.FromHours(2); Client c = new Client(_appSettings.RestApiUrl, hc); FileParameter fileParameter = new FileParameter(file.OpenReadStream(), file.FileName, file.ContentType); JobResult jobResult = null; try { jobResult = await c.UploadJobAsync(fileParameter, JsonConvert.SerializeObject(lstScriptParams), form.FirstOrDefault().Value, form.FirstOrDefault(a => a.Key == "selectedOutputFormat").Value); } catch (Exception e) { //TODO: Schöner ViewBag.Error = "Error at uploading."; ViewBag.Code = e.ToString(); return(View("Error")); } if (jobResult != null && jobResult.ResultCode.Number != JobResultCodeNumber._0) { //Job wasn't finished successfull ViewBag.Error = jobResult.ResultCode.Message; ViewBag.Code = jobResult.ResultCode.Number; return(View("Error")); } else if (jobResult != null) { var resultFile = await c.DownloadJobFileResultAsync(jobResult.FileResultName, jobResult.JobId, newPath); model.Result.Filename = resultFile; model.Result.AdditionalValues = new Dictionary <string, string>(jobResult.AdditionalData); model.Result.FileSize = jobResult.FileResultSize; model.Result.NumberOfFaces = jobResult.ResultNumberOfFaces; model.Result.NumberOfVertices = jobResult.ResultNumberOfVertices; model.ReducedBy = jobResult.ReducedBy; model.Original.FileSize = jobResult.FileInputSize; ViewBag.Link = $"{_appSettings.RestApiUrl}/api/DownloadLogForJob/{jobResult.JobId}"; } } else { //no file selected ViewBag.Error = "Please select file"; ViewBag.Code = ""; return(View("Error")); } return(View("~/Views/Visualization/ModelResultPreview.cshtml", model)); }