public IActionResult Upload(IFormFileCollection files) { throw new NotImplementedException(); }
public IActionResult Upload(HttpPostedFileBase myFile, [Required] IFormFile myFile2, ICollection<IFormFile> files, ICollection<HttpPostedFileBase> files2, IFormFileCollection files3) { throw new NotImplementedException(); }
public async Task<IEnumerable<string>> UploadAsync(IFormFileCollection files) { var result = new List<string>(); foreach (var file in files) { //bug !!!not checked!!! var file = files[fileName]; var newName = GenerateNewName() + "." + file.FileName.Split('.').Last(); var newPath = GenerateNewPath(ImagesPath); var relativePath = Path.Combine(newPath, newName); var path = GetFullPath(relativePath); using (var fileStream = new FileStream(path, FileMode.Create)) { await file.CopyToAsync(fileStream); } result.Add(relativePath); } return result; }
public MyFormCollection(IDictionary<string, string[]> store, IFormFileCollection files) : base(store) { Files = files; }
public FormCollection(IDictionary<string, StringValues> store, IFormFileCollection files) : base(store) { if (store == null) { throw new ArgumentNullException(nameof(store)); } if (files == null) { throw new ArgumentNullException(nameof(files)); } Files = files; }
public async Task<AdvertisementItemPhotosPaths> SaveAdvertisementPhotos(IFormFileCollection files) { var photosPathsModel = new AdvertisementItemPhotosPaths(); var filesCount = files.Count; for (int i = 0; i < filesCount; i++) { using (Stream readStream = files.GetFile(this.appFilesNamesHelper.GetPhotoNameInForm(i)).OpenReadStream()) { var newFileName = this.appFilesNamesHelper.GetPhotoRandomUniqueName("jpg"); var newFilePath = String.Concat(this.appFilesPathHelper.GetAdvertisementPhotosMainPath(), "/", newFileName); using (FileStream fileStream = System.IO.File.Create(newFilePath)) { await readStream.CopyToAsync(fileStream); photosPathsModel.PhotosPaths.Add(newFilePath); } //first file (name ends with "0") will be main photo if (i==0) { var minImage = CreateMinPhoto(readStream); var newMinFilePath = String.Concat(this.appFilesPathHelper.GetAdvertisementMinPhotosMainPath(), "/", newFileName); minImage.Save(newMinFilePath, System.Drawing.Imaging.ImageFormat.Jpeg); photosPathsModel.PhotosPaths.Add(newMinFilePath); } } } return photosPathsModel; }
public void ActionWithFormFileCollectionParameter(IFormFileCollection formFile) { }
public IEnumerable <Arquivo> GravarArquivosUpload(IFormFileCollection arquivos, int formularioId, string caminhoDiretorio) { this.WriteFiles(arquivos, formularioId, caminhoDiretorio); return(this.aArquivos); }
public async Task <MessageModel <string> > InsertPicture([FromServices] IWebHostEnvironment environment) { var data = new MessageModel <string>(); string path = string.Empty; string foldername = "images"; IFormFileCollection files = null; // 获取提交的文件 files = Request.Form.Files; // 获取附带的数据 var max_ver = Request.Form["max_ver"].ObjToString(); if (files == null || !files.Any()) { data.msg = "请选择上传的文件。"; return(data); } //格式限制 var allowType = new string[] { "image/jpg", "image/png", "image/jpeg" }; string folderpath = Path.Combine(environment.WebRootPath, foldername); if (!Directory.Exists(folderpath)) { Directory.CreateDirectory(folderpath); } if (files.Any(c => allowType.Contains(c.ContentType))) { if (files.Sum(c => c.Length) <= 1024 * 1024 * 4) { //foreach (var file in files) var file = files.FirstOrDefault(); string strpath = Path.Combine(foldername, DateTime.Now.ToString("MMddHHmmss") + file.FileName); path = Path.Combine(environment.WebRootPath, strpath); using (var stream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite)) { await file.CopyToAsync(stream); } data = new MessageModel <string>() { response = strpath, msg = "上传成功", success = true, }; return(data); } else { data.msg = "图片过大"; return(data); } } else { data.msg = "图片格式错误"; return(data); } }
public AddMediaCommand(AddMediaRequest request, IFormFileCollection files) { File = files[0]; }
public async Task AddFileAsync(MethodOptions methodOptions, StorageOptions storageOptions, IFormFileCollection files, string subPath) { ICollection <EndpointOptions> endpoints = GetWriteEndpoints(methodOptions, storageOptions).ToList(); foreach (var file in files) { if (string.IsNullOrEmpty(file.FileName)) { Log.Warning("Attempt to upload a file with a null or empty name"); continue; } try { foreach (EndpointOptions endpoint in endpoints) { IBlobStorage storage = _storageProvider.GetStorage(endpoint.Provider); using (var fs = file.OpenReadStream()) { await storage.WriteAsync(file.FileName, fs); } } } catch (Exception ex) { Log.Error(ex, ex.Message); } } }
public IActionResult CommintFK111(IFormCollection Files, string jsonArray, string registerCode, string fkcount) { // JsonArray jsonObject = JsonConvert.DeserializeObject<JsonArray>(jsonArray); var resultCountModel = new RespResultCountViewModel(); //string fileCode = "";//申诉主表编码 try { //UserInfo userInfo = new UserInfo //{ // UserId = User.GetCurrentUserId(), // UserName = User.GetCurrentUserName(), // InstitutionCode = User.GetCurrentUserOrganizeId(), // InstitutionName = User.GetCurrentUserOrganizeName() //}; ////改ID为申诉主表的主键CheckComplainId //if (!string.IsNullOrEmpty(fkcount) && fkcount == "1") //{ // fileCode = _complaintMZService.Commint("2", jsonObject, registerCode, userInfo); //} //else if (!string.IsNullOrEmpty(fkcount) && fkcount == "2") //{ // fileCode = _complaintMZService.Commint("22", jsonObject, registerCode, userInfo); //} IFormFileCollection cols = Request.Form.Files; int i = 0; foreach (IFormFile file in cols) { i++; //定义文件数组后缀格式 string[] LimitFileType = { ".JPG", ".JPEG", ".PNG", ".GIF", ".PNG", ".BMP", ".DOC", ".DOCX", ".XLS", ".XLSX", ".TXT", ".PDF" }; string[] LimitFileType1 = { ".JPG", ".JPEG", ".PNG", ".GIF", ".PNG", ".BMP" }; string[] LimitFileType2 = { ".DOC", ".DOCX", ".XLS", ".XLSX", ".TXT", ".PDF" }; //获取文件后缀是否存在数组中 string currentPictureExtension = Path.GetExtension(file.FileName).ToUpper(); if (LimitFileType.Contains(currentPictureExtension)) { var uppath = XYDbContext.UPLOADPATH + "医院初次反馈上传/" + 222222 + "/"; var new_path = Path.Combine(uppath, file.FileName); var path = Path.Combine(Directory.GetCurrentDirectory(), new_path); if (!Directory.Exists(uppath)) { Directory.CreateDirectory(uppath); } using (var stream = new FileStream(path, FileMode.Create)) { byte[] fileByte = new byte[file.Length]; //用文件的长度来初始化一个字节数组存储临时的文件 Stream fileStream = file.OpenReadStream(); //建立文件流对象 //再把文件保存的文件夹中 file.CopyTo(stream); } } else { return(Ok(new { status = -2, message = "请上传指定格式的图片", data = "" })); } } return(Ok(new { status = 0, message = "上传成功", data = "" })); } catch (Exception ex) { return(Ok(new { status = -3, message = "上传失败", data = ex.Message })); } }
public async Task <RespuestaDatos> SubirDocumentosEmprendedor(string correoUsuario, string razonSoccial, IFormFileCollection files) { DemografiaCor demografiaCor = _cOGeneralFachada.GetDemografiaPorEmail(correoUsuario); return(await _cOSeguridadBiz.SubirDocumentosEmprendedor(demografiaCor, razonSoccial, files)); }
/// <summary> /// პიროვნების ფაილის ატვირთვა რედაქტირება /// </summary> /// <param name="personId"></param> /// <param name="filesData"></param> /// <returns></returns> public async Task <Result> UploadUpdatePersonFile(int?personId, IFormFileCollection pFiles) { var currentDate = DateTime.Now; if (personId == 0 || personId == null) { return(new Result(false, 12, ValidationMassages.PersonIdMustProvided)); } if (pFiles.IsNullOrEmpty()) { return(new Result(false, 13, ValidationMassages.FileMustProvided)); } var filesData = pFiles.First(); // არსებობს თუ არა ასეთი იდენტიფიქატორით ჩანაწერი var personDB = await personRepository.GetParentPersonAsync(personId.GetValueOrDefault()); if (personDB == null) { return(new Result(false, 13, ValidationMassages.PersonNotFound)); } //ფაილის ფორმატზე გადამოწმება var fileType = Path.GetExtension(filesData.FileName).ToLower(); if (!fileFormat.Contains(fileType, StringComparison.OrdinalIgnoreCase)) { return(new Result(false, -1, ValidationMassages.WrongFileFormat)); } //var megabyte = new decimal(1024 * 1024); //// ფაილის ზომის წამოღება //var uploadFileSize = Math.Round(filesData.Length / megabyte, 2, MidpointRounding.AwayFromZero); //if ((uploadFileSize) > 5) //{ // return new Result(false, -1, "ფაილების მაქსიმალური ზომა არ უნდა აღემატებოდეს 5MB -ს"); //} //ფაილებს ვინახავთ პიროვნების იდენტიფიქატორის სახელის მქონე საქაღალდეში var subDirectory = personId.GetValueOrDefault().ToString(); var target = Path.Combine(directoryAddress, subDirectory); // თუ ესეთი საქაღალდე არ არსებობს if (!Directory.Exists(target)) { Directory.CreateDirectory(target); } //ფაილის შენახვა მოცემულ საქაღალდეში var filePath = Path.Combine(target, Guid.NewGuid().ToString() + fileType); using (var stream = new FileStream(filePath, FileMode.Create)) { await filesData.CopyToAsync(stream); } var personFiles = new PersonFiles { FilePath = filePath, PersonId = personId.GetValueOrDefault(), DateCreated = currentDate, }; var result = await personFilesRepository.UpdatePersonFilesAsync(personFiles); return(result); }
public async Task <IActionResult> AddNews(AddNewsViewModel model, IFormFileCollection uploads) { // Проверяем, чтобы размер файлов не превышал заданный объем foreach (var file in uploads) { if (file.Length > 2097152) { ModelState.AddModelError("NewsImage", $"Файл \"{file.FileName}\" превышает установленный лимит 2MB."); break; } } // Если все в порядке, заходим в тело условия if (ModelState.IsValid) { // Создаем экземпляр класса News и присваиваем ему значения News news = new News() { Id = Guid.NewGuid(), NewsTitle = model.NewsTitle, NewsBody = model.NewsBody, NewsDate = DateTime.Now, UserName = "******" // В рабочем варианте будет брать имя из User.Identity }; // Далее начинаем обработку изображений List <NewsImage> newsImages = new List <NewsImage>(); foreach (var uploadedImage in uploads) { // Если размер входного файла больше 0, заходим в тело условия if (uploadedImage.Length > 0) { // Создаем новый объект класса FileInfo из полученного изображения для дальнейшей обработки FileInfo imgFile = new FileInfo(uploadedImage.FileName); // Приводим расширение к нижнему регистру (если оно было в верхнем) string imgExtension = imgFile.Extension.ToLower(); // Генерируем новое имя для файла string newFileName = Guid.NewGuid() + imgExtension; // Пути сохранения файла string pathNormal = "/files/images/normal/" + newFileName; // изображение исходного размера string pathScaled = "/files/images/scaled/" + newFileName; // уменьшенное изображение // В операторе try/catch делаем уменьшенную копию изображения. // Если входным файлом окажется не изображение, нас перекинет в блок CATCH и выведет сообщение об ошибке try { // Создаем объект класса SixLabors.ImageSharp.Image и грузим в него полученное изображение using (Image image = Image.Load(uploadedImage.OpenReadStream())) { // Создаем уменьшенную копию и обрезаем её var clone = image.Clone(x => x.Resize(new ResizeOptions { Mode = ResizeMode.Crop, Size = new Size(300, 200) })); // Сохраняем уменьшенную копию await clone.SaveAsync(_appEnvironment.WebRootPath + pathScaled, new JpegEncoder { Quality = 50 }); // Сохраняем исходное изображение await image.SaveAsync(_appEnvironment.WebRootPath + pathNormal); } } // Если вдруг что-то пошло не так (например, на вход подало не картинку), то выводим сообщение об ошибке catch { // Создаем сообщение об ошибке для вывода пользователю ModelState.AddModelError("NewsImage", $"Файл {uploadedImage.FileName} имеет неверный формат."); // Удаляем только что созданные файлы (если ошибка возникла не на первом файле) foreach (var image in newsImages) { // Исходные (полноразмерные) изображения FileInfo imageNormal = new FileInfo(_appEnvironment.WebRootPath + image.ImagePathNormal); if (imageNormal.Exists) { imageNormal.Delete(); } // И их уменьшенные копии FileInfo imageScaled = new FileInfo(_appEnvironment.WebRootPath + image.ImagePathScaled); if (imageScaled.Exists) { imageScaled.Delete(); } } // Возвращаем модель с сообщением об ошибке в представление return(View(model)); } // Создаем объект класса NewsImage со всеми параметрами NewsImage newsImage = new NewsImage() { Id = Guid.NewGuid(), ImageName = newFileName, ImagePathNormal = pathNormal, ImagePathScaled = pathScaled, NewsId = news.Id }; // Добавляем объект newsImage в список newsImages newsImages.Add(newsImage); } } // Если в процессе выполнения не возникло ошибок, сохраняем всё в БД if (newsImages != null && newsImages.Count > 0) { await cmsDB.NewsImages.AddRangeAsync(newsImages); } await cmsDB.News.AddAsync(news); await cmsDB.SaveChangesAsync(); // Редирект на главную страницу return(RedirectToAction("Index", "News")); } // Возврат модели в представление в случае, если запорится валидация return(View(model)); }
public async Task <ActionResult <MainResponse> > EditAvatar(IFormFileCollection file) { User user = HttpContext.GetUser(); if (file == null || file.Count != 2) { return(BadRequest()); } IFormFile thumb = file.FirstOrDefault(p => p.FileName.EndsWith("::t")); if (thumb == null) { return(BadRequest()); } IFormFile formFile = file.FirstOrDefault(p => !p.FileName.EndsWith("::t")); if (formFile == null) { return(BadRequest()); } string path = _serverConfig.Users.Paths.MainPath + _serverConfig.Users.Paths.ImagesPath; string hashName = Hash.Sha1(Path.GetFileNameWithoutExtension(formFile.FileName) + user.Id); string extension = Path.GetExtension(formFile.FileName); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } string thumbPath = path + "\\" + hashName + "_t" + extension; path += "\\" + hashName + extension; using (Stream stream = new FileStream(path, FileMode.Create)) { await formFile.CopyToAsync(stream); } using (Stream stream = new FileStream(thumbPath, FileMode.Create)) { await thumb.CopyToAsync(stream); } FileData fileData = await _context.Files.FirstOrDefaultAsync(p => p.PhysicalName == hashName + extension); if (fileData == null) { fileData = new FileData() { FileName = formFile.FileName, PhysicalName = hashName + extension, Type = Enums.FileType.Image, UploadDate = DateTime.Now, Thumbnail = hashName + "_t" + extension }; _context.Files.Add(fileData); user.Files.Add(fileData); } user.Img = fileData; await _context.SaveChangesAsync().ConfigureAwait(false); return(MainResponse.GetSuccess()); }
public IActionResult FormFileCollectionParameter(IFormFileCollection formFiles) => null;
public IActionResult PostFile(FileData fileData, IFormFileCollection files) { var requestFiles = Request.Form.Files; return(Ok()); }
public IActionResult PostStaticFile(IFormFileCollection files) { var requestFiles = Request.Form.Files; return(Ok()); }
public virtual ValidationResult Validate(IFormFileCollection formFileCollection) { return(_nextStep != null ? _nextStep.Validate(formFileCollection) : ValidationResultFactory.CreateValidationResultSucceeded()); }
public async Task <RespuestaDatos> SubirImagenSocial(string correoUsuario, IFormFileCollection files) { DemografiaCor demografiaCor = _cOGeneralFachada.GetDemografiaPorEmail(correoUsuario); return(await _cOSeguridadBiz.SubirImagenSocial(files, demografiaCor)); }
public async Task <bool> UploadClarificationFile(Guid applicationId, string userId, IFormFileCollection clarificationFiles) { var fileName = string.Empty; var content = new MultipartFormDataContent(); content.Add(new StringContent(userId), "userId"); if (clarificationFiles != null && clarificationFiles.Any()) { foreach (var file in clarificationFiles) { fileName = file.FileName; var fileContent = new StreamContent(file.OpenReadStream()) { Headers = { ContentLength = file.Length, ContentType = new MediaTypeHeaderValue(file.ContentType) } }; content.Add(fileContent, file.FileName, file.FileName); } try { var response = await _client.PostAsync($"/Clarification/Applications/{applicationId}/Upload", content); return(response.StatusCode == HttpStatusCode.OK); } catch (HttpRequestException ex) { _logger.LogError(ex, $"Error when submitting Clarification File update for Application: {applicationId} | Filename: {fileName}"); return(false); } } return(true); }
public async Task <IActionResult> FileJacobiDownload(JacobiMethod jacobiMethod, IFormFileCollection inputFiles) { uint id = _options.FileId; lock (_options) _options.FileId++; List <string> markers = new List <string> { "A", "b", "x" }; int i = 0; string fileResult = _hostingEnvironment.WebRootPath + "\\output_files\\"; foreach (var file in inputFiles) { if (file != null) { string files = Path.Combine(_hostingEnvironment.WebRootPath, "input_files"); string filePath = Path.Combine(files, id.ToString() + markers[i] + ".txt"); await using FileStream stream = System.IO.File.Create(filePath); await file.CopyToAsync(stream); stream.Close(); } i++; } JacobiMethodCPlusPlus jacobiMethodCPlusPlus = new JacobiMethodCPlusPlus(); if (jacobiMethodCPlusPlus.method(id, jacobiMethod.Eps)) { fileResult += id.ToString() + ".txt"; } else { fileResult += "empty.txt"; } Stream newStream = new FileStream(fileResult, FileMode.Open); return(File(newStream, "text/plain")); }
/// <summary> /// 上传单个文件 /// </summary> /// <param name="fileModule"></param> /// <param name="fileCollection"></param> /// <returns></returns> public async static Task <TData <string> > UploadFile(int fileModule, IFormFileCollection files) { string dirModule = string.Empty; TData <string> obj = new TData <string>(); if (files == null || files.Count == 0) { obj.Message = "请先选择文件!"; return(obj); } if (files.Count > 1) { obj.Message = "一次只能上传一个文件!"; return(obj); } TData objCheck = null; IFormFile file = files[0]; switch (fileModule) { case (int)UploadFileType.Portrait: objCheck = CheckFileExtension(Path.GetExtension(file.FileName), ".jpg|.jpeg|.gif|.png"); if (objCheck.Tag != 1) { obj.Message = objCheck.Message; return(obj); } dirModule = UploadFileType.Portrait.ToString(); break; case (int)UploadFileType.News: if (file.Length > 5 * 1024 * 1024) // 5MB { obj.Message = "文件最大限制为 5MB"; return(obj); } objCheck = CheckFileExtension(Path.GetExtension(file.FileName), ".jpg|.jpeg|.gif|.png"); if (objCheck.Tag != 1) { obj.Message = objCheck.Message; return(obj); } dirModule = UploadFileType.News.ToString(); break; case (int)UploadFileType.Import: objCheck = CheckFileExtension(Path.GetExtension(file.FileName), ".xls|.xlsx"); if (objCheck.Tag != 1) { obj.Message = objCheck.Message; return(obj); } dirModule = UploadFileType.Import.ToString(); break; default: obj.Message = "请指定上传到的模块"; return(obj); } string fileExtension = TextHelper.GetCustomValue(Path.GetExtension(file.FileName), ".png"); string newFileName = SecurityHelper.GetGuid(true) + fileExtension; string dir = "Resource" + Path.DirectorySeparatorChar + dirModule + Path.DirectorySeparatorChar + DateTime.Now.ToString("yyyy-MM-dd").Replace('-', Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar; string absoluteDir = Path.Combine(GlobalContext.HostingEnvironment.ContentRootPath, dir); string absoluteFileName = string.Empty; if (!Directory.Exists(absoluteDir)) { Directory.CreateDirectory(absoluteDir); } absoluteFileName = absoluteDir + newFileName; try { using (FileStream fs = File.Create(absoluteFileName)) { await file.CopyToAsync(fs); fs.Flush(); } obj.Data = Path.AltDirectorySeparatorChar + ConvertDirectoryToHttp(dir) + newFileName; obj.Message = Path.GetFileNameWithoutExtension(TextHelper.GetCustomValue(file.FileName, newFileName)); obj.Description = (file.Length / 1024).ToString(); // KB obj.Tag = 1; } catch (Exception ex) { obj.Message = ex.Message; } return(obj); }
public async Task <IActionResult> UploadPictures(IFormFileCollection files, [FromForm] string userId) { if (files.Count == 0) { return(Content("file not selected")); } // Create the CloudBlobClient that represents the Blob storage endpoint for the storage account. var cloudBlobClient = _storageAccount.CreateCloudBlobClient(); // Create a container called 'quickstartblobs' and append a GUID value to it to make the name unique. var cloudBlobContainer = cloudBlobClient.GetContainerReference("pictures"); await cloudBlobContainer.CreateIfNotExistsAsync(); // Set the permissions so the blobs are public. var permissions = new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob }; await cloudBlobContainer.SetPermissionsAsync(permissions); var user = await _userManager.FindByIdAsync(userId); using (var client = new HttpClient()) { client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", _config["FaceApi:Key"]); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var person = new { Name = user.Email }; var result = await client.PostAsync("https://westeurope.api.cognitive.microsoft.com/face/v1.0/largepersongroups/pictit_users/persons", new StringContent(JsonConvert.SerializeObject(person), Encoding.UTF8, "application/json")); if (result.IsSuccessStatusCode) { try { var createdPerson = await result.Content.ReadAsAsync <Person>(); user.PersonId = Guid.Parse(createdPerson.PersonId); await _userManager.UpdateAsync(user); foreach (var file in files) { var stream = file.OpenReadStream(); var resultPicture = await client.PostAsync("https://westeurope.api.cognitive.microsoft.com/face/v1.0/detect?returnFaceId=true&returnFaceLandmarks=true&returnFaceAttributes=age,gender,smile,facialHair,glasses,emotion,hair,makeup,occlusion,accessories,blur,exposure,noise", stream, new BinaryMediaTypeFormatter()); if (resultPicture.IsSuccessStatusCode) { try { var faces = await resultPicture.Content.ReadAsAsync <IEnumerable <Face> >(); // Get a reference to the blob address, then upload the file to the blob. // Use the value of fileName for the blob name. var picture = new Picture { UserId = Guid.Parse(userId), Face = faces.First(), Extension = MimeTypeMap.GetExtension(file.ContentType) }; bool succeeded = await _pictureRepository.Insert(picture); if (!succeeded) { continue; } var fileName = picture.Id + MimeTypeMap.GetExtension(file.ContentType); System.Console.WriteLine(fileName); var cloudBlockBlob = cloudBlobContainer.GetBlockBlobReference(fileName); await cloudBlockBlob.UploadFromStreamAsync(file.OpenReadStream()); stream = file.OpenReadStream(); await client.PostAsync($"https://westeurope.api.cognitive.microsoft.com/face/v1.0/largepersongroups/pictit_users/persons/{user.PersonId}/persistedfaces", stream, new BinaryMediaTypeFormatter()); } catch (Exception e) { Console.WriteLine(e.Message); } } } await _pictureRepository.Save(); var resultTrainingStatus = await client.GetAsync("https://westeurope.api.cognitive.microsoft.com/face/v1.0/largepersongroups/pictit_users/training"); if (resultTrainingStatus.IsSuccessStatusCode) { string answer = await resultTrainingStatus.Content.ReadAsStringAsync(); if (answer.IndexOf("running", StringComparison.Ordinal) == -1) { await client.PostAsync("https://westeurope.api.cognitive.microsoft.com/face/v1.0/largepersongroups/pictit_users/train", null); } } } catch (Exception e) { Console.WriteLine(e.Message); } } } return(Ok()); }
/**public void Post([FromBody] string value) * { * }**/ public async Task <IActionResult> Post()//ASP.NET MVC 操作支持使用简单的模型绑定(针对较小文件)或流式处理(针对较大文件)上传一个或多个文件。(在此选择流式处理)) { // return (Content(Request.Query["FolderAndFileName"])); //判断是本机版还是服务器版,服务器不允许上传 if (new LocalVersionOrServerVersion().IsLocalVersion(this.Request.Host.ToUriComponent())) { IFormFileCollection files = Request.Form.Files; long size = files.Sum(f => f.Length); string webRootPath = _hostingEnvironment.WebRootPath; string contentRootPath = _hostingEnvironment.ContentRootPath; String filePathPartTemp = "\\webCourse\\lessons\\content\\book\\"; String filePathAll = ""; String FolderPath = webRootPath + filePathPartTemp + Request.Query["FolderAndFileName"]; foreach (var formFile in files) { if (formFile.Length > 0) { string fileExt = formFile.FileName.Substring(formFile.FileName.IndexOf("."), formFile.FileName.Length - formFile.FileName.IndexOf(".")); //文件扩展名,含“.” long fileSize = formFile.Length; //获得文件大小,以字节为单位 Directory.CreateDirectory(FolderPath); String filePath = FolderPath + "\\" + Request.Query["FolderAndFileName"] + fileExt; using (var stream = new FileStream(filePath, FileMode.Create)) { await formFile.CopyToAsync(stream); } filePathAll += filePath; //将Word另存为.htm; //创建一个名为WordApp的组件对象 try { Application WordApp = new ApplicationClass(); //必须设置为不可见 WordApp.Visible = false; Document document = WordApp.Documents.Open(filePath); document.WebOptions.Encoding = MsoEncoding.msoEncodingUTF8; //document.SaveAs2(FolderPath + "\\" + Request.Query["FolderAndFileName"] + ".htm", Encoding.UTF8, WdSaveFormat.wdFormatFilteredHTML);//无法调用.net的编码 //document.SaveAs2(FolderPath + "\\" + Request.Query["FolderAndFileName"] + ".htm", WdSaveFormat.wdFormatFilteredHTML, MsoEncoding.msoEncodingUTF8); document.SaveAs2(FolderPath + "\\" + Request.Query["FolderAndFileName"] + ".htm", WdSaveFormat.wdFormatFilteredHTML); // document.SaveAs2(FolderPath + "\\" + Request.Query["FolderAndFileName"] + ".htm" ,WdSaveFormat.wdFormatFilteredHTML, MsoEncoding.msoEncodingUTF8);//加入UTF-8编码暂时未成功//增加了COM形式的依赖,但COM形式的在Web服务器端无法调用?,NUGET形式的可以。 document.Close(); WordApp.Quit(); WordApp = null; //杀死打开的word进程//没达到预期。好像也没必要杀死。 Process myProcess = new Process(); Process[] wordProcess = Process.GetProcessesByName("winword"); try { foreach (Process pro in wordProcess) //这里是找到那些没有界面的Word进程 { IntPtr ip = pro.MainWindowHandle; string str = pro.MainWindowTitle; //发现程序中打开跟用户自己打开的区别就在这个属性。用户打开的str 是文件的名称,程序中打开的就是空字符串。 if (string.IsNullOrEmpty(str)) { pro.Kill(); } } } catch (Exception ex) { ex.ToString(); } } catch (Exception Ex) { throw new Exception(Ex.Message); } } else { string fileExt = formFile.FileName.Substring(formFile.FileName.IndexOf("."), formFile.FileName.Length - formFile.FileName.IndexOf(".")); //文件扩展名,含“.” long fileSize = formFile.Length; //获得文件大小,以字节为单位 //String FolderPath = webRootPath + filePathPartTemp + Request.Query["FolderAndFileName"]; Directory.CreateDirectory(FolderPath); String filePath = FolderPath + "\\" + Request.Query["FolderAndFileName"] + fileExt; filePathAll += filePath; } } //(已解决).htm文件中增加想要的代码 //好象Word转.htm如果非UTF-8编码方式,会出乱码。Microsoft.Office.Interop.Word默认又不提供该编程机制。目前只好修改操作系统的默认编码(ANSI中文简体/GB2312/GBK)为UTF-8.Microsoft.Office.Interop.Word转化.htm时默认就是UTF-8了。不乱码。应该也是最好维护,最便于Word与.htm互转。 // StreamReader streamReader = new StreamReader(FolderPath + "\\" + Request.Query["FolderAndFileName"] + ".htm", System.Text.Encoding.UTF8);// 创建文本的读取流(会检查字节码标记确定编码格式)//好像调用JS文件出错 StreamReader streamReader = new StreamReader(FolderPath + "\\" + Request.Query["FolderAndFileName"] + ".htm", new TexFileEncodeType().GetFileEncodeType(FolderPath + "\\" + Request.Query["FolderAndFileName"] + ".htm")); // 创建文本的读取流(会检查字节码标记确定编码格式) String stringFromFile = streamReader.ReadToEnd(); //读取文本中的所有字符 // String stringFromFileProcessedTemp = stringFromFile.Replace("charset=gb2312", "charset=utf-8");//尚无法实现.docx转.htm时utf-8编码 String stringFromFileProcessed = stringFromFile.Replace("</body>", "<!--右键菜单开始 --><div id='popupDiv' onclick='fnPopupClosePopup();' oncontextmenu='fnPopupContextMenu();' style='position:fixed;z-Index:1000;margin: 2px; border: 1px; overflow:visible; font-size: 11px; cursor: default;display:none;'><div style='position: relative;' onmouseover='fnPopupMouseOver();' onmouseout='fnPopupMouseOut();'><div title='刷新标题面' onclick='location.reload();'>刷新</div><div title='单击将在是否可以在线编辑课文的之间切换!' onclick='if(document.body.contentEditable==true) { document.body.contentEditable = false; } else { document.body.contentEditable = true;}'>课文编辑切换</div><div title='编辑后可保存编辑结果' onclick='fnSave();'>保存</div><div>帮助</div></div></div><!--右键菜单结束--><script id=sIdScriptAutoAddedForDynFunction1 src='../../../../common/script/content.js'></script><script id=sIdScriptAutoAddedForDynFunction2 src='../../../../common/script/Popup.js'></script><script id=sIdScriptAutoAddedForDynFunction3>document.body.onload=fnOnLoad;</script>" + "</body>"); streamReader.Close(); StreamWriter streamWriter = new StreamWriter(FolderPath + "\\" + Request.Query["FolderAndFileName"] + ".htm", false, Encoding.UTF8);//修改为了UTF8编码,可以运行。但还未检验。因为windows系统使用了utf8,需要在windows系统没有使用utf8的机器检验。 // streamWriter.Write(stringFromFileProcessed,,Encoding.UTF8);//出错。 streamWriter.Write(stringFromFileProcessed); streamWriter.Close(); return(Ok(new { count = files.Count, size, filePathAll, host = this.Request.Host.ToUriComponent() })); } else { return(Ok("这是服务器版(或者是本机版发布为了服务器版的方式运行),不允许直接上传!请在本机版制作好后(本机版无需登录),连接服务器版(课程资源管理员的账号登录连接服务器版),上传本机版中的资源到服务器版!" + this.Request.Host.ToUriComponent())); } }
public async Task <IActionResult> FileAdd(IFormFileCollection uploadFile, int?ChairIdd, int?FolderIdd) { try { if (uploadFile == null) { return(BadRequest()); } ViewBag.Host = HttpContext.Request.Host.ToString(); foreach (var file in uploadFile) { // путь к папке Files string path = "/Files/" + file.FileName; // сохраняем файл в папку Files в каталоге wwwroot using (var fileStream = new FileStream(_appEnvironment.WebRootPath + path, FileMode.Create)) { await file.CopyToAsync(fileStream); } path = "/Files/" + HttpUtility.UrlEncode(file.FileName); Models.File f = new Models.File { Path = path, ChairId = ChairIdd, FolderId = FolderIdd }; if (file.FileName.Contains(".doc") || file.FileName.Contains(".docx")) { f.TypeFile = TypeFile.Word; f.Name = file.FileName.Replace(".docx", "").Replace(".doc", ""); } else if (file.FileName.Contains(".ppt") || file.FileName.Contains(".pptx")) { f.TypeFile = TypeFile.PowerPoint; f.Name = file.FileName.Replace(".pptx", "").Replace(".ppt", ""); } else if (file.FileName.Contains(".xls") || file.FileName.Contains(".xlsx")) { f.TypeFile = TypeFile.Excel; f.Name = file.FileName.Replace(".xlsx", "").Replace(".xls", ""); } else if (file.FileName.Contains(".pdf")) { f.TypeFile = TypeFile.PDF; f.Name = file.FileName.Replace(".pdf", ""); } else if (file.FileName.Contains(".djvu")) { f.TypeFile = TypeFile.DJVU; f.Name = file.FileName.Replace(".djvu", ""); } else if (file.FileName.Contains(".jpg") || file.FileName.Contains(".png") || file.FileName.Contains(".jpeg")) { f.TypeFile = TypeFile.Image; f.Name = file.FileName.Replace(".jpg", "").Replace(".png", "").Replace(".jpeg", ""); } else { f.TypeFile = TypeFile.None; f.Name = file.FileName; } db.Files.Add(f); } db.SaveChanges(); if (ChairIdd != null) { return(View("ChairPartial", db.Chairs.Include(f => f.Folders).Include(fl => fl.Files).Include(c => c.Advertisements).Single(a => a.Id == ChairIdd))); } else { return(View("Folder", db.Folders.Include(f => f.Folders).Include(fl => fl.Files).Single(a => a.Id == FolderIdd))); } } catch (Exception e) { return(BadRequest("Помилка запиту (" + e.Message + ")")); } }
public IActionResult CommintFK(IFormCollection Files, string jsonArray, string registerCode, string fkcount) { JsonArray jsonObject = JsonConvert.DeserializeObject <JsonArray>(jsonArray); var resultCountModel = new RespResultCountViewModel(); Hashtable hash = new Hashtable(); string fileCode = "";//申诉主表编码 try { UserInfo userInfo = new UserInfo { UserId = User.GetCurrentUserId(), UserName = User.GetCurrentUserName(), InstitutionCode = User.GetCurrentUserOrganizeId(), InstitutionName = User.GetCurrentUserOrganizeName() }; //改ID为申诉主表的主键CheckComplainId if (!string.IsNullOrEmpty(fkcount) && fkcount == "1") { fileCode = _complaintMZService.Commint("2", jsonObject, registerCode, userInfo); } else if (!string.IsNullOrEmpty(fkcount) && fkcount == "2") { fileCode = _complaintMZService.Commint("22", jsonObject, registerCode, userInfo); } IFormFileCollection cols = Request.Form.Files; if (cols == null || cols.Count == 0) { return(Ok(new { code = -1, msg = "没有上传文件", data = hash })); } if (string.IsNullOrEmpty(fileCode)) { return(Ok(new { code = -4, msg = "请选择档案目录" })); } int i = 0; foreach (IFormFile file in cols) { i++; //定义文件数组后缀格式 string[] LimitFileType = { ".JPG", ".JPEG", ".PNG", ".GIF", ".PNG", ".BMP", ".DOC", ".DOCX", ".XLS", ".XLSX", ".TXT", ".PDF" }; string[] LimitFileType1 = { ".JPG", ".JPEG", ".PNG", ".GIF", ".PNG", ".BMP" }; string[] LimitFileType2 = { ".DOC", ".DOCX", ".XLS", ".XLSX", ".TXT", ".PDF" }; //获取文件后缀是否存在数组中 string currentPictureExtension = Path.GetExtension(file.FileName).ToUpper(); if (LimitFileType.Contains(currentPictureExtension)) { string filetype = string.Empty; //1图片、2文本 if (LimitFileType1.Contains(currentPictureExtension)) { filetype = "1"; } if (LimitFileType2.Contains(currentPictureExtension)) { filetype = "2"; } if (!string.IsNullOrEmpty(fkcount) && fkcount == "2") { var uppath = XYDbContext.UPLOADPATH + "医院二次反馈上传/" + fileCode + "/"; var lookpath = "/" + fileCode + "/"; var new_path = Path.Combine(uppath, file.FileName); var path = Path.Combine(Directory.GetCurrentDirectory(), new_path); if (!Directory.Exists(uppath)) { Directory.CreateDirectory(uppath); } using (var stream = new FileStream(path, FileMode.Create)) { byte[] fileByte = new byte[file.Length]; //用文件的长度来初始化一个字节数组存储临时的文件 Stream fileStream = file.OpenReadStream(); //建立文件流对象 string fileNameNew = Path.GetFileNameWithoutExtension(file.FileName); //int a = int.Parse(fileNameNew.Substring(fileNameNew.Length - 4, 4)); Check_ComplaintDetail_MZLEntity checkComplaintDetailEntity = new Check_ComplaintDetail_MZLEntity() { ComplaintDetailCode = ConstDefine.CreateGuid(), CheckComplainId = fileCode, ImageName = file.FileName, ImageSize = (int)(file.Length) / 1024, ImageUrl = "/医院二次反馈上传" + lookpath + file.FileName,//上线时需更改 CreateUserId = User.GetCurrentUserId(), CreateUserName = User.GetCurrentUserName(), CreateTime = DateTime.Now, Datatype = "2", //二次反馈 FilesType = filetype }; //文件保存到数据库里面去 bool flag = _afterCheckService.Add2(checkComplaintDetailEntity); if (flag) { //再把文件保存的文件夹中 file.CopyTo(stream); hash.Add("file", "/" + new_path); } } #region 第二次反馈时 删除第一次反馈上传文件 再重新创建 待用 //if (_afterCheckService.DeleteFiles(fileCode)) //{ // if (CommonHelper.DeleteDir(XYDbContext.UPLOADPATH + "医院反馈上传/" + fileCode)) // { // if (!Directory.Exists(uppath)) // { // Directory.CreateDirectory(uppath); // } // using (var stream = new FileStream(path, FileMode.Create)) // { // byte[] fileByte = new byte[file.Length];//用文件的长度来初始化一个字节数组存储临时的文件 // Stream fileStream = file.OpenReadStream();//建立文件流对象 // string fileNameNew = Path.GetFileNameWithoutExtension(file.FileName); // //int a = int.Parse(fileNameNew.Substring(fileNameNew.Length - 4, 4)); // CheckComplaintDetailEntity checkComplaintDetailEntity = new CheckComplaintDetailEntity() // { // ComplaintDetailCode = ConstDefine.CreateGuid(), // CheckComplainId = fileCode, // ImageName = file.FileName, // ImageSize = (int)(file.Length) / 1024, // ImageUrl = "/医院反馈上传" + lookpath + file.FileName,//上线时需更改 // CreateUserId = User.GetCurrentUserId(), // CreateUserName = User.GetCurrentUserName(), // CreateTime = DateTime.Now, // Datatype = "2", //二次反馈 // FilesType = filetype // }; // //文件保存到数据库里面去 // bool flag = _afterCheckService.Add(checkComplaintDetailEntity); // if (flag) // { // //再把文件保存的文件夹中 // file.CopyTo(stream); // hash.Add("file", "/" + new_path); // } // } // } // else // { // return Ok(new { code = -1, msg = "删除附件失败 请联系管理员!" }); // } //} //else //{ // return Ok(new { code = 1, msg = "原有附件已删除!" }); //} #endregion } else { var uppath = XYDbContext.UPLOADPATH + "医院初次反馈上传/" + fileCode + "/"; var lookpath = "/" + fileCode + "/"; var new_path = Path.Combine(uppath, file.FileName); var path = Path.Combine(Directory.GetCurrentDirectory(), new_path); if (!Directory.Exists(uppath)) { Directory.CreateDirectory(uppath); } using (var stream = new FileStream(path, FileMode.Create)) { byte[] fileByte = new byte[file.Length]; //用文件的长度来初始化一个字节数组存储临时的文件 Stream fileStream = file.OpenReadStream(); //建立文件流对象 string fileNameNew = Path.GetFileNameWithoutExtension(file.FileName); //int a = int.Parse(fileNameNew.Substring(fileNameNew.Length - 4, 4)); Check_ComplaintDetail_MZLEntity checkComplaintDetailEntity = new Check_ComplaintDetail_MZLEntity() { ComplaintDetailCode = ConstDefine.CreateGuid(), CheckComplainId = fileCode, ImageName = file.FileName, ImageSize = (int)(file.Length) / 1024, ImageUrl = "/医院初次反馈上传" + lookpath + file.FileName,//上线时需更改 CreateUserId = User.GetCurrentUserId(), CreateUserName = User.GetCurrentUserName(), CreateTime = DateTime.Now, Datatype = "1", //医院初次反馈 FilesType = filetype }; //文件保存到数据库里面去 bool flag = _afterCheckService.Add2(checkComplaintDetailEntity); if (flag) { //再把文件保存的文件夹中 file.CopyTo(stream); hash.Add("file", "/" + new_path); } } } } else { return(Ok(new { status = -2, message = "请上传指定格式的图片", data = hash })); } } return(Ok(new { status = 0, message = "上传成功", data = hash })); } catch (Exception ex) { return(Ok(new { status = -3, message = "上传失败", data = ex.Message })); } }
public object UploadPortrait(IFormFileCollection portraits) { if (portraits.Count == 0) { return CustomJsonResult.Instance.GetError("请选择需要上传的文件"); } var fileName = ""; foreach (var file in portraits) { fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"'); var supportedTypes = new[] {"jpg", "jpeg", "png", "gif", "bmp"}; var fileExt = Path.GetExtension(fileName).Substring(1); if (!supportedTypes.Contains(fileExt)) { return CustomJsonResult.Instance.GetError("file type error"); } if (file.Length > 1024*1000*10) { return CustomJsonResult.Instance.GetError("file size error"); } var r = new Random(); fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + r.Next(10000) + "." + fileExt; var filePath = Path.Combine(GlobalVariables.FilePath, fileName); file.SaveAs(filePath); } return CustomJsonResult.Instance.GetSuccess(GlobalVariables.FileServer + fileName); }
public override ValidationResult Validate(IFormFileCollection formFileCollection) { return(formFileCollection.Single().ContentType != "text/csv" ? ValidationResultFactory.CreateValidationResultError(ErrorMessages.ContentTypeInvalid) : base.Validate(formFileCollection)); }
public async Task <IActionResult> AccountValidation(IFormFileCollection files, ClientUpdateViewModel viewmodel) { var model = new ClientUpdateTemp(); var _user = new AuthenticateResponse { MembershipKey = 1006979, //1007435, EmailAddress = "*****@*****.**", //"*****@*****.**", FirstName = "Tolulope", LastName = "Olusakin", FullName = "Olusakin Tolulope S"//"Funmilayo Ruth Adeyemi", }; try { if (files != null) { int index = 0; foreach (var file in files) { if (file.Length > 0) { var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"'); byte[] fileBytes = null; using (var fileStream = file.OpenReadStream()) using (var ms = new MemoryStream()) { fileStream.CopyTo(ms); fileBytes = ms.ToArray(); } if (index == 0) { model.Passport = fileBytes; } else if (index == 1) { model.Signature = fileBytes; } else if (index == 2) { model.Thumbprint = fileBytes; } else if (index == 3) { model.ValidID = fileBytes; } index++; } } model.MembershipNumber = _user.MembershipKey; model.EvaluationStatus = ""; model.ProgressStatus = "Pending"; model.TaxNumber = viewmodel.TaxNumber; model.Jurisdiction = viewmodel.Jurisdiction; model.IsKYCApproved = false; model.IsPassportApproved = false; model.IsSignatureApproved = false; model.IsThumbprintApproved = false; model.IsValidIdApproved = false; model.DateUpdated = DateTime.Now; //check if client already has a record in the table var clientquery = db.ClientUpdateTemps.Where(s => s.MembershipNumber.Equals(_user.MembershipKey)).FirstOrDefault(); if (clientquery != null) { db.ClientUpdateTemps.Update(model); await db.SaveChangesAsync(); var msg = "Success: your details have been updated!"; viewmodel.SuccessMessage = msg; //TempData["message"] = ViewBag.Message = msg; TempData["message"] = true; //return RedirectToAction("ClientUpdate", "SelfService", viewmodel.SuccessMessage); return(AccountValidation(viewmodel)); } else { db.ClientUpdateTemps.Add(model); await db.SaveChangesAsync(); var msg = "Success: your details have been updated!"; viewmodel.SuccessMessage = msg; TempData["message"] = true; //return RedirectToAction("ClientUpdate", "SelfService", viewmodel); return(AccountValidation(viewmodel)); } } } catch (Exception ex) { viewmodel.ErrorMessage = ex.Message; TempData["message"] = false; Utilities.ProcessError(ex, _contentRootPath); _logger.LogError(null, ex, ex.Message); } return(View()); }
public IActionResult Post(int id, IFormFileCollection _files) { try { var files = Request.Form.Files[0]; var fileExtension = Path.GetExtension(files.FileName); string fileFilt = ".mp4"; if (fileExtension == null) { return(Json(new { state = "-1", msg = "上传的文件没有后缀!" })); } if (fileFilt.IndexOf(fileExtension.ToLower(), StringComparison.Ordinal) <= -1) { return(Json(new { state = "-1", msg = "上传的文件不是视频格式!" })); } long size = files.Length; var now = DateTime.Now; var filePathExt = now.ToString("yyyyMMdd"); if (size > 20971420) { return(Json(new { state = "-1", msg = "文件大小不应超过20M!" })); } var fileName = ContentDispositionHeaderValue.Parse(files.ContentDisposition).FileName.Trim('"'); string filePath = $@"E:\corewebapi\Upload\Video\"; if (!Directory.Exists(filePath + filePathExt)) { Directory.CreateDirectory(filePath + filePathExt); } fileName = Guid.NewGuid() + "." + fileName.Split('.')[1]; string fileFullName = filePath + filePathExt + @"\" + fileName; using (FileStream fs = System.IO.File.Create(fileFullName)) { files.CopyTo(fs); fs.Flush(); } string message = $"上传成功!"; EventVideoTable _video = new EventVideoTable { EventTableId = id, VideoPath = $@"\Upload\Video\{filePathExt}\{fileName}" }; if (_repository.Save(_video)) { return(Json(new { path = $@"\Upload\Video\{filePathExt}\{fileName}", state = "0", msg = message })); } else { return(Json(new { state = "-1", msg = "上传失败!" })); } } catch (Exception ex) { return(Json(new { state = "-1", msg = "上传失败!" })); } }
public static async Task AddGroups(IFormFileCollection excelFiles, string rootPath, UniAPI _api) { SaveOnServer(excelFiles, rootPath); foreach (var file in excelFiles) { var package = new ExcelPackage(new FileInfo($"{ rootPath }\\{ file.FileName }")); var sheets = package.Workbook.Worksheets; foreach (var sheet in sheets) { for (int i = 1; i < sheet.Dimension.Rows + 1; i++) { var groupName = sheet.Cells[i, 1].Value.ToString(); var disciplinesString = sheet.Cells[i, 2].Value.ToString().Split(","); var disciplines = new List <Discipline>(); // Add disciplines to db if they don't exist // If exist, add to disciplines list foreach (var discipline in disciplinesString) { var dip = await _api.Post <Discipline, Discipline>($"Disciplines/Get", new Discipline(discipline)); if (!(dip.Result is EmptyResult)) { disciplines.Add(dip.Value); } else { var addingResponse = await _api.Post <Discipline, Discipline>("Disciplines/Add", new Discipline(discipline)); if (addingResponse.Value != null && addingResponse.Value.Id != 0) { disciplines.Add(addingResponse.Value); } } } // Find group in db. If not found, add var groupResponse = await _api.Post <Group, Group>("Groups/Get", new Group(groupName)); Group group = null; if (groupResponse.Result is EmptyResult) { var groupAdded = await _api.Post <Group, Group>("Groups/Add", new Group(groupName)); if (!(groupAdded.Result is EmptyResult)) { group = groupAdded.Value; } } else { group = groupResponse.Value; } // Add relationship many-to-many foreach (var discipline in disciplines) { try { var groupDisciplines = new GroupsDisciplines(group, discipline); await _api.Post <GroupsDisciplines, GroupsDisciplines>("GroupsDisciplines", groupDisciplines); } catch (Exception) { throw; } } } } File.Delete(rootPath + file.FileName); } }
public JsonResponse<string> UploadImages(IFormFileCollection Files, int user_id, int candidate_id, Boolean isProfile) { CandidateImageLogger candidateImageLogger = new CandidateImageLogger(); JsonResponse<string> jsonResponse = new JsonResponse<string>(); string folderName; DirectoryInfo di; List<string> image_names = new List<string>(); try { using (IDbConnection dbConnection = new NpgsqlConnection(_ConnectionStringService.Value)) { dbConnection.Open(); using (var transaction = dbConnection.BeginTransaction()) { if (Files.Count > 0) { if (isProfile == true) { folderName = Path.Combine("Resources", "Images", "User", user_id.ToString(), "Candidates", candidate_id.ToString(), "Profile Image"); image_names = dbConnection.Query<string>("select image_name from candidate_image_logger where user_id = @p0 and candidate_id = @p1 and is_approved = false and is_profile_pic = true ", new { p0 = user_id, @p1 = candidate_id }).ToList(); dbConnection.Query<CandidateImageLogger>("update candidate_image_logger set is_deleted = true where user_id = @p0 and candidate_id = @p1 and is_approved = false and is_profile_pic = true ", new { p0 = user_id, @p1 = candidate_id }); } else { folderName = Path.Combine("Resources", "Images", "User", user_id.ToString(), "Candidates", candidate_id.ToString(), "Other Images"); } var pathToSave = Path.Combine(Directory.GetCurrentDirectory(), folderName); if (!Directory.Exists(pathToSave)) { di = Directory.CreateDirectory(pathToSave); } else { di = new DirectoryInfo(pathToSave); if (isProfile && image_names != null && image_names.Count > 0) { foreach (string image_name in image_names) { foreach (var fi in di.GetFiles()) { if (fi.Name == image_name) { fi.Delete(); break; } } } } } for (int i = 0; i < Files.Count; i++) { var file = Files[i]; 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); } candidateImageLogger.user_id = user_id; candidateImageLogger.candidate_id = candidate_id; candidateImageLogger.image_name = file.FileName; candidateImageLogger.image_path = dbPath; candidateImageLogger.content_type = file.ContentType; candidateImageLogger.image_upload_time = DateTime.Now; candidateImageLogger.is_approved = false; candidateImageLogger.is_deleted = false; if (isProfile) { candidateImageLogger.is_profile_pic = true; candidateImageLogger.is_from_other_three_photos = false; } else { candidateImageLogger.is_from_other_three_photos = true; candidateImageLogger.is_profile_pic = false; } dbConnection.Insert<CandidateImageLogger>(candidateImageLogger, transaction); } } } transaction.Commit(); jsonResponse.Data = "Profile images uploaded successfully"; jsonResponse.IsSuccess = true; jsonResponse.Message = "Success"; } } return jsonResponse; } catch (System.Exception ex) { jsonResponse.Data = "Profile images upload fail"; jsonResponse.IsSuccess = false; jsonResponse.Message = "fail"; return jsonResponse; } }
public static async Task AddTeachers(IFormFileCollection excelFiles, string rootPath, UniAPI _api) { SaveOnServer(excelFiles, rootPath); foreach (var file in excelFiles) { var package = new ExcelPackage(new FileInfo($"{ rootPath }\\{ file.FileName }")); var sheets = package.Workbook.Worksheets; foreach (var sheet in sheets) { for (int i = 1; i < sheet.Dimension.Rows + 1; i++) { var fullName = sheet.Cells[i, 1].Value.ToString().Split(" "); var lastName = fullName[0]; var firstName = fullName[1]; var middleName = fullName[2]; var password = sheet.Cells[i, 2].Value.ToString(); var disciplinesString = sheet.Cells[i, 3].Value.ToString().Split(","); var disciplines = new List <Discipline>(); // Add disciplines to db if they don't exist // If exist, add to disciplines list foreach (var discipline in disciplinesString) { var dip = await _api.Post <Discipline, Discipline>($"Disciplines/Get", new Discipline(discipline)); if (!(dip.Result is EmptyResult)) { disciplines.Add(dip.Value); } else { var addingResponse = await _api.Post <Discipline, Discipline>("Disciplines/Add", new Discipline(discipline)); if (addingResponse.Value != null && addingResponse.Value.Id != 0) { disciplines.Add(addingResponse.Value); } } } // Find teacher. If not found, add var teacher = new TeacherCred(firstName, lastName, middleName, password, new List <TeachersDisciplines>(), new List <Grade>()); var teacherResponse = await _api.Post <Teacher, Teacher>("Teachers/Get", teacher); TeacherCred teacherdb = null; if (teacherResponse.Result is EmptyResult) { var teacherAdding = await _api.Post <Teacher, Teacher>("Teachers/Add", teacher); if (!(teacherAdding.Result is EmptyResult)) { var teacherAdded = teacherAdding.Value; teacherdb = new TeacherCred { Id = teacherAdded.Id, FirstName = teacherAdded.FirstName, LastName = teacherAdded.LastName, MiddleName = teacherAdded.MiddleName, Role = teacherAdded.Role }; } else { continue; } } else { var teacherFind = teacherResponse.Value; teacherdb = new TeacherCred { FirstName = teacherFind.FirstName, LastName = teacherFind.LastName, MiddleName = teacherFind.MiddleName, Id = teacherFind.Id }; } var teacherDiscip = new List <TeachersDisciplines>(); foreach (var discipline in disciplines) { try { var td = new TeachersDisciplines(teacherdb, discipline); await _api.Post <TeachersDisciplines, TeachersDisciplines>("TeachersDisciplines", td); } catch (Exception) { } } } } File.Delete(rootPath + file.FileName); } }
public async Task <IActionResult> AddObject(AddHomeViewModel mode, IFormFileCollection files) { Home home = new Home { About = mode.About, Adress = mode.Adress, TypeSdelki = mode.TypeSdelki, Coords = mode.Coords, AllCountRoom = mode.AllCountRoom, AllPloshadRoom = mode.AllPloshadRoom, Animals = mode.Animals, Balkon = mode.Balkon, Children = mode.Children, Communal = mode.Communal, Comnat = mode.Comnat, Etag = mode.Etag, EtagAll = mode.EtagAll, Kuxnya = mode.Kuxnya, ObjectText = mode.ObjectText, Name = mode.Name, Price = mode.Price, PloshadRoom = mode.PloshadRoom, Predoplata = mode.Predoplata, Sostav = mode.Sostav, Parkovka = mode.Parkovka, Remont = mode.Remont, SanUzelRazdel = mode.SanUzelRazdel, SanUzelVmeste = mode.SanUzelVmeste, TypeArenda = mode.TypeArenda, TypeCommerce = mode.TypeCommerce, Zalog = mode.Zalog }; var result = await _context.AddAsync(home); if (mode.Dop != null) { foreach (string text in mode.Dop) { await _context.AddAsync(new Dop { HomeId = result.Entity.Id, Text = text }); } } if (files.Count() != 0) { foreach (var uploadedFile in files) { Photos photos = new Photos(); using (var memoryStream = new MemoryStream()) { await uploadedFile.CopyToAsync(memoryStream); photos.Photo = memoryStream.ToArray(); } photos.HomeId = result.Entity.Id; await _context.AddAsync(photos); } } await _context.AddAsync(home); await _context.SaveChangesAsync(); return(RedirectToAction("Panel", "Admin")); }
public async Task <bool> UploadFiles(Guid applicationId, int?sequenceNumber, int?sectionNumber, string pageId, IFormFileCollection files, ContainerType containerType, CancellationToken cancellationToken) { var success = false; if (!string.IsNullOrWhiteSpace(pageId) && files != null) { var container = await BlobContainerHelpers.GetContainer(_fileStorageConfig, containerType); if (container != null) { var pageDirectory = container.GetDirectory(applicationId, sequenceNumber, sectionNumber, pageId); success = await pageDirectory.UploadFiles(files, _logger, cancellationToken); } } return(success); }