public IActionResult Create(DoucumentsViewModel documents) { try { var docNameExists = _IDocuments.checkDocumentnameExists(documents.dbModel.name); if (docNameExists) { TempData["MessageRegistration"] = "Document Name already exists."; } else { var uploadFileName = string.Empty; if (HttpContext.Request.Form.Files != null) { var fileName = string.Empty; string PathDB = string.Empty; var files = HttpContext.Request.Form.Files; if (files == null) { ModelState.AddModelError("", "Upload a document"); return(View(documents.dbModel)); } if (!ModelState.IsValid) { return(View(documents.dbModel)); } var uploads = Path.Combine(_env.WebRootPath, "files"); foreach (var file in files) { if (file.Length > 0) { fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"'); if (fileName.EndsWith(".txt") || fileName.EndsWith(".pdf") || fileName.EndsWith(".docx") || fileName.EndsWith(".doc")) { var myUniqueFileName = Convert.ToString(Guid.NewGuid()); var FileExtension = Path.GetExtension(fileName); uploadFileName = myUniqueFileName + FileExtension; fileName = Path.Combine(_env.WebRootPath, "files") + $@"\{uploadFileName}"; PathDB = uploadFileName; using (FileStream fs = System.IO.File.Create(fileName)) { file.CopyTo(fs); fs.Flush(); } } else { ModelState.AddModelError("", "Invalid document format. Please upload a file with extension .pdf, .txt, .docx or .doc"); return(View(documents.dbModel)); } } } documents.dbModel.file = PathDB; documents.dbModel.created_at = documents.dbModel.updated_at = DateTime.Now; if (_IDocuments.Commit(documents.dbModel, 0) > 0) { TempData["MessageRegistration"] = "Document Name successfully added."; //return View(documents.dbModel); return(RedirectToAction("Index")); } else { return(View(documents.dbModel)); } } } return(View(documents.dbModel)); } catch (Exception) { throw; } }
public IActionResult Add(Venue Venue) { var newFileName = string.Empty; var dateTime = DateTime.Now; if (HttpContext.Request.Form.Files != null) { var fileName = string.Empty; string PathDB = string.Empty; var files = HttpContext.Request.Form.Files; if (files == null) { ModelState.AddModelError("", "Upload Venue Photo !"); return(View()); } if (!ModelState.IsValid) { return(View("Venue")); } var uploads = Path.Combine(_environment.WebRootPath, "VenueImages"); foreach (var file in files) { if (file.Length > 0) { fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"'); var myUniqueFileName = Convert.ToString(Guid.NewGuid()); var FileExtension = Path.GetExtension(fileName); newFileName = myUniqueFileName + FileExtension; fileName = Path.Combine(_environment.WebRootPath, "VenueImages") + $@"\{newFileName}"; PathDB = "VenueImages/" + newFileName; using (FileStream fs = System.IO.File.Create(fileName)) { file.CopyTo(fs); fs.Flush(); } } } Venue objvenue = new Venue { VenueFilename = newFileName, VenueFilePath = PathDB, VenueID = 0, VenueName = Venue.VenueName, VenueCost = Venue.VenueCost, Createdate = dateTime.Date, Createdby = Convert.ToInt32(HttpContext.Session.GetString("UserID")) }; _IVenue.SaveVenue(objvenue); TempData["VenueMessage"] = "Venue Saved Successfully"; ModelState.Clear(); return(View(new Venue())); } return(View(Venue)); }
//public ViewResult Insert(RecipeModel recipeModel, string[] IngredientString) public ViewResult Insert(RecipeModel recipeModel) { if (ModelState.IsValid) { recipeModel.Recipe.DateTimeUpdate = DateTime.Now; long size = 0; string fileName = Request.Form.Files.ElementAt(0).FileName.ToString(); foreach (var file in Request.Form.Files) { var filename = ContentDispositionHeaderValue .Parse(file.ContentDisposition) .FileName .Trim('"'); filename = this.ihostingEnvironment.WebRootPath + url + fileName; var urlfilename = this.ihostingEnvironment.WebRootPath + url + fileName; size += file.Length; using (FileStream fs = System.IO.File.Create(filename)) { file.CopyTo(fs); fs.Flush(); } } //The end of Upload File if (iRecipeRepo.Recipes.Where(r => r.RecipeId == recipeModel.Recipe.RecipeId).Count() == 0) { recipeModel.Recipe.FileToUpload = url + fileName; //Insert new recipe in recipe table iRecipeRepo.AddRecipe(recipeModel.Recipe); /** * It is being generated loop to create ingredientDetail and RecipeIngredient table * at the same time as much as the number of Ingredients by user */ foreach (string ingredientString in recipeModel.IngredientString) { if (string.IsNullOrEmpty(ingredientString)) { Console.WriteLine("There is a empty or null in the ingredient detail by the user input (ingredientString is null) in the recipe Id [" + recipeModel.Recipe.RecipeId + "]"); } else { IngredientDetail ingredientDetail = new IngredientDetail(); ingredientDetail.IngredientString = ingredientString; //Insert Ingredients details (IngredientString) of New Recipe in IngredientDetail Table iIngredientDetailRepo.AddIngredientDetail(ingredientDetail); // Insert Ingredients of New Recipe in RecipeIngredient Table as Bridge Table for many to many relations // Between Recipe and IngredientDetail Table (Ingredient Informations) iRecipeIngredientRepo.AddRecipeIngredient( recipeModel.Recipe.RecipeId, ingredientDetail); } } // Insert data (Model ID : 1, 2, 3 by the relationship Modal of new recipe) in RecipeModal Table as bridge table between recipe and Model (Model Id: 1, 2, 3) //to display View/Edit/Delete Button in "Data/List.cshtml" recipeModel.AllModalDetails = iModalDetailRepo.ModalDetails.ToList <ModalDetail>(); foreach (ModalDetail modalDetail in recipeModel.AllModalDetails) { iRecipeModalRepo.AllRecipeModal(recipeModel.Recipe.RecipeId, modalDetail); } return(View("../Recipe/Display", new SearchRecipeModel { RecipeCollection = iRecipeRepo.Recipes })); } else { return(View("Insert", recipeModel)); } } else { return(View("Insert", recipeModel)); } }
public static string GetFilename(this IFormFile file) { return(ContentDispositionHeaderValue.Parse( file.ContentDisposition).FileName.ToString().Trim('"')); }
public async Task <IActionResult> Edit( Note model, ICollection <IFormFile> files, int id, string previousFileName = "", int previousFileSize = 0) { ViewBag.FormType = BoardWriteFormType.Modify; ViewBag.TitleDescription = "글 수정 - 아래 항목을 수정하세요."; ViewBag.SaveButtonText = "수정"; string fileName = ""; int fileSize = 0; if (previousFileName != null) { fileName = previousFileName; fileSize = previousFileSize; } //파일 업로드 처리 시작 var uploadFolder = Path.Combine(_environment.WebRootPath, "files"); foreach (var file in files) { if (file.Length > 0) { fileSize = Convert.ToInt32(file.Length); // 파일명 중복 처리 fileName = Dul.FileUtility.GetFileNameWithNumbering( uploadFolder, Path.GetFileName( ContentDispositionHeaderValue.Parse( file.ContentDisposition).FileName.Trim('"'))); // 파일업로드 using (var fileStream = new FileStream( Path.Combine(uploadFolder, fileName), FileMode.Create)) { await file.CopyToAsync(fileStream); } } } Note note = new Note(); note.Id = id; note.Name = model.Name; note.Email = Dul.HtmlUtility.Encode(model.Email); note.Homepage = model.Homepage; note.Title = Dul.HtmlUtility.Encode(model.Title); note.Content = model.Content; note.FileName = fileName; note.FileSize = fileSize; note.Password = (new Dul.Security.CryptorEngine()).EncryptPassword(model.Password); note.ModifyIp = HttpContext.Connection.RemoteIpAddress.ToString(); // IP 주소 note.Encoding = model.Encoding; int r = _repository.UpdateNote(note); // 데이터베이스에 수정 적용 if (r > 0) { TempData["Message"] = "수정되었습니다."; return(RedirectToAction("Details", new { Id = id })); } else { ViewBag.ErrorMessage = "업데이트가 되지 않았습니다. 암호를 확인하세요."; return(View(note)); } }
public IActionResult Add(Flower Flower) { var newFileName = string.Empty; if (HttpContext.Request.Form.Files != null) { var fileName = string.Empty; string PathDB = string.Empty; var files = HttpContext.Request.Form.Files; if (files == null) { ModelState.AddModelError("", "Upload Flower Photo !"); return(View()); } if (!ModelState.IsValid) { return(View("Add")); } var uploads = Path.Combine(_environment.WebRootPath, "FlowerImages"); foreach (var file in files) { if (file.Length > 0) { fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"'); var myUniqueFileName = Convert.ToString(Guid.NewGuid()); var FileExtension = Path.GetExtension(fileName); newFileName = myUniqueFileName + FileExtension; fileName = Path.Combine(_environment.WebRootPath, "FlowerImages") + $@"\{newFileName}"; PathDB = "FlowerImages/" + newFileName; using (FileStream fs = System.IO.File.Create(fileName)) { file.CopyTo(fs); fs.Flush(); } } } Flower objEqu = new Flower { FlowerFilename = newFileName, FlowerFilePath = PathDB, FlowerID = 0, FlowerName = Flower.FlowerName, FlowerCost = Flower.FlowerCost, Createdate = DateTime.Now, Createdby = Convert.ToInt32(HttpContext.Session.GetString("UserID")) }; _IFlower.SaveFlower(objEqu); TempData["FLowerMessage"] = "FLower Saved Successfully"; ModelState.Clear(); return(View(new Flower())); } return(View(Flower)); }
public async Task <IActionResult> Create(PostsViewModel model, string userId) { var files = HttpContext.Request.Form.Files; var usedFileName = default(string); foreach (var Image in files) { if (Image != null && Image.Length > 0) { var file = Image; var uploads = Path.Combine(_hostingEnvironment.WebRootPath, "uploads\\img\\posts"); if (file.Length > 0) { var fileName = ContentDispositionHeaderValue.Parse (file.ContentDisposition).FileName.Trim('"'); System.Console.WriteLine(fileName); using (var fileStream = new FileStream(Path.Combine(uploads, file.FileName), FileMode.Create)) { await file.CopyToAsync(fileStream); usedFileName = file.FileName; } } } } var post = new Post { Title = model.Title, Body = model.Body, CreationDate = DateTime.Now, CreatedBy = this.User.Identity.Name, Enabled = true, PostImage = usedFileName, UserId = userId, }; var listTagsId = new List <int>(); if (model.Tags != null) { foreach (var tagItem in model.Tags) { tagItem.CreatedBy = User.Identity.Name; if (tagItem.IsSelected) { listTagsId.Add(tagItem.TagId); } } } if (ModelState.IsValid) { _repositoryWrapper.Post.Create(post); var thisPost = post; _repositoryWrapper.Save(); foreach (var element in listTagsId) { var postTags = new PostTag { PostId = thisPost.PostId, TagId = element, }; _repositoryWrapper.PostTags.Create(postTags); _repositoryWrapper.Save(); } return(RedirectToAction(nameof(Index), new { userId = post.UserId })); } return(View(model)); }
public async Task <IActionResult> Upload2() { try { var file = Request.Form.Files[0]; //////به دست آوردن مقادیری که به فایل اضافه کردیم با استفاده از حلقه /////// foreach (string key in Request.Form.Keys) { if (key == "type") { ga = Request.Form[key]; } if (key == "number") { gb = Request.Form[key]; } if (key == "id") { gc = Request.Form[key]; } if (key == "date") { gd = Request.Form[key]; } } ////////////ایجاد یک مونه کپی از فایل ارسالی در پوشه//// var folderName = Path.Combine("Resources", "Images"); var pathToSave = Path.Combine(Directory.GetCurrentDirectory(), folderName); if (file.Length > 0) { var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"'); var fullPath = Path.Combine(pathToSave, fileName); var dbPath = Path.Combine(folderName, fileName); using (var stream = new FileStream(fullPath, FileMode.Create)) { file.CopyTo(stream); } ///////خواندن فایل کپی شده در فولدر مورد نظر و تبدیل آن به فت بایت و ذخیره در جدول دیتابیس//////// byte[] bytes; using (var stream = new FileStream(fullPath, FileMode.Open, FileAccess.Read)) { bytes = new byte[stream.Length]; stream.Read(bytes, 0, Convert.ToInt32(stream.Length)); long u = Convert.ToInt64(gc.ToString()); if (ga == "subscription-letter") { University university = _contextt.University.SingleOrDefault(s => s.UniNationalId == u); university.SubscriptionLetter = bytes; _contextt.Entry(university).State = EntityState.Modified; await _contextt.SaveChangesAsync(); } } ////////در آخر پاک کردن فایل مورد نظر از پوشه////////// if (System.IO.File.Exists(fullPath)) { System.IO.File.Delete(fullPath); } return(Ok(new { dbPath })); } else { return(BadRequest()); } } catch (Exception ex) { return(StatusCode(500, "Internal server error")); } }
public IActionResult UploadFiles(IList <IFormFile> files) { long size = 0, second = 0; //IList<IFormFile> 内的IFormFile对象 foreach (var file in files) { string filename = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim(); filename = hostingEnv.WebRootPath + $@"\{filename.Replace("\"", "")}"; size += file.Length; //将excal 写入本地 using (FileStream fs = System.IO.File.Create(filename)) { file.CopyTo(fs); fs.Flush(); } //创建数据容器的实例 DataTransfer.DataTable dt = new DataTransfer.DataTable(); using (FileStream stream = System.IO.File.Open(filename, FileMode.Open, FileAccess.Read)) { //创建 XSSFWorkbook和ISheet实例 XSSFWorkbook workbook = new XSSFWorkbook(stream); ISheet sheet = workbook.GetSheetAt(0); //获取sheet的首行 IRow headerRow = sheet.GetRow(0); int cellCount = headerRow.LastCellNum; List <DataTransfer.DataColumn> Columnlist = new List <DataTransfer.DataColumn>(); for (int i = headerRow.FirstCellNum; i < cellCount; i++) { //Column 添加ColumnName Columnlist.Add(new DataTransfer.DataColumn(headerRow.GetCell(i).StringCellValue, headerRow.GetCell(i).CellType.GetType())); } int rowCount = sheet.LastRowNum; object[] rowlist = new object[sheet.LastRowNum]; for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++) { object[] valuelist = new object[cellCount]; IRow row = sheet.GetRow(i); for (int j = row.FirstCellNum; j < cellCount; j++) { //遍历添加Column的数据 if (row.GetCell(j) != null) { valuelist.SetValue(row.GetCell(j).ToString(), j); } } //遍历将Column的数据添加到Datarow rowlist.SetValue(valuelist, i - 1); dt.Rows.Add(new DataTransfer.DataRow(Columnlist, valuelist)); } List <AddDataViewModel> list = new List <AddDataViewModel>(); foreach (DataTransfer.DataRow dr in dt.Rows) { //填充entity 这个可换成自己的表 AddDataViewModel moudel = new AddDataViewModel(); foreach (PropertyInfo prop in moudel.GetType().GetRuntimeProperties()) { if (dr[prop.Name] != null) { object obj = new object(); if (prop.Name == "SecondLevel") { obj = Convert.ToInt32(dr[prop.Name]); } else { obj = dr[prop.Name]; } prop.SetValue(moudel, obj); } } //excel 中没有的栏位可以在此添加 //moudel.ViewSupportId = 0; //moudel.ViewSupportName = ""; //moudel.FirstLevel = 111; //moudel.Keywords = 0; //moudel.IsCompany = false; //moudel.IsReady = false; //moudel.UnLock = true; //moudel.IsCrm = false; //moudel.IsOpera = false; //moudel.IP = ""; //moudel.ImportType = ""; //moudel.ProtectedTimes = DateTime.Now; //moudel.RegisterTime = DateTime.Now; //moudel.IsCheck = 0; //moudel.IsAborad = 0; list.Add(moudel); } //创建计时器 Stopwatch watch = Stopwatch.StartNew(); //ef连接数据库 using (_context) { //批量insert foreach (AddDataViewModel entity in list) { _context.AddDataViewModel.Add(entity); } _context.SaveChanges(); } //获取处理数据所用的时间 second = watch.ElapsedMilliseconds; } ViewBag.Message = $"{files.Count} file(s) / { size} bytes When used { second } uploaded successfully!"; } return(View()); }
public async Task <IActionResult> SubirArticulo(string titulo, IFormFile urlPdf, IFormFile urlImg, string coment, int[] coautor = null) { string correo = HttpContext.Session.GetString("Correo"); string pass = HttpContext.Session.GetString("pass"); int tipo = (int)HttpContext.Session.GetInt32("tipo"); int id = (int)HttpContext.Session.GetInt32("id"); try { var PdfName = ContentDispositionHeaderValue.Parse(urlPdf.ContentDisposition.ToString()).FileName.Trim('"'); var RootPath = _hostingEnv.WebRootPath; var pdfFullPath = Path.Combine(RootPath, "PdfUploaded"); if (!Directory.Exists(pdfFullPath)) { Directory.CreateDirectory(pdfFullPath); } var pdfFullName = pdfFullPath + Path.DirectorySeparatorChar + PdfName; using (var stream = new FileStream(pdfFullName, FileMode.Create)) await urlPdf.CopyToAsync(stream); var ZipName = ContentDispositionHeaderValue.Parse(urlImg.ContentDisposition.ToString()).FileName.Trim('"'); var imgFullPath = Path.Combine(RootPath, "ZipUploaded"); if (!Directory.Exists(imgFullPath)) { Directory.CreateDirectory(imgFullPath); } var imgFullName = imgFullPath + Path.DirectorySeparatorChar + ZipName; using (var stream2 = new FileStream(imgFullName, FileMode.Create)) await urlImg.CopyToAsync(stream2); var context = HttpContext.RequestServices.GetService(typeof(proyecto_r_mcynContext)) as proyecto_r_mcynContext; Articulo articulo = new Articulo(); articulo.TituloArticulo = titulo; articulo.RutaDocumentoA = pdfFullName; articulo.RutaZipImagenesA = imgFullName; articulo.ComentariosAutor = coment; DateTime dateNow = DateTime.Now.Date; string formatMysql = dateNow.ToString("dd-MM-yyyy"); articulo.FechaPublicacionA = formatMysql; articulo.RAutor = id; articulo.Status = 8; context.Articulo.Add(articulo); context.SaveChanges(); //hechizo de coautores if (coautor != null) { foreach (int v in coautor) { var c = context.Coautores.Find(new object[] { v }); int idar = context.Articulo.OrderByDescending(x => x.IdArticulo).First().IdArticulo; c.RArticulo = idar; context.Update(c); context.SaveChanges(); } } ViewData["id"] = id; ViewData["correo"] = correo; ViewData["tipo"] = tipo; return(View()); } catch { ViewData["id"] = id; ViewData["correo"] = correo; ViewData["tipo"] = tipo; return(View()); } }
public async Task <IActionResult> EditarArticulo(int id_ar, string titulo, IFormFile urlPdf, IFormFile urlImg, string coment) { try { var context = HttpContext.RequestServices.GetService(typeof(proyecto_r_mcynContext)) as proyecto_r_mcynContext; var artiviejo = context.Articulo.Find(new object[] { id_ar }); artiviejo.TituloArticulo = titulo; if (urlPdf != null) { var PdfName = ContentDispositionHeaderValue.Parse(urlPdf.ContentDisposition.ToString()).FileName.Trim('"'); var RootPath = _hostingEnv.WebRootPath; var pdfFullPath = Path.Combine(RootPath, "PdfUploaded"); if (!Directory.Exists(pdfFullPath)) { Directory.CreateDirectory(pdfFullPath); } var pdfFullName = pdfFullPath + Path.DirectorySeparatorChar + PdfName; using (var stream = new FileStream(pdfFullName, FileMode.Create)) await urlPdf.CopyToAsync(stream); artiviejo.RutaDocumentoA = pdfFullName; } if (urlImg != null) { var ZipName = ContentDispositionHeaderValue.Parse(urlImg.ContentDisposition.ToString()).FileName.Trim('"'); var RootPath = _hostingEnv.WebRootPath; var imgFullPath = Path.Combine(RootPath, "ZipUploaded"); if (!Directory.Exists(imgFullPath)) { Directory.CreateDirectory(imgFullPath); } var imgFullName = imgFullPath + Path.DirectorySeparatorChar + ZipName; using (var stream2 = new FileStream(imgFullName, FileMode.Create)) await urlImg.CopyToAsync(stream2); artiviejo.RutaZipImagenesA = imgFullName; } artiviejo.ComentariosAutor = coment; DateTime dateNow = DateTime.Now.Date; string formatMysql = dateNow.ToString("dd-MM-yyyy"); artiviejo.FechaEdicionA = formatMysql; artiviejo.Status = 8; context.Update(artiviejo); context.SaveChanges(); return(RedirectToAction(nameof(ListadoAutor))); } catch { return(RedirectToAction(nameof(EditarArticulo))); } }
public async Task <IActionResult> Upload(IList <IFormFile> files, int?id, Int16?kind, int?kindId) { foreach (var file in files) { var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"').ToLower();// FileName returns "fileName.ext"(with double quotes) in beta 3 if (fileName.EndsWith(".jpg") || fileName.EndsWith(".png") || fileName.EndsWith(".gif") || fileName.EndsWith(".bmp") || fileName.EndsWith(".tif") || fileName.EndsWith(".tiff") || fileName.EndsWith(".ico") || fileName.EndsWith(".pdf") )// Important for security if saving in webroot { Photo photo = null; if (id.HasValue) { photo = await FindPhotoAsync(id.Value); } else { photo = new Models.Photo(); photo.Kind = kind.Value; photo.KindId = kindId.Value; } photo.Name = Path.GetFileName(fileName); var filePath = Path.Combine(_environment.WebRootPath, "uploads", photo.Name); using (Stream str = file.OpenReadStream()) { //byte[] buf = new byte[file.Length]; //str.Read(buf, 0, buf.Length); //photo.Content = buf; using (MemoryStream data = new MemoryStream()) { str.CopyTo(data); data.Seek(0, SeekOrigin.Begin); // <-- missing line byte[] buf = new byte[data.Length]; data.Read(buf, 0, buf.Length); photo.Content = buf; } } //await file.SaveAsAsync(filePath); //photo.Content = System.IO.File.ReadAllBytes(filePath); db.Photos.Add(photo); await db.SaveChangesAsync(); // save the image path path to the database or you can send image // directly to database // in-case if you want to store byte[] ie. for DB //using (MemoryStream ms = new MemoryStream()) //{ // file2.InputStream.CopyTo(ms); // byte[] array = ms.GetBuffer(); //} } } return(RedirectToAction("Index", new { kind = kind, kindId = kindId }));// PRG //return View(); }
public async Task <IActionResult> UpdateFile(IList <IFormFile> UploadFiles, Document doc)//pass doc instead { var invalidChars = Path.GetInvalidFileNameChars(); string validFileName = new string(doc.DocumentName .Where(x => !invalidChars.Contains(x)) .ToArray()); try { doc.DocStatusId = await _unitOfWork.Documents.GetDocumentStatusIdAsync("Active"); foreach (var file in UploadFiles) { var oldFilename = ContentDispositionHeaderValue .Parse(file.ContentDisposition) .FileName.Trim('"'); doc.MimeType = oldFilename.Split('.').Last(); string oldFilePath = await GetFullPath(doc.FolderId, validFileName) + "." + doc.MimeType; var newFileName = oldFilePath.Replace(oldFilename, validFileName); if (System.IO.File.Exists(oldFilePath)) { System.IO.File.Delete(oldFilePath); // just fully remove and to upload again. an additional copy should already be saved on server } using (FileStream fs = System.IO.File.Create(newFileName)) { await file.CopyToAsync(fs); doc.Path = await GetRelativePath(doc.FolderId, validFileName + "." + doc.MimeType); //the upload date is only set when a new file is uploaded. This will give the last "document revised" date. doc.UploadDate = DateTime.Now; } } //03.23.2020 network path //string oldPath = _hostingEnv.WebRootPath + doc.Path; string oldPath = _networkDocPath + doc.Path; var relPath = await GetRelativePath(doc.FolderId, validFileName + "." + doc.MimeType); //03.23.2020 network path //string newPath = _hostingEnv.WebRootPath + relPath; string newPath = _networkDocPath + relPath; if (System.IO.File.Exists(oldPath)) { System.IO.File.Move(oldPath, newPath);//rename file } doc.Path = relPath; await UpdateDocument(doc); if (doc.SendNotification) { await _unitOfWork.Documents.SendNotification(doc.DocId, _userSession.Id); } return(Redirect(Request.Headers["Referer"].ToString())); } catch (Exception ex) { Response.Clear(); Response.StatusCode = 404; Response.Headers.Add("status", ex.Message); } return(Redirect(Request.Headers["Referer"].ToString())); }
public async Task <IActionResult> UploadFile() { try { var files = Request.Form.Files; var leadId = Request.Form["leadId"]; var folderName = Path.Combine("LeadFiles", leadId); //string subPath = "ImagesPath"; // your code goes here var pathToSave = Path.Combine(Directory.GetCurrentDirectory(), folderName); bool exists = System.IO.Directory.Exists(pathToSave); if (!exists) { System.IO.Directory.CreateDirectory(pathToSave); } if (!files.Any(f => f.Length == 0)) { foreach (var file in files) { var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"'); var fullPath = Path.Combine(pathToSave, fileName); var dbPath = Path.Combine(folderName, fileName); //you can add this path to a list and then return all dbPaths to the client if require using (var stream = new FileStream(fullPath, FileMode.Create)) { file.CopyTo(stream); } FilesModel obj = new FilesModel(); obj.leadFiles = file; obj.fileName = fileName; obj.filePath = dbPath; Guid Lid = new Guid(leadId); obj.leadId = Lid; ClaimsIdentity claimsIdentity = User.Identity as ClaimsIdentity; var currentLoginUserid = new UserClaims(claimsIdentity).LoggedInUserId; var config = new MapperConfiguration(cfg => { cfg.CreateMap <FilesModel, FileDTO>(); }); obj.createdBy = currentLoginUserid; IMapper mapperResponse = config.CreateMapper(); var fileDTO = mapperResponse.Map <FilesModel, FileDTO>(obj); using (var uow = new UnitOfWork(_configs.Value.DbConnectionString)) { string result = await uow.Files.uploadFIleAsync(fileDTO); uow.Commit(); return(Ok(new ApiResponse { message = ApiMessageConstants.commonAdded, data = result })); } } return(Ok(new ApiResponse { message = "", data = "" })); } else { return(BadRequest(new ApiResponse { message = ApiMessageConstants.someThingWentWrong })); } } catch (Exception ex) { return(BadRequest(new ApiResponse { message = ex.Message })); } }
public async Task Instance_Post_WithNæringOgSkattemelding_ValidateOk() { string token = PrincipalUtil.GetToken(1337); HttpClient client = SetupUtil.GetTestClient(_factory, "tdd", "sirius"); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); HttpRequestMessage httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, "/tdd/sirius/instances?instanceOwnerPartyId=1337") { }; HttpResponseMessage response = await client.SendAsync(httpRequestMessage); string responseContent = await response.Content.ReadAsStringAsync(); Instance instance = JsonConvert.DeserializeObject <Instance>(responseContent); Assert.Equal(HttpStatusCode.Created, response.StatusCode); Assert.NotNull(instance); Assert.Equal("1337", instance.InstanceOwner.PartyId); // Get Data from Instance HttpRequestMessage httpRequestMessageGetData = new HttpRequestMessage(HttpMethod.Get, "/tdd/sirius/instances/" + instance.Id + "/data/" + instance.Data[0].Id); { }; HttpResponseMessage responseData = await client.SendAsync(httpRequestMessageGetData); string responseContentData = await responseData.Content.ReadAsStringAsync(); Skjema siriusMainForm = (Skjema)JsonConvert.DeserializeObject(responseContentData, typeof(Skjema)); // Modify the prefilled form. This would need to be replaced with the real sirius form siriusMainForm.Permisjonsopplysningergrp8822 = new Permisjonsopplysningergrp8822(); siriusMainForm.Permisjonsopplysningergrp8822.AnsattEierandel20EllerMerdatadef33294 = new AnsattEierandel20EllerMerdatadef33294() { value = "50" }; XmlSerializer serializer = new XmlSerializer(typeof(Skjema)); using MemoryStream stream = new MemoryStream(); serializer.Serialize(stream, siriusMainForm); stream.Position = 0; StreamContent streamContent = new StreamContent(stream); streamContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml"); HttpResponseMessage putresponse = await client.PutAsync("/tdd/sirius/instances/" + instance.Id + "/data/" + instance.Data[0].Id, streamContent); // Add Næringsoppgave.xml string næringsppgave = File.ReadAllText("Data/Files/data-element.xml"); byte[] byteArray = Encoding.UTF8.GetBytes(næringsppgave); //byte[] byteArray = Encoding.ASCII.GetBytes(contents); MemoryStream næringsoppgavestream = new MemoryStream(byteArray); StreamContent streamContentNæring = new StreamContent(næringsoppgavestream); streamContentNæring.Headers.ContentType = MediaTypeHeaderValue.Parse("text/xml"); streamContentNæring.Headers.ContentDisposition = ContentDispositionHeaderValue.Parse("attachment; filename=data-element.xml"); HttpResponseMessage postresponseNæring = await client.PostAsync("/tdd/sirius/instances/" + instance.Id + "/data/?datatype=næringsoppgave", streamContentNæring); DataElement dataElementNæring = (DataElement)JsonConvert.DeserializeObject(await postresponseNæring.Content.ReadAsStringAsync(), typeof(DataElement)); // Add skattemelding.xml string skattemelding = File.ReadAllText("Data/Files/data-element.xml"); byte[] byteArraySkattemelding = Encoding.UTF8.GetBytes(næringsppgave); //byte[] byteArray = Encoding.ASCII.GetBytes(contents); MemoryStream skattemeldingstream = new MemoryStream(byteArraySkattemelding); StreamContent streamContentSkattemelding = new StreamContent(skattemeldingstream); streamContent.Headers.ContentType = MediaTypeHeaderValue.Parse("text/xml"); HttpResponseMessage postresponseskattemelding = await client.PostAsync("/tdd/sirius/instances/" + instance.Id + "/data/?datatype=skattemelding", streamContentNæring); DataElement dataElementSkattemelding = (DataElement)JsonConvert.DeserializeObject(await postresponseskattemelding.Content.ReadAsStringAsync(), typeof(DataElement)); // Validate instance string url = "/tdd/sirius/instances/" + instance.Id + "/validate"; HttpResponseMessage responseValidation = await client.GetAsync(url); string responseContentValidation = await responseValidation.Content.ReadAsStringAsync(); List <ValidationIssue> messages = (List <ValidationIssue>)JsonConvert.DeserializeObject(responseContentValidation, typeof(List <ValidationIssue>)); Assert.Empty(messages); TestDataUtil.DeleteInstanceAndData("tdd", "sirius", 1337, new Guid(instance.Id.Split('/')[1])); }
//returns physical file which is uploaded public async Task <Medium> AddMediaFile(IFormFile postedFile, CancellationToken cancellationToken = default) { try { var name = postedFile.FileName; var uploadFolder = _options.MediaStoragePath ?? (Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "app_data", @"UploadedFiles")); var fileLen = postedFile.Length; var contentType = postedFile.ContentType; string finalPath; if (fileLen > 0) { var fileName = ContentDispositionHeaderValue.Parse(postedFile.ContentDisposition) .FileName.Trim('"'); using var createHash = MD5.Create(); var bytes = RandomNumberGenerator.GetBytes(32); string hash = null; if (fileLen < _formOptions.MemoryBufferThreshold) //fast hash otherwise, we'll break memory { using var memStream = new MemoryStream(); await postedFile.CopyToAsync(memStream, cancellationToken); if (cancellationToken.IsCancellationRequested) { return(null); } memStream.Position = 0; hash = Convert.ToHexString(bytes).ToLowerInvariant(); if (cancellationToken.IsCancellationRequested) { return(null); } memStream.Position = 0; finalPath = Path.Combine(uploadFolder, string.Concat(hash, MimeMap(contentType))); using var fileStream = File.Create(finalPath, (int)postedFile.Length, FileOptions.WriteThrough); await memStream.CopyToAsync(fileStream, cancellationToken); if (cancellationToken.IsCancellationRequested) { return(null); } } //slower but on disk else { var tempPath = Path.Combine(uploadFolder, $"{new Random().Next(int.MaxValue)}.tmp"); using (var fileStream = File.Create(tempPath, 4096 * 8, FileOptions.SequentialScan)) { await postedFile.CopyToAsync(fileStream, cancellationToken); if (cancellationToken.IsCancellationRequested) { return(null); } fileStream.Position = 0; hash = Convert.ToHexString(await createHash.ComputeHashAsync(fileStream, cancellationToken)).ToLowerInvariant(); if (cancellationToken.IsCancellationRequested) { return(null); } } finalPath = Path.Combine(uploadFolder, string.Concat(hash, MimeMap(contentType))); File.Move(tempPath, finalPath, true); } string thumbNail = null; (int width, int height, double duration)meta = default; if (!string.IsNullOrEmpty(finalPath)) { if (contentType.StartsWith("image")) { thumbNail = await MimeTypeHelper.CreateImageThumbnail(finalPath, 500, cancellationToken); var(width, height, mimeType) = await MimeTypeHelper.DetectImageType(finalPath, cancellationToken); meta = (width, height, 0F); } else if (contentType.StartsWith("video")) { thumbNail = await MimeTypeHelper.CreateThumbNail(finalPath, cancellationToken); meta = await MimeTypeHelper.GetResolution(finalPath, cancellationToken); } if (thumbNail == null) { _logger.LogError($"cannot create CreateThumbNail for {finalPath} is ffmpeg correctly installed"); } } var media = new Medium { Id = new Random().Next(), Size = fileLen, Name = name, Ext = MimeMap(contentType), Height = meta.height, Width = meta.width, HashKeyThumbNail = thumbNail != null?Path.GetFileName(thumbNail) : null, MediaType = contentType, HashKey = hash, Created = DateTimeOffset.UtcNow }; return(media); } } catch (Exception ex) { _logger.LogError("AddMediaFile failed {0}", ex); } return(null); }
public IActionResult UploadFiles() { try { IFormFileCollection fileCollection = Request.Form.Files; Regex regEx = new Regex("[*?|\\\t/:\"\"'<>#{}%~&]"); string clientUrl = Request.Form["clientUrl"]; string folderUrl = Request.Form["folderUrl"]; string folderName = folderUrl.Substring(folderUrl.LastIndexOf(ServiceConstants.FORWARD_SLASH, StringComparison.OrdinalIgnoreCase) + 1); string documentLibraryName = Request.Form["documentLibraryName"]; MatterExtraProperties documentExtraProperites = null; if (!string.IsNullOrWhiteSpace(Request.Form["DocumentExtraProperties"])) { documentExtraProperites = JsonConvert.DeserializeObject <MatterExtraProperties>(Request.Form["DocumentExtraProperties"].ToString()); } bool isDeployedOnAzure = Convert.ToBoolean(generalSettings.IsTenantDeployment, CultureInfo.InvariantCulture); string originalName = string.Empty; bool allowContentCheck = Convert.ToBoolean(Request.Form["AllowContentCheck"], CultureInfo.InvariantCulture); Int16 isOverwrite = 3; //Input validation #region Error Checking GenericResponseVM genericResponse = null; IList <object> listResponse = new List <object>(); bool continueUpload = true; if (isDeployedOnAzure == false && string.IsNullOrWhiteSpace(clientUrl) && string.IsNullOrWhiteSpace(folderUrl)) { genericResponse = new GenericResponseVM() { Value = errorSettings.MessageNoInputs, Code = HttpStatusCode.BadRequest.ToString(), IsError = true }; return(matterCenterServiceFunctions.ServiceResponse(genericResponse, (int)HttpStatusCode.OK)); } #endregion //Get all the files which are uploaded by the user for (int fileCounter = 0; fileCounter < fileCollection.Count; fileCounter++) { IFormFile uploadedFile = fileCollection[fileCounter]; if (!Int16.TryParse(Request.Form["Overwrite" + fileCounter], out isOverwrite)) { isOverwrite = 3; } continueUpload = true; ContentDispositionHeaderValue fileMetadata = ContentDispositionHeaderValue.Parse(uploadedFile.ContentDisposition); string fileName = originalName = fileMetadata.FileName.Trim('"'); fileName = System.IO.Path.GetFileName(fileName); ContentCheckDetails contentCheckDetails = new ContentCheckDetails(fileName, uploadedFile.Length); string fileExtension = System.IO.Path.GetExtension(fileName).Trim(); if (-1 < fileName.IndexOf('\\')) { fileName = fileName.Substring(fileName.LastIndexOf('\\') + 1); } else if (-1 < fileName.IndexOf('/')) { fileName = fileName.Substring(fileName.LastIndexOf('/') + 1); } if (null != uploadedFile.OpenReadStream() && 0 == uploadedFile.OpenReadStream().Length) { listResponse.Add(new GenericResponseVM() { Code = fileName, Value = errorSettings.ErrorEmptyFile, IsError = true }); } else if (regEx.IsMatch(fileName)) { listResponse.Add(new GenericResponseVM() { Code = fileName, Value = errorSettings.ErrorInvalidCharacter, IsError = true }); } else { string folder = folderUrl.Substring(folderUrl.LastIndexOf(ServiceConstants.FORWARD_SLASH, StringComparison.OrdinalIgnoreCase) + 1); //If User presses "Perform content check" option in overwrite Popup if (2 == isOverwrite) { genericResponse = documentProvision.PerformContentCheck(clientUrl, folderUrl, uploadedFile, fileName); } //If user presses "Cancel upload" option in overwrite popup or file is being uploaded for the first time else if (3 == isOverwrite) { genericResponse = documentProvision.CheckDuplicateDocument(clientUrl, folderUrl, documentLibraryName, fileName, contentCheckDetails, allowContentCheck); } //If User presses "Append date to file name and save" option in overwrite Popup else if (1 == isOverwrite) { string fileNameWithoutExt = System.IO.Path.GetFileNameWithoutExtension(fileName); string timeStampSuffix = DateTime.Now.ToString(documentSettings.TimeStampFormat, CultureInfo.InvariantCulture).Replace(":", "_"); fileName = fileNameWithoutExt + "_" + timeStampSuffix + fileExtension; } if (genericResponse == null) { genericResponse = documentProvision.UploadFiles(uploadedFile, fileExtension, originalName, folderUrl, fileName, clientUrl, folder, documentLibraryName, documentExtraProperites); } if (genericResponse == null) { string documentIconUrl = string.Empty; fileExtension = fileExtension.Replace(".", ""); if (fileExtension.ToLower() != "pdf") { documentIconUrl = $"{generalSettings.SiteURL}/_layouts/15/images/ic{fileExtension}.gif"; } else { documentIconUrl = $"{generalSettings.SiteURL}/_layouts/15/images/ic{fileExtension}.png"; } //Create a json object with file upload success var successFile = new { IsError = false, Code = HttpStatusCode.OK.ToString(), Value = UploadEnums.UploadSuccess.ToString(), FileName = fileName, DropFolder = folderName, DocumentIconUrl = documentIconUrl }; listResponse.Add(successFile); } else { //Create a json object with file upload failure var errorFile = new { IsError = true, Code = genericResponse.Code.ToString(), Value = genericResponse.Value.ToString(), FileName = fileName, DropFolder = folderName }; listResponse.Add(errorFile); } } } //Return the response with proper http status code and proper response object return(matterCenterServiceFunctions.ServiceResponse(listResponse, (int)HttpStatusCode.OK)); } catch (Exception ex) { customLogger.LogError(ex, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, logTables.SPOLogTable); throw; } }
public ActionResult UploadFile() { try { //recieve file and read details attached var file = Request.Form.Files[0]; var assetId = HttpContext.Request.Form["assetId"]; var imageTypeFolder = HttpContext.Request.Form["imageType"]; string rootFolderName = "Uploads"; string imageFolder = assetId; string apiPath = null; string webRootPath = _hostingEnvironment.WebRootPath; if (file.Length > 0) { //get exstension and validate string uploadFileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"'); string ext = Path.GetExtension(uploadFileName); if (ext == ".jpg" || ext == ".jpeg" || ext == ".png") { int assetIdInt = Int32.Parse(assetId); //creat timestamp for porperty images and room images string time = DateTime.Now.ToString("hh.mm.ss.ffffff"); var fileName = imageTypeFolder.Equals("client") ? assetId + ext : assetId + time + ext; apiPath = Path.Combine(imageTypeFolder, imageFolder, fileName); //change path from explorer reference to url reference apiPath = apiPath.Replace('\\', '/'); // var uri = new Uri(apiPath); //3 different methods for each image type if (imageTypeFolder.Equals("client")) { _repository.AddUserImage(assetIdInt, apiPath); } if (imageTypeFolder.Equals("room")) { _repository.AddRoomImage(assetIdInt, apiPath); } if (imageTypeFolder.Equals("property")) { _repository.AddPropertyImage(assetIdInt, apiPath); } //generate path based on data attached to image var fullPath = Path.Combine(webRootPath, rootFolderName, apiPath); string fileFolder = Path.Combine(webRootPath, rootFolderName, imageTypeFolder, imageFolder); if (!Directory.Exists(fileFolder)) { Directory.CreateDirectory(fileFolder); } using (var stream = new FileStream(fullPath, FileMode.Create)) { file.CopyTo(stream); } } return(Json(apiPath)); } return(Json("Upload Failed, Please Ensure Image is either JPG, PNG or JPEG Format")); } catch (System.Exception ex) { return(Json("Upload Failed: " + ex.Message)); } }
public IEnumerable <object> Get() { try { DB db = new DB(); var file = Request.Form.Files[0]; var folderName = Path.Combine("Resources"); var pathToSave = Path.Combine(Directory.GetCurrentDirectory(), folderName); if (file.Length > 0) { var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"'); var fullPath = Path.Combine(pathToSave, fileName); var dbPath = Path.Combine(folderName, fileName); DataTable dt = new DataTable(); dt.Columns.Add("SchemeId", typeof(string)); dt.Columns.Add("FirstName", typeof(string)); dt.Columns.Add("LastName", typeof(string)); dt.Columns.Add("Email", typeof(string)); dt.Columns.Add("Mobile", typeof(Int64)); dt.Columns.Add("Error", typeof(string)); int i = 0; using (var reader = new StreamReader(file.OpenReadStream())) { while (!reader.EndOfStream) { DataRow dr = dt.NewRow(); string row = reader.ReadLine(); var arr = row.Split("|"); dr["SchemeId"] = arr[0]; dr["FirstName"] = arr[1]; dr["LastName"] = arr[2]; bool isEmail = Regex.IsMatch(arr[3], @"\A(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\Z", RegexOptions.IgnoreCase); dr["Email"] = arr[3]; dr["Mobile"] = Convert.ToInt64(arr[4]); if (!isEmail) { dr["Error"] = "Invalid email"; } else { dr["Error"] = "Success"; } dt.Rows.Add(dr); } db.BulkCopy(dt.AsEnumerable().Where(row => row.Field <String>("Error") == "Success").CopyToDataTable()); } return(dt.AsEnumerable().ToList().Take(1)); } else { //return BadRequest(); return(null); } } catch (Exception ex) { return(null); //return StatusCode(500, $"Internal server error: {ex}"); } }
public async Task <IActionResult> Create(ComponenttypeVM componentType) { //todo rename kjal var kjal = new ESImage(); if (componentType.Image != null && componentType.Image.Length > 0) { var fileName = ContentDispositionHeaderValue.Parse(componentType.Image.ContentDisposition).FileName.Trim('"'); using (var reader = new StreamReader(componentType.Image.OpenReadStream())) { string contentAsString = reader.ReadToEnd(); byte[] bytes = new byte[contentAsString.Length * sizeof(char)]; System.Buffer.BlockCopy(contentAsString.ToCharArray(), 0, bytes, 0, bytes.Length); kjal.ImageData = bytes; } } kjal.ImageMimeType = "image/png"; var tmp = new ComponentType(); tmp.ComponentName = componentType.ComponentName; tmp.AdminComment = componentType.AdminComment; tmp.Datasheet = componentType.Datasheet; tmp.ComponentInfo = componentType.ComponentInfo; tmp.ImageUrl = componentType.ImageUrl; tmp.Location = componentType.Location; tmp.Status = componentType.Status; tmp.Manufacturer = componentType.Manufacturer; tmp.WikiLink = componentType.WikiLink; tmp.Image = kjal; _context.Add(tmp); await _context.SaveChangesAsync(); //long Id = tmp.ComponentTypeId; ICollection <Category> categories = new List <Category>(); List <Category> cool = new List <Category>(); if (componentType.Categories != null) { var catlist = componentType.Categories.Split(","); foreach (var item in catlist) { cool = _context.Categories.Select(a => a).Where(a => a.Name == item).ToList(); if (!cool.Any()) { var aCat = new Category { Name = item, }; categories.Add(aCat); _context.Add(aCat); } else { //TODO lol :) hacks categories.Add(cool.First()); } } } await _context.SaveChangesAsync(); foreach (var item in categories) { var free = new CategoryComponenttypebinding() { CategoryId = item.CategoryId, ComponentTypeId = tmp.ComponentTypeId, Category = item, ComponentType = tmp }; _context.Add(free); tmp.CategoryComponenttypebindings.Add(free); item.CategoryComponenttypebindings.Add(free); //TODO check if it works without _context.Entry(item).State = EntityState.Modified; _context.Update(item); } _context.Entry(tmp).Collection("CategoryComponenttypebindings").IsModified = true; await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); }
public IActionResult UpdateUser(UserJobCard updateUser) { var sessionId = Request.Form["ddlInterest"].ToString(); var userSession = _context.UserSessions.FirstOrDefault <UserSession>(us => us.SessionID == int.Parse(sessionId) && us.UserID == updateUser.User.ID); if (userSession == null) { _context.UserSessions.Add(new UserSession() { SessionID = int.Parse(sessionId), UserID = updateUser.User.ID }); } var user = _context.Users.FirstOrDefault <User>(u => u.ID == updateUser.User.ID); var userPassword = user.Password; user = updateUser.User; user.Password = userPassword; _context.SaveChanges(); updateUser.JobCard.CreateOn = DateTime.Now; updateUser.JobCard.ModifiedOn = DateTime.Now; updateUser.JobCard.OwnerID = updateUser.User.ID; updateUser.User = updateUser.User; updateUser.JobCard.ApprovedOn = DateTime.Now; updateUser.JobCard.VouchersPaidOn = DateTime.Now; string statusMessageStr = string.Empty; if (Request.Form["rdoMessage"].ToString() == "2") { statusMessageStr = Request.Form["txtMessageTemplate"].ToString(); } else if (Request.Form["rdoMessage"].ToString() == "0") { statusMessageStr = Request.Form["sp0_message"].ToString(); } else if (Request.Form["rdoMessage"].ToString() == "1") { statusMessageStr = Request.Form["sp1_message"].ToString(); } updateUser.JobCard.StatusMessage = statusMessageStr; _context.JobCards.Add(updateUser.JobCard); _context.SaveChanges(); if (Request.Form.Files.Count > 0) { var dirPath = @"\images\jobcard\" + updateUser.JobCard.ID; DirectoryInfo di = Directory.CreateDirectory(hostingEnv.WebRootPath + $@"{dirPath}"); long size = 0; foreach (var file in Request.Form.Files) { var filename = ContentDispositionHeaderValue .Parse(file.ContentDisposition) .FileName .Trim('"'); filename = hostingEnv.WebRootPath + $@"{dirPath}\{filename}"; size += file.Length; using (FileStream fs = System.IO.File.Create(filename)) { file.CopyTo(fs); fs.Flush(); } } _context.SaveChanges(); ViewBag.ErrorMessage = ""; } return(RedirectToAction("UserProfile", "Account", new { id = updateUser.User.ID })); }
public async Task <IActionResult> Create(CreateContactViewModel vm, IFormFile file) { if (ModelState.IsValid) { Contact contact = new Contact(); contact.BirthDate = vm.BirthDate; contact.Comments = vm.Comments; contact.EmailAddress = vm.EmailAddress; contact.FirstName = vm.FirstName; contact.LastName = vm.LastName; contact.PhoneNumber = vm.PhoneNumber; // File upload logic var uploads = Path.Combine(_environment.WebRootPath, "images/UploadedProfileImages"); if (file != null && file.Length > 0) { contact.ProfileImagePath = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"'); await file.SaveAsAsync(Path.Combine(uploads, contact.ProfileImagePath)); } // if (vm.SelectedGroups != null) { foreach (string group in vm.SelectedGroups) { switch (group) { case "Associate": contact.isAssociate = true; break; case "Colleague": contact.isColleague = true; break; case "Family": contact.isFamily = true; break; case "Friend": contact.isFriend = true; break; default: contact.isAssociate = false; contact.isColleague = false; contact.isFamily = false; contact.isFriend = false; break; } } } else { contact.isAssociate = false; contact.isColleague = false; contact.isFamily = false; contact.isFriend = false; } _context.Contacts.Add(contact); _context.SaveChanges(); return(RedirectToAction("Index")); } return(View(vm)); }
public async Task <IEnumerable <FileEntity> > Upload(IFormFileCollection files, ApplicationUser uploader = null) { var uploadDirectory = WebRootDirectoryInfo.ToString(); var currentYear = DateTime.UtcNow.Year.ToString(); var currentMonth = DateTime.UtcNow.Month.ToString(); var uploadedFiles = new List <FileEntity>(); foreach (var file in files) { var fileLength = file.Length; var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.ToString().Trim('"').ToLower(); var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileName); fileNameWithoutExtension = fileNameWithoutExtension + "-" + Guid.NewGuid().ToString().Substring(0, 5); var fileExtension = Path.GetExtension(fileName); var rawPath = Path.Combine("Upload", uploader?.Id ?? "unknow", currentYear, currentMonth); var destinationFolderPath = Path.Combine(uploadDirectory, rawPath); if (!Directory.Exists(destinationFolderPath)) { Directory.CreateDirectory(destinationFolderPath); } var fileSavePath = Path.Combine(destinationFolderPath, fileName); using (var fileStream = File.Create(fileSavePath)) { await file.CopyToAsync(fileStream); fileStream.Flush(); } var fileMeta = new FileMeta(); var fileType = FileUtilities.GetFileType(fileName); if (fileType == FileType.Image) { var fileDimension = FileUtilities.GetImageDimension(fileSavePath); fileMeta.Height = fileDimension.Height; fileMeta.Width = fileDimension.Width; fileMeta.ImageAlt = fileNameWithoutExtension; var thumbFileName = $"{fileNameWithoutExtension}_thumb{fileExtension}"; var thumbFilePath = Path.Combine(destinationFolderPath, thumbFileName); var thubSize = int.Parse(Properties.Resources.THUMBNAIL_SIZE); var thumbnailCropResult = FileUtilities.CropAndSave(fileSavePath, thumbFilePath, new SixLabors.ImageSharp.Processing.ResizeOptions { Mode = SixLabors.ImageSharp.Processing.ResizeMode.Crop, Size = new Size(thubSize) }, (i) => i.Width > thubSize); if (thumbnailCropResult) { fileMeta.ThumbnailFileName = thumbFileName; } fileMeta.Base64PlaceHolder = FileUtilities.CropToBase64(fileSavePath, thumbFilePath, new SixLabors.ImageSharp.Processing.ResizeOptions { Mode = SixLabors.ImageSharp.Processing.ResizeMode.Max, Size = new Size() { Width = 40 } });; } var fileURI = "/" + Path.Combine(rawPath, fileName).Replace("\\", "/"); var fileEntity = new FileEntity { Src = fileURI, Size = fileLength, MetaJson = fileMeta.ToJsonString(), FileType = (int)fileType, CreateByUserId = uploader.Id }; _context.FileEntity.Add(fileEntity); await _context.SaveChangesAsync(); uploadedFiles.Add(fileEntity); } return(uploadedFiles); }
public async Task <IActionResult> UserContributionEdit(Guid id, UserContributionEditViewModel participant, IFormCollection formCollection) { if (id != participant.Id) { return(NotFound()); } if (ModelState.IsValid) { try { var participantToUpdate = await _context.Participants.FindAsync(id); participantToUpdate.LastUpdateTime = DateTime.Now; participantToUpdate.CompetitionSubjectId = participant.CompetitionSubjectId; participantToUpdate.Description = participant.Description; participantToUpdate.Subject = participant.Subject; participantToUpdate.StatusId = participant.StatusId; participantToUpdate.LastStatusTime = DateTime.Now; if (formCollection.Files != null) { foreach (var file in formCollection.Files) { var fileContent = ContentDispositionHeaderValue.Parse(file.ContentDisposition); var userId = HttpContext.User.Identity.Name; // Some browsers send file names with full path. // We are only interested in the file name. var format = Path.GetExtension(fileContent.FileName.ToString().Trim('"')); var filename = Guid.NewGuid().ToString() + format; var physicalPath = Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot\uploads\" + userId, filename); var path = Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot\uploads\" + userId); bool exists = Directory.Exists(path); if (!exists) { Directory.CreateDirectory(path); } // The files are not actually saved in this demo using (var fileStream = new FileStream(physicalPath, FileMode.Create)) { await file.CopyToAsync(fileStream); } participantToUpdate.AttachedFile = filename; } } _context.Update(participantToUpdate); await _context.SaveChangesAsync(); var userPhoneNumber = (from u in _context.Users where u.Id == participantToUpdate.UserId select u.PhoneNumber).FirstOrDefault(); var statusTitle = (from s in _context.Statues where s.StatusId == participant.StatusId select s.Title).FirstOrDefault(); Classes.SendSmsAsync(userPhoneNumber, "مشارکت", statusTitle, "changestatus"); } catch (DbUpdateConcurrencyException) { if (!ParticipantExists(participant.Id)) { return(NotFound()); } else { throw; } } var url = "/ParticipantUsers/UserContributions/" + participant.UserId; return(Redirect(url)); } return(View(participant)); }
public async Task <IActionResult> r2addObjUnitCode() { try { var model = JsonConvert.DeserializeObject <VB_QT_VanBanMoiSoHoa>(Request.Form["model"]); VB_QT_VanBanMoiSoHoa objvb = new VB_QT_VanBanMoiSoHoa(); var userId = Convert.ToInt32(User.Claims.First(c => c.Type == "UserId").Value); var user = await _context.Sys_Dm_User.FindAsync(userId); var userNguoiKy = await _context.Sys_Dm_User.FirstOrDefaultAsync(x => x.Id == model.NguoiKyId); if (model != null) { objvb.Id = Helper.GenKey(); objvb.CompanyId = user.CompanyId ?? 0; objvb.DepartmentId = user.DepartmentId ?? 0; objvb.TenNguoiKy = userNguoiKy.FullName; objvb.LinhVucId = model.LinhVucId; objvb.LoaiVanBanId = model.LoaiVanBanId; objvb.SoKyHieu = model.SoKyHieu; objvb.NoiBanHanh = model.NoiBanHanh; objvb.NgayBanHanh = model.NgayBanHanh; objvb.TuKhoa = model.TuKhoa; objvb.SoTrang = model.SoTrang; objvb.SoTrang = model.SoTrang; objvb.TenNguoiTao = user.FullName; objvb.CreateDate = DateTime.Now; objvb.UserCreateId = userId; objvb.TrichYeu = model.TrichYeu; _context.VB_QT_VanBanMoiSoHoa.Add(objvb); } VB_QT_LuanChuyenVanBan lcvb = LuanChuyenVanBan.r2AddLuanChuyenVanBan(objvb.Id, userId, user.FullName, userId, user.FullName, "", "", false, null, null, 1, "VB_MOISOHOA", DateTime.Now, false, null, "VB0101", "VB0101", user.PositionName, user.PositionName, user.DepartmentName, user.DepartmentName); _context.VB_QT_LuanChuyenVanBan.Add(lcvb); if (Request.Form.Files.Count != 0) { foreach (var item in Request.Form.Files) { VB_QT_FileVBMoiSoHoa obj = new VB_QT_FileVBMoiSoHoa(); var file = item; var folderName = Path.Combine("Resources", "VanBan"); var pathToSave = Path.Combine(Directory.GetCurrentDirectory(), folderName); if (!Directory.Exists(pathToSave)) { Directory.CreateDirectory(pathToSave); } if (model != null) { if (file.Length > 0) { var fileName = long.Parse(DateTime.Now.ToString("yyyyMMddHHmmss")).ToString() + ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"'); var fullPath = Path.Combine(pathToSave, fileName); var dbPath = Path.Combine(folderName, fileName); obj.Path = dbPath; using (var stream = new FileStream(fullPath, FileMode.Create)) { file.CopyTo(stream); } } } obj.Name = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"'); obj.VbMoiSoHoaId = objvb.Id; obj.Size = file.Length; obj.Type = 1; _context.VB_QT_FileVBMoiSoHoa.Add(obj); } } await _context.SaveChangesAsync(); return(new ObjectResult(new { error = 0, ms = "" }));; } catch (Exception ex) { var result = new OkObjectResult(new { error = 1, ms = "Lỗi khi thêm mới UnitCode, vui lòng kiểm tra lại!" }); return(result); } }
public FileResult Upload() { var file = Request.Form.Files[0]; string type_cipher = Request.Form["tipo"]; int BufferLength = 100; //lectura archivo var folderName = Path.Combine("Resources", "Files"); var pathToSave = Path.Combine(Directory.GetCurrentDirectory(), folderName); if (!Directory.Exists(pathToSave)) { Directory.CreateDirectory(pathToSave); } string extension = Path.GetExtension(file.FileName); var buffer = new byte[100]; if (extension == ".txt") { if (file.Length > 0) { var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"'); var fullPath = Path.Combine(pathToSave, fileName); string file_nameN = "cifrado.txt"; string pathToSave1 = Path.Combine(pathToSave, "Archivos"); //Carpeta donde estarán los archivos que devuelve cesar string pathToSaveK = Path.Combine(pathToSave, "Keys"); //Carpeta donde estarán los archivos de las llaves //Archivos que devuelve cesar string fullPathC = Path.Combine(pathToSave1, file_nameN); string PathKey = Path.Combine(pathToSave1, "key.txt"); if (Directory.Exists(pathToSave1)) { FileInfo f = new FileInfo(fullPathC); if (f.Exists) { f.Delete(); } f = new FileInfo(PathKey); if (f.Exists) { f.Delete(); } } else { Directory.CreateDirectory(pathToSave1); } //Archivos con las llaves string PathPubl = Path.Combine(pathToSaveK, "public.txt"); string PathPriv = Path.Combine(pathToSaveK, "private.txt"); if (Directory.Exists(pathToSaveK)) { FileInfo f = new FileInfo(PathPubl); f.Delete(); f = new FileInfo(PathPriv); f.Delete(); } else { Directory.CreateDirectory(pathToSaveK); } string clave = Request.Form["clave"]; int cl = int.Parse(clave); Cesar2 cif = new Cesar2(); cif.LlenarDiccionarios(); if (type_cipher == "rsa") { //clave mayor a 26 if (cl > 25) { int n = -(26 - cl); cl = n; } cif.LlenarClaveInt(cl); using (var stream = new FileStream(fullPathC, FileMode.Create)) { //ya se creó el archivo } using (var stream = new FileStream(fullPath, FileMode.Create)) { file.CopyTo(stream); } using (var stream = new FileStream(fullPath, FileMode.Open)) { using (BinaryReader br = new BinaryReader(stream)) { while (br.BaseStream.Position != br.BaseStream.Length) { buffer = br.ReadBytes(BufferLength); //llenar el buffer cif.Cifrar(buffer); cif.EscribirCifrado(fullPathC); } } } string auxp = Request.Form["p"]; string auxq = Request.Form["q"]; int p = int.Parse(auxp); int q = int.Parse(auxq); CifradoRSA cifa = new CifradoRSA(); if (cifa.VerificarPrimo(p) && cifa.VerificarPrimo(q)) { cifa.p = p; cifa.q = q; cifa.n = (cifa.p) * (cifa.q); //generando N cifa.z = (cifa.p - 1) * (cifa.q - 1); //Generando phu cifa.GenerandoE(); //cifa.e = 17; cifa.CalcularD(); cifa.Cifrar(PathKey, cl); using (var stream = new FileStream(PathPubl, FileMode.Create)) { //ya se creó el archivo } using (var stream = new FileStream(PathPriv, FileMode.Create)) { //ya se creó el archivo } cifa.EscribirArchPriv(PathPriv); cifa.EscribirArchPubl(PathPubl); // cifa string pathToSaveZip = Path.Combine(Directory.GetCurrentDirectory(), "Comprimido"); string archzip = Path.Combine(pathToSaveZip, "archivos.zip"); if (Directory.Exists(pathToSaveZip)) { FileInfo f = new FileInfo(archzip); f.Delete(); } else { Directory.CreateDirectory(pathToSaveZip); } ZipFile.CreateFromDirectory(pathToSave1, archzip); var stream1 = new FileStream(archzip, FileMode.Open); return(File(stream1, System.Net.Mime.MediaTypeNames.Application.Octet, "archivo.zip")); } else { return(null); } } else if (type_cipher == "diffie") { string auxB = Request.Form["B"]; Diffie cifa = new Diffie(); cifa.priv = Convert.ToInt32(cl); cifa.publ = Convert.ToInt32(auxB); cifa.CalcularPubl(); cl = cifa.k; //clave mayor a 26 if (cl > 25) { int n = -(25 - cl); cl = n; } cif.LlenarClaveInt(cl); using (var stream = new FileStream(fullPathC, FileMode.Create)) { //ya se creó el archivo } using (var stream = new FileStream(fullPath, FileMode.Create)) { file.CopyTo(stream); } using (var stream = new FileStream(fullPath, FileMode.Open)) { using (BinaryReader br = new BinaryReader(stream)) { while (br.BaseStream.Position != br.BaseStream.Length) { buffer = br.ReadBytes(BufferLength); //llenar el buffer cif.Cifrar(buffer); cif.EscribirCifrado(fullPathC); } } } cifa.EscribirArch(PathPubl, PathPriv); var stream1 = new FileStream(fullPathC, FileMode.Open); return(File(stream1, System.Net.Mime.MediaTypeNames.Application.Octet, "cifrado.txt")); } else { return(null); } } else { return(null); } } else { return(null); } }
public ActionResult Uploadimg() { var result = new ResultAdaptDto(); //long size = 0; //当设置了开始水印的时候,可以使用nomark来过滤图片不加水印 int nomark = RequestHelper.GetPostInt("nomark"); var files = Request.Form.Files; if (files.Count == 0) { result.status = false; result.message = "没有文件信息"; return(Content(result.ToJson())); } string url = $"/upfiles/images/{DateTime.Now.ToString("yyyyMMdd")}"; var folder = GlobalContext.WebRootPath + url; if (!Directory.Exists(folder)) { Directory.CreateDirectory(folder); } var file = files[0]; var filename = ContentDispositionHeaderValue .Parse(file.ContentDisposition) .FileName .Trim('"'); int index = filename.LastIndexOf('.'); string extName = filename.Substring(index); string guidstr = Guid.NewGuid().ToString("N"); string guidFileName = guidstr + extName; //这个hostingEnv.WebRootPath就是要存的地址可以改下 filename = $"{folder}/{guidFileName}"; using (FileStream fs = System.IO.File.Create(filename)) { file.CopyTo(fs); fs.Flush(); } var firstFileInfo = new FileInfo(filename); if (firstFileInfo.Length > 200 * 1024) { string compressFileName = IdHelper.ObjectId() + extName; string compressFile = $"{folder}/{compressFileName}"; ImageUtilities.CompressImage(filename, compressFile, 90, 200); guidFileName = compressFileName; } if (nomark == 0) { var imageSet = SiteManagerCache.GetUploadInfo(); if (imageSet.open_watermark == 1) { try { string sourcePath = $"{folder}/{guidFileName}"; if (System.IO.File.Exists(sourcePath)) { FileStream fs = new FileStream(sourcePath, FileMode.Open); //把文件读取到字节数组 byte[] data = new byte[fs.Length]; fs.Read(data, 0, data.Length); fs.Close(); //实例化一个内存流--->把从文件流中读取的内容[字节数组]放到内存流中去 MemoryStream ms = new MemoryStream(data); Image image = Image.FromStream(ms); if (image.Width > imageSet.image_width && image.Height > imageSet.image_height) { ImageWatermarker marker = new ImageWatermarker(); //图片水印 if (imageSet.watermark_type == 1) { string waterMarkIamge = GlobalContext.WebRootPath + imageSet.watermark_image; if (System.IO.File.Exists(waterMarkIamge)) { marker.AddImageSignPic(image, sourcePath, waterMarkIamge, imageSet.water_postion, imageSet.image_quality, imageSet.image_opacity); } } else { marker.AddWatermarkText(image, sourcePath, imageSet.watermark_word, imageSet.water_postion, imageSet.font_size, imageSet.font_color); } } } } catch (Exception ex) { LoggerHelper.Exception(ex); } } } string imgurl = $"{ url}/{guidFileName}"; result.data.Add("url", imgurl); return(Content(result.ToJson())); }
public async Task Instance_Post_WithNæringOgSkattemelding_ValidateOkThenNext() { // Gets JWT token. In production this would be given from authentication component when exchanging a ID porten token. string token = PrincipalUtil.GetToken(1337); // Setup client and calls Instance controller on the App that instansiates a new instances of the app HttpClient client = SetupUtil.GetTestClient(_factory, "tdd", "sirius"); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); HttpRequestMessage httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, "/tdd/sirius/instances?instanceOwnerPartyId=1337") { }; HttpResponseMessage response = await client.SendAsync(httpRequestMessage); string responseContent = await response.Content.ReadAsStringAsync(); Instance instance = JsonConvert.DeserializeObject <Instance>(responseContent); Assert.Equal(HttpStatusCode.Created, response.StatusCode); Assert.NotNull(instance); Assert.Equal("1337", instance.InstanceOwner.PartyId); // Get Data from the main form HttpRequestMessage httpRequestMessageGetData = new HttpRequestMessage(HttpMethod.Get, "/tdd/sirius/instances/" + instance.Id + "/data/" + instance.Data[0].Id); { }; HttpResponseMessage responseData = await client.SendAsync(httpRequestMessageGetData); string responseContentData = await responseData.Content.ReadAsStringAsync(); Skjema siriusMainForm = (Skjema)JsonConvert.DeserializeObject(responseContentData, typeof(Skjema)); // Modify the prefilled form. This would need to be replaced with the real sirius form siriusMainForm.Permisjonsopplysningergrp8822 = new Permisjonsopplysningergrp8822(); siriusMainForm.Permisjonsopplysningergrp8822.AnsattEierandel20EllerMerdatadef33294 = new AnsattEierandel20EllerMerdatadef33294() { value = "50" }; XmlSerializer serializer = new XmlSerializer(typeof(Skjema)); using MemoryStream stream = new MemoryStream(); serializer.Serialize(stream, siriusMainForm); stream.Position = 0; StreamContent streamContent = new StreamContent(stream); streamContent.Headers.ContentType = MediaTypeHeaderValue.Parse("text/xml"); streamContent.Headers.ContentDisposition = ContentDispositionHeaderValue.Parse("attachment; filename=data-element.xml"); HttpResponseMessage putresponse = await client.PutAsync("/tdd/sirius/instances/" + instance.Id + "/data/" + instance.Data[0].Id, streamContent); // Add Næringsoppgave.xml string næringsppgave = File.ReadAllText("Data/Files/data-element.xml"); byte[] byteArray = Encoding.UTF8.GetBytes(næringsppgave); //byte[] byteArray = Encoding.ASCII.GetBytes(contents); MemoryStream næringsoppgavestream = new MemoryStream(byteArray); StreamContent streamContentNæring = new StreamContent(næringsoppgavestream); streamContentNæring.Headers.ContentDisposition = ContentDispositionHeaderValue.Parse("attachment; filename=data-element.xml"); streamContentNæring.Headers.ContentType = MediaTypeHeaderValue.Parse("text/xml"); HttpResponseMessage postresponseNæring = await client.PostAsync("/tdd/sirius/instances/" + instance.Id + "/data/?datatype=næringsoppgave", streamContentNæring); DataElement dataElementNæring = (DataElement)JsonConvert.DeserializeObject(await postresponseNæring.Content.ReadAsStringAsync(), typeof(DataElement)); // Add skattemelding.xml string skattemelding = File.ReadAllText("Data/Files/data-element.xml"); byte[] byteArraySkattemelding = Encoding.UTF8.GetBytes(skattemelding); //byte[] byteArray = Encoding.ASCII.GetBytes(contents); MemoryStream skattemeldingstream = new MemoryStream(byteArraySkattemelding); HttpContent streamContentSkattemelding = new StreamContent(skattemeldingstream); streamContent.Headers.ContentType = MediaTypeHeaderValue.Parse("text/xml"); streamContent.Headers.ContentDisposition = ContentDispositionHeaderValue.Parse("attachment; filename=data-element.xml"); HttpResponseMessage postresponseskattemelding = await client.PostAsync("/tdd/sirius/instances/" + instance.Id + "/data/?datatype=skattemelding", streamContentNæring); DataElement dataElementSkattemelding = (DataElement)JsonConvert.DeserializeObject(await postresponseskattemelding.Content.ReadAsStringAsync(), typeof(DataElement)); // Validate instance. This validates that main form has valid data and required data string url = "/tdd/sirius/instances/" + instance.Id + "/validate"; HttpResponseMessage responseValidation = await client.GetAsync(url); string responseContentValidation = await responseValidation.Content.ReadAsStringAsync(); List <ValidationIssue> messages = (List <ValidationIssue>)JsonConvert.DeserializeObject(responseContentValidation, typeof(List <ValidationIssue>)); Assert.Empty(messages); // Handle first next go from data to confirmation HttpRequestMessage httpRequestMessageFirstNext = new HttpRequestMessage(HttpMethod.Put, "/tdd/sirius/instances/" + instance.Id + "/process/next") { }; HttpResponseMessage responseFirstNext = await client.SendAsync(httpRequestMessageFirstNext); string responseContentFirstNext = await responseFirstNext.Content.ReadAsStringAsync(); ProcessState stateAfterFirstNext = (ProcessState)JsonConvert.DeserializeObject(responseContentFirstNext, typeof(ProcessState)); Assert.Equal("Task_2", stateAfterFirstNext.CurrentTask.ElementId); // Validate instance in Task_2. This validates that PDF for nærings is in place HttpResponseMessage responseValidationTask2 = await client.GetAsync(url); string responseContentValidationTask2 = await responseValidationTask2.Content.ReadAsStringAsync(); List <ValidationIssue> messagesTask2 = (List <ValidationIssue>)JsonConvert.DeserializeObject(responseContentValidationTask2, typeof(List <ValidationIssue>)); Assert.Empty(messagesTask2); // Move process from Task_2 (Confirmation) to Task_3 (Feedback). HttpRequestMessage httpRequestMessageSecondNext = new HttpRequestMessage(HttpMethod.Put, "/tdd/sirius/instances/" + instance.Id + "/process/next") { }; HttpResponseMessage responseSecondNext = await client.SendAsync(httpRequestMessageSecondNext); string responseContentSecondNext = await responseSecondNext.Content.ReadAsStringAsync(); ProcessState stateAfterSecondNext = (ProcessState)JsonConvert.DeserializeObject(responseContentSecondNext, typeof(ProcessState)); Assert.Equal("Task_3", stateAfterSecondNext.CurrentTask.ElementId); // Delete all data created TestDataUtil.DeleteInstanceAndData("tdd", "sirius", 1337, new Guid(instance.Id.Split('/')[1])); }
public IActionResult Img(string savesize = "[]") { try { uploadfile user = new uploadfile(); var files = Request.Form.Files; if (files == null || files.Count == 0) { return(Json(new { jsonrpc = "2.0", error = new { code = 101, message = "没有上传图片" }, id = "id" })); } user.ShareImg = files[0]; var contentRoot = Directory.GetCurrentDirectory(); var webRoot = Path.Combine(contentRoot, "wwwroot"); var parsedContentDisposition = ContentDispositionHeaderValue.Parse(user.ShareImg.ContentDisposition); var originalName = parsedContentDisposition.FileName.ToString().Replace("\"", ""); var ext = Path.GetExtension(Path.Combine(webRoot, originalName)); if (ext != ".jpg") { return(Json(new { jsonrpc = "2.0", error = new { code = 101, message = "文件格式错误" }, id = "id" })); } var fileName = Path.Combine("upload", Guid.NewGuid().ToString() + "_" + savesize + ext); using (var stream = new FileStream(Path.Combine(webRoot, fileName), FileMode.CreateNew)) { user.ShareImg.CopyTo(stream); } FileInfo file = new FileInfo(Path.Combine(webRoot, fileName)); //缩略图(最后一张生成缩略图) var sizeArray = savesize.Substring(savesize.LastIndexOf("[") + 1, savesize.IndexOf("]") - 1).Split('-'); var thumbnail = ""; string fn_thum = ""; string fullname = ""; int width_thum = 0; int height_thum = 0; for (int i = 0; i < sizeArray.Length; i++) { if (sizeArray[i] != "") { var wh = sizeArray[i].Split('x');; if (wh.Length == 2) { //宽 width_thum = int.Parse(wh[0]); //高 height_thum = int.Parse(wh[1]); fn_thum = fileName.Replace(ext, "_thum" + ext); fullname = Path.Combine(webRoot, fn_thum); thumbnail = "\\" + fn_thum; } } } ////生成缩略图 if (thumbnail != "") { IMGUtility.Thumbnail(Path.Combine(webRoot, fileName), fullname, width_thum, height_thum, CutMode.None); } return(Content(JsonHelper.SerializeObject(new { jsonrpc = "2.0", result = Path.Combine(webRoot, fileName), id = "id", imgthum = thumbnail }))); } catch (Exception exc) { NLogger.Error(exc.ToString()); return(Content(JsonHelper.SerializeObject(new { jsonrpc = "2.0", error = new { code = 101, message = exc.Message }, id = "id" }))); } }
public async Task <Result <FileModel> > UploadFile() { var form = await Request.ReadFormAsync(); int? bugTicketId = null; int? bugTicketCommentId = null; string publicId = null; string description = String.Empty; if (!StringValues.IsNullOrEmpty(form["bugTicketId"])) { bugTicketId = Int32.Parse(form["bugTicketId"]); } if (!StringValues.IsNullOrEmpty(form["bugTicketCommentId"])) { bugTicketCommentId = Int32.Parse(form["bugTicketCommentId"]); } if (!StringValues.IsNullOrEmpty(form["publicId"])) { publicId = form["publicId"]; } var parsedContentDisposition = ContentDispositionHeaderValue.Parse(form.Files[0].ContentDisposition); var contentType = form.Files[0].ContentType; using (var stream = form.Files[0].OpenReadStream()) { var fileContent = stream.ReadFully(); try { BugFile file = null; var mode = bugTicketId.HasValue ? BugFileType.Ticket : BugFileType.Comment; var fileName = await _helpService.UploadBugFileToStoreAsync(mode, fileContent, parsedContentDisposition.FileName.Replace("\"", ""), publicId, contentType); if (!String.IsNullOrEmpty(fileName) && ((bugTicketId.HasValue && bugTicketId != 0) || (bugTicketCommentId.HasValue && bugTicketCommentId != 0))) { file = new BugFile { IdBugTicket = bugTicketId, IdBugTicketComment = bugTicketCommentId, FileName = fileName, Description = description }; file = await _helpService.AddBugFileAsync(file); } var uploadDate = file?.UploadDate ?? DateTime.Now; var id = file?.Id ?? 0; return(new FileModel() { FileName = fileName, UploadDate = uploadDate, Id = id }); } catch (Exception ex) { _logger.LogError(ex.ToString()); throw; } } }