public async Task <IActionResult> Upload(int id) { IActionResult result; try { Contato contato = await repository.GetAsync(id); if (contato == null) { return(NotFound()); } var modelo = new UploadFileViewModel() { Id = id }; return(View(modelo)); } catch (Exception) { result = StatusCode(StatusCodes.Status500InternalServerError, "Ocorreu um erro ao enviar"); } return(result); }
//Add Attachment internal int AddAttachment(UploadFileViewModel uploadFile) { FileLogic fl = new FileLogic(); UnicodeEncoding encoding = new UnicodeEncoding(); // byte[] fileByteArray = encoding.GetBytes(uploadFile.fileByteArray); string newName = Guid.NewGuid().ToString(); try { fl.WriteFileToDisk(uploadFile.fileByteArray, newName); } catch (Exception ex) { throw ex; } Fisiere att = new Fisiere() { Path = HttpContext.Current.Server.MapPath(Utils.GetAppSettings.GetAttachmentDirectoryPath() + "\\" + newName), Name = uploadFile.Name, FileType = uploadFile.FileType, IdStudent = uploadFile.IdStudent }; //uploadFile.receivableAttachment.Path = HttpContext.Current.Server.MapPath(attachementDirectory.GetAttachmentDirectoryPath()); // cl.AddAttachment(att); var newatt = _fisiereServices.Add(att); return(newatt.Id); }
public async Task <ActionResult> Upload(HttpPostedFileBase file) { var model = new UploadFileViewModel(); if (file == null || file.ContentLength <= 0) { ModelState.AddModelError("File", "Invalid File request received "); return(View(model)); } if (!_allowedExtensions.Contains(file.FileName.Substring(file.FileName.LastIndexOf('.')))) { ModelState.AddModelError("File", "Please file of type: " + string.Join(", ", _allowedExtensions)); return(View(model)); } try { var path = Path.Combine(Path.GetTempPath(), Path.GetFileName(file.FileName)); file.SaveAs(path); var results = Task.Run(() => _parserService.ParseFile(path)); model = new UploadFileViewModel() { Result = results.Result }; ViewBag.Message = "File uploaded successfully"; } catch (Exception ex) { ViewBag.Message = "ERROR:" + ex.Message.ToString(); } return(View(model)); }
public UploadFileViewModel POST(RouteUploadFile request) { var uploadVm = new UploadFileViewModel(); var files = Request.Files; if (files.Length == 1) { var file = files[0]; #region 文件 try { if (null != file && file.ContentLength != 0L) { var info = ZZTXManager.GetADCDInfoByADCD(adcd); if (info == null) { throw new Exception("用户信息为空请重新登陆!"); } var fileFolde = "/Upload/" + (info == null ? adcd : info.adnm) + (request.fileFolde != null && request.fileFolde.Trim() != "" ? "/" + request.fileFolde : ""); // " / Upload/funds/DocumentBasis"; var allowedFileTypes = request.allowedFileTypes; // "doc,docx,pdf"; var allowedFileSize = request.allowedFileSize != 0 ? request.allowedFileSize : 20480; // 20480; var fileName = file.FileName; if (fileName.Contains(":")) { var lastIndex = fileName.LastIndexOf("\\"); var leftLength = fileName.Length - lastIndex - 1; fileName = fileName.Substring(lastIndex + 1, leftLength); } /*第一步上传文件*/ FileUploader uploader = new FileUploader(fileFolde, DateTime.Now.ToString("yyyyMMddHHmmssff-") + fileName.Trim(), allowedFileTypes, allowedFileSize); var flag = uploader.UploadFile(file); uploadVm.isSuccess = flag; if (flag) { uploadVm.fileName = fileName.Substring(0, fileName.LastIndexOf(".")); uploadVm.fileSrc = uploader.SaveFilePath; uploadVm.flieSize = (file.ContentLength / 1024) + "kb"; uploadVm.fileType = fileName.Substring(fileName.LastIndexOf(".") + 1, fileName.Length - fileName.LastIndexOf(".") - 1); uploadVm.message = "上传成功"; } else { uploadVm.message = "上传失败"; } } }catch (Exception ex) { uploadVm.isSuccess = false; uploadVm.message = "文件超出规定大小5MB"; } #endregion 文件 } return(uploadVm); }
public JsonResult UploadFileImage(UploadFileViewModel uploadFileViewModel) { RestaurantDBEntities db = new RestaurantDBEntities(); int imgId = 0; ////var file = model.UploadFileImageWrapper; //// Get all files from Request object //HttpFileCollectionBase files = Request.Files; //HttpPostedFileBase file = files[0]; HttpPostedFileBase file = uploadFileViewModel.httpPostedUploadFileImage; byte[] imagebyte = null; if (file != null) { // Get the complete folder path and store the file inside it. string fname = Path.Combine(Server.MapPath("~/Upload/img/temp"), file.FileName); file.SaveAs(fname); BinaryReader reader = new BinaryReader(file.InputStream); imagebyte = reader.ReadBytes(file.ContentLength); //Not use mapper //Using directly to Model UploadFile img = new UploadFile(); img.UploadFileName = file.FileName; img.UploadFileImage = imagebyte; img.UploadFilePath = "/Upload/img/temp/" + file.FileName; img.UploadFileId = uploadFileViewModel.UploadFileId; img.SubCatagoryId = uploadFileViewModel.SubCatagoryId; img.UploadFileVersion = uploadFileViewModel.UploadFileVersion; //DBset db.UploadFiles.Add(img); db.SaveChanges(); imgId = img.UploadFileId; } return(Json(imgId, JsonRequestBehavior.AllowGet)); }
public ActionResult Index() { // Authentican code will be to pass user identity to signalR and signalR will notify to that user. var authenticationManager = HttpContext.GetOwinContext().Authentication; if (authenticationManager != null) { if (authenticationManager.User == null || authenticationManager.User.Identity == null || string.Compare(Session.SessionID, authenticationManager.User.Identity.Name, StringComparison.OrdinalIgnoreCase) != 0) { var claims = new List <Claim> { new Claim(ClaimTypes.Name, Session.SessionID), new Claim(ClaimTypes.NameIdentifier, Guid.NewGuid().ToString()) }; var identity = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie); authenticationManager.SignIn(new AuthenticationProperties { IsPersistent = false }, identity); Session["Authenticated"] = true; } } var viewModel = new UploadFileViewModel(); return(View(viewModel)); }
public ActionResult Index(string id = "Undefined") { var condition = new ConditionViewModel <UserFile>() { ChangeOrderDirection = false, OrderDirection = "desc" }; if (string.IsNullOrEmpty(id)) { condition.Func = d => d.Deleted != true && d.Category == "Undefined"; } else { condition.Func = d => d.Deleted != true && d.Category == id; } condition.PerPageSize = 300; condition.CurrentPage = 1; var viewModel = new UploadFileViewModel(); viewModel.CategoryList = _db.Get <UserFile>(d => d.Deleted != true).GroupBy(d => d.Category).Select(g => new SelectListItem { Text = g.Key, Value = g.Key, Selected = g.Key == id }).ToArray(); viewModel.Data = _db.GetSearchResult(condition, d => d.OperationDate, null); return(View(viewModel)); }
public async Task <bool> SaveUploadedFile(UploadFileViewModel uploadedFile) { var stream = uploadedFile.FormFile.OpenReadStream(); var storageUri = await _blobStorage.UploadFile(stream, uploadedFile.FormFile.FileName); var file = new File { StorageUrl = storageUri.AbsolutePath, Guid = Guid.NewGuid(), Name = uploadedFile.FormFile.FileName, HistoryEntries = new List <BlockchainHistory>() }; using (var md5 = MD5.Create()) { stream.Position = 0; var isSuccess = await _ethereumStorage.SendDocumentHashToChain(Convert.ToBase64String(md5.ComputeHash(stream)), file.Guid.ToString()); if (!isSuccess) { return(false); } } file.HistoryEntries.Add(new BlockchainHistory { Timestamp = DateTime.Now, Status = BlockchainStatuses.Verified }); await _filesRepository.SaveAsync(file); return(true); }
public ActionResult Index(UploadFileViewModel ufViewModel) { PaginationInfo pager = new PaginationInfo(); try { if (TempData["FriendlyMessage"] != null) { ufViewModel.FriendlyMessage.Add((FriendlyMessage)TempData["FriendlyMessage"]); } pager = ufViewModel.Pager; ufViewModel.attachments = _attachmentsMan.Get_Attachments(ref pager); // //ufViewModel.Pager = pager; //ufViewModel.Pager.PageHtmlString = PageHelper.NumericPager("javascript:PageMore({0})", ufViewModel.Pager.TotalRecords, ufViewModel.Pager.CurrentPage + 1, ufViewModel.Pager.PageSize, 10, true); // } catch (Exception ex) { Logger.Error("Error : " + ex.ToString()); ufViewModel.FriendlyMessage.Add(MessageStore.Get("SYS01")); } return(View("Index", ufViewModel)); }
public async Task <IActionResult> NewDocument(Guid projectId, UploadFileViewModel model) { if (model.File == null || model.File.Length == 0) { TempData["message"] = $"{_locService.GetLocalizedHtmlString("noDocAttached")}"; return(RedirectToAction("NewDocument")); } if (model.File.Length > 11000000) { TempData["message"] = $"{_locService.GetLocalizedHtmlString("maxSizeValidation")}"; return(RedirectToAction("NewDocument")); } var docType = await _context.DocumentTypes.Where(w => w.Id == model.DocumentTypeId).SingleOrDefaultAsync(); var type = model.File.FileName.Substring(model.File.FileName.Length - 5); var extArray = model.File.FileName.Split("."); var ext = $".{extArray.Last()}"; if (ext != docType.Name) { TempData["message"] = $"{_locService.GetLocalizedHtmlString("formatsValidation")}"; return(RedirectToAction("NewDocument")); } var docName = ""; if (model.File.FileName.Contains("\\")) { var array = model.File.FileName.Split("\\"); docName = array.Last(); } else { docName = model.File.FileName; } var exist = await _context.ProjectDocuments.Where(x => x.Name == docName && x.ProjectId == projectId).FirstOrDefaultAsync(); if (exist != null) { TempData["message"] = $"{_locService.GetLocalizedHtmlString("docexists")}"; return(RedirectToAction("NewDocument")); } switch (docType.Name) { case ".xml": await LoadXmlDocumentAsync(projectId, model, docName); return(RedirectToAction("ProjectDocument")); default: TempData["message"] = $"{_locService.GetLocalizedHtmlString("falseFormat")}"; return(RedirectToAction("NewDocument")); } }
public IActionResult UploadMapperFile() { var viewModel = new UploadFileViewModel(); viewModel.UploadFileTypes = ExcelLoanServices.GetUploadFileTypes().Select(m => new SelectListItem() { Text = m.Description, Value = m.ID.ToString() }).ToList(); return(View(viewModel)); }
public IActionResult Upload(UploadFileViewModel model) { if (!ModelState.IsValid) { return NotFound(); } SaveToDatabase(model); return RedirectToAction(nameof(Index)); }
public async Task <IActionResult> Post([FromForm] UploadFileViewModel model) { if (!ModelState.IsValid) { return(BadRequest(GetModelStateErrorResponse(ModelState))); } var resp = await Save(model); return(Ok(resp)); }
public async Task <IActionResult> UploadFile([FromRoute] UploadFileViewModel model) { try { var fileModel = _mapper.Map <UploadFileViewModel, UploadFileDto>(model); await _contentService.UploadFileAsync(fileModel); return(Ok()); } catch { return(BadRequest()); } }
public static UploadFile AsDatabaseModel(UploadFileViewModel model) { return(new UploadFile() { ID = model.ID, IsActive = model.IsActive, UploadDate = model.UploadDate, UploadFileTypeID = model.FileTypeID, UploadFileData = model.FileBytes, FileName = model.UploadFile.FileName }); }
private async Task LoadXmlDocumentAsync(Guid projectId, UploadFileViewModel model, string docName) { using (var memoryStream = new MemoryStream()) { await model.File.CopyToAsync(memoryStream); memoryStream.Position = 0; XmlDocument docs = new XmlDocument(); docs.Load(memoryStream); XmlNodeList dataNodes = docs.GetElementsByTagName("data"); var lang = await _context.Languages.Where(w => w.Id == model.LanguageId).SingleOrDefaultAsync(); var project = await _context.Projects.Where(x => x.Id == projectId).SingleOrDefaultAsync(); var doc = await _context.DocumentTypes.Where(w => w.Id == model.DocumentTypeId).SingleOrDefaultAsync(); var projectDocument = new ProjectDocument { Name = docName, Language = lang, Project = project, DocumentType = doc, AddedDate = DateTime.Now }; _context.Add(projectDocument); if (_context.SaveChanges() > 0) { foreach (XmlNode item in dataNodes) { var nodeId = item.Attributes["name"].Value; var nodeValue = item.SelectSingleNode("value").InnerText; var dictionary = new ProjectDocumentDictionary { Document = projectDocument, Name = nodeId, Value = nodeValue }; _context.Add(dictionary); } var pro = _context.Projects.Where(w => w.Id == projectId).FirstOrDefault(); pro.HasDocument = true; _context.Update(pro); await _context.SaveChangesAsync(); } } }
public async Task <IActionResult> Index(UploadFileViewModel model) { var token = HttpContext.Request.Cookies["__token"]?.ToString(); if (!authentication.HasValidToken(token)) { return(RedirectToAction("Login")); } if (!ModelState.IsValid) { return(View(new UploadFileViewModel())); } if (!authentication.AuthenticateUploadAttempt(token, model.Password)) { logger.LogInformation("Incorrect password"); return(View(new UploadFileViewModel())); } logger.LogInformation("Uploading file. Name: {0}, Content Type: {1}", model.File.FileName, model.File.ContentType); if (!ValidUpload(model)) { logger.LogInformation("File format was incorrect. {0}", model.File.ContentType); return(View(new UploadFileViewModel())); } switch (model.SelectedType) { case UploadType.Post: await postRepository.CreatePost(model.File); break; case UploadType.Image: await imageRepository.UploadImage(model.Folder, model.File); break; default: break; } return(RedirectToAction("Success")); }
public UserFile CreateModel(UploadFileViewModel viewModel, UserFile datamodel) { var result = datamodel; result.Name = viewModel.Name; result.ContentType = viewModel.ContentType; result.Global = viewModel.Global; result.IsTemp = !viewModel.IsPermanent; result.CreatedUTC = viewModel.Created; return result; }