public HttpResponseMessage UploadFile(int fileTypeId) { List <FileBase> data = null; for (int i = 0; i < HttpContext.Current.Request.Files.Count; i++) { string userId = UserService.GetCurrentUserId(); HttpPostedFile file = HttpContext.Current.Request.Files[i]; if (file.ContentLength > 0) { if (data == null) { data = new List <FileBase>(); } var path = _fileService.UploadToCloud(file); var fileId = _fileService.Add(path, fileTypeId); data.Add(new FileBase { FileId = fileId, Path = "https://sabio-training.s3-us-west-2.amazonaws.com/C11/" + path, FileTypeId = fileTypeId }); } } ItemsResponse <FileBase> response = new ItemsResponse <FileBase>(); response.Items = data; return(Request.CreateResponse(response)); }
public IResult Add(CarImage carImage, IFormFile file) { IResult result = BusinessRules.Run( CheckIfImageLimitExceded(carImage.CarID) ); if (result != null) { return(result); } carImage.ImagePath = _fileService.Add(uploadPath, file).Data; carImage.Date = DateTime.Now; _carImageDal.Add(carImage); return(new SuccessResult(Messages.CarImageAdded)); }
public async Task <IActionResult> Upload(FileUploadVM model) { if (ModelState.IsValid) { string filePath = null; string fileName = null; if (model.CsvFile != null) { string uploadsFolder = Path.Combine(_hostingEnvironment.WebRootPath, "data"); fileName = model.CsvFile.FileName; filePath = Path.Combine(uploadsFolder, model.CsvFile.FileName); using (Stream fileStream = new FileStream(filePath, FileMode.Create)) { await model.CsvFile.CopyToAsync(fileStream); } } CSVFile csvFile = new CSVFile { FilePath = filePath, FileName = fileName }; _fileService.Add(csvFile); return(RedirectToAction("details", new { Id = csvFile.Id })); } return(View()); }
public ActionResult <ItemResponse <int> > Add(List <FileAddRequest> modelList) { ObjectResult result = null; int userId = _authService.GetCurrentUserId(); try { List <int> id = _service.Add(modelList, userId); ItemsResponse <int> response = new ItemsResponse <int>() { Items = id }; result = StatusCode(201, response); } catch (Exception ex) { Logger.LogError(ex.ToString()); ErrorResponse response = new ErrorResponse(ex.Message); result = StatusCode(500, response); } return(result); }
public async Task <IHttpActionResult> Post() { IHttpActionResult res = BadRequest(); if (!Request.Content.IsMimeMultipartContent()) { return(res); } var serviceRes = await _fileService.Add(new FileAddRequest() { RequestOwner = User, File = Request.Content }); if (serviceRes.Access == ResponseAccess.Granted) { res = Ok(serviceRes.Model); } if (serviceRes.Access == ResponseAccess.Deny) { res = Unauthorized(serviceRes.Message); } return(res); }
public async Task <FileResponse> Add(FileAddRequest request) { var res = await _fileService.Add(request); if (res.Access == ResponseAccess.Granted) { _observers.ForEach(x => x.FileAdded(res, request)); await _unitOfWork.SaveChangesAsync(); } return(res); }
private static void files() { file = new FileManager(new EfFileDal()); file.Add(new File { Path = "c:\\abc.txt" }); var lst = file.GetAll(); foreach (var item in lst) { Console.WriteLine(item.Path); } }
public ActionResult <ItemResponse <int> > Add(FileAddRequest model) { try { int id = _fileService.Add(model, _authService.GetCurrentUserId()); ItemResponse <int> resp = new ItemResponse <int>(); resp.Item = id; return(Created201(resp)); } catch (Exception ex) { Logger.LogError(ex.ToString()); return(StatusCode(500, new ErrorResponse(ex.Message))); } }
public async Task <JsonResult> AddFile(IEnumerable <IFormFile> file, int Id) { string error = ""; try { foreach (var item in file) { string filename = item.FileName; int index = filename.LastIndexOf("\\"); filename = filename.Substring(index + 1, filename.Length - index - 1); var folder = CreateOrUpdateFolder(Id, fileHelper.FilePath); var filePath = Path.Combine(folder, "FTS", filename); if (UserIdentityInfo.Roles.Contains(Roles.Customer)) { filePath = Path.Combine(folder, "MUSTERI", filename); } using (var stream = new FileStream(filePath, FileMode.Create)) { await item.CopyToAsync(stream); } Entities.Concrete.File fileBox = new Entities.Concrete.File(); fileBox.DataSheetId = Id; fileBox.FileName = filename; fileBox.FilePath = filePath; fileBox.ContentType = item.ContentType; fileBox.Uploader = "MUSTERI"; fileBox.CreateDate = DateTime.Now; fileBox.CreateUser = Convert.ToInt32(UserIdentityInfo.Id); _fileService.Add(fileBox); if (UserIdentityInfo.Roles.Contains(Roles.FTSUser)) { var datasheet = _dataSheetService.GetById(Id); datasheet.FTSUserId = Convert.ToInt32(UserIdentityInfo.Id); _dataSheetService.Update(datasheet); } } } catch (Exception ex) { error = ex.Message; } return(Json(error)); }
public async Task <IResultModel> Upload([FromForm] Application.FileService.ViewModels.FileUploadModel model, IFormFile formFile) { var config = _configProvider.Get <PathConfig>(); var module = _moduleCollection.FirstOrDefault(m => m.Code.EqualsIgnoreCase(model.ModuleCode)); if (module == null) { return(ResultModel.Success("指定模块不存在")); } //使用模块编码,防止大小写问题 model.ModuleCode = module.Code; var uploadModel = new FileUploadModel { Request = Request, FormFile = formFile, RootPath = config.UploadPath, Module = "Admin", Group = Path.Combine("OSS", model.AccessMode == FileAccessMode.Open ? "Open" : "Private"), SubPath = Path.Combine(model.ModuleCode.ToLower(), model.Group.ToLower()) }; var result = await _fileUploadHelper.Upload(uploadModel); if (!result.Successful) { return(result); } //文件本地物理路径 model.PhysicalPath = Path.Combine(config.UploadPath, result.Data.FullPath); //文件的OSS相对路径 result.Data.Path = Path.Combine(result.Data.Path.Split(Path.DirectorySeparatorChar).Skip(3).ToArray()); return(await _service.Add(model, result.Data)); }
public async Task <string> Add(DataImage base64Image) { if (base64Image.RawData.Length > _configuration.MaxSizeByte) { throw new ClientException("too-big-image"); } else if (base64Image == null) { throw new ClientException("inc-photo-type", base64Image.ToString()); } string Id = null; MemoryStream ms = new MemoryStream(); try { new ImageProcessor.ImageFactory() .Load(base64Image.RawData) .Constrain(_configuration.MaxSize) .Format(_configuration.Format) .Save(ms); Id = await _fileService.Add(Convert.ToBase64String(ms.ToArray())); await _imageGR.CreateAsync(new Image { FileId = Id, Type = _configuration.Format.MimeType }); } catch (Exception) { if (Id != null) { await _fileService.Remove(Id); } throw new ClientException("image-load-err"); } finally { ms.Close(); } return(Id); }
public async Task <HttpResponseMessage> UploadFile() { if (!Request.Content.IsMimeMultipartContent()) { Request.CreateResponse(HttpStatusCode.UnsupportedMediaType); } var provider = GetMultipartMemoryStreamProvider(); var tt = await Request.Content.ReadAsMultipartAsync(provider).ContinueWith(p => { var result = p.Result; // var myParameter = result.FormData.GetValues("myParameter").FirstOrDefault(); var file = _fileService.Create(); foreach (var stream in result.Contents.Where((content, idx) => result.IsStream(idx))) { string fileName = GetFileInfo.GetDeserializedFileName(stream); var contentType = GetFileInfo.GetContentType(stream); if (_fileService.IsValidType(fileName) && _fileService.IsValidContent(contentType.MediaType)) { file.FileBinary = stream.ReadAsByteArrayAsync().Result; file.Size = stream.Headers.ContentLength; file.IsDeleted = false; file.Extention = contentType.MediaType; file.Guid = Guid.NewGuid(); file.Name = fileName; file.UploadDate = DateTime.UtcNow; // var file = new this.GetFormData<string >(stream.Headers.ContentDisposition.FileName); // var contentTest = stream.ReadAsByteArrayAsync(); // ... and so on, as per your original code. _fileService.Add(file); _unitOfWork.SaveChanges(); } } return(file); }); /*var result = await Request.Content.ReadAsMultipartAsync(provider); * * * // On upload, files are given a generic name like "BodyPart_26d6abe1-3ae1-416a-9429-b35f15e6e5d5" * // so this is how you can get the original file name * * var originalFileName = GetDeserializedFileName(result.FileData.First()); * * // uploadedFileInfo object will give you some additional stuff like file length, * // creation time, directory name, a few filesystem methods etc.. * * var uploadedFileInfo = new FileInfo(result.FileData.First().LocalFileName); * * // Remove this line as well as GetFormData method if you're not * // sending any form data with your upload request * * var fileUploadObj = GetFormData<UploadDataModel>(result); * * // Through the request response you can return an object to the Angular controller * // You will be able to access this in the .success callback through its data attribute * // If you want to send something to the .error callback, use the HttpStatusCode.BadRequest instead * * var returnData = "ReturnTest"; * * */ return(this.Request.CreateResponse(HttpStatusCode.OK, new { id = tt.Id })); }
public File AddFile(File file) { return(_serviceFile.Add(file)); }
public async Task <IHttpActionResult> Upload(Guid refId, string screenCode) { #region Condition /// Checks whether the parameters are null. if (refId == null || screenCode == null) { return(BadRequest(Messages.FUE0002)); } /// Controls whether the screen code is in the <see cref="ScreenCodes"/> class. if (!typeof(ScreenCodes).GetFields().Any(x => x.Name == screenCode)) { return(BadRequest(Messages.GNW0002)); } /// Checks the media type for the file-s to be uploaded. if (!Request.Content.IsMimeMultipartContent()) { return(Content(HttpStatusCode.UnsupportedMediaType, Messages.FUW0001)); } #endregion /// `localPath` and `useCloud` is get from Web.Config. string localPath = HostingEnvironment.MapPath(ConfigurationManager.AppSettings["fileServiceLocalPath"]); bool useCloud = Convert.ToBoolean(ConfigurationManager.AppSettings["useCloud"]); var provider = new MultipartFormDataStreamProvider(localPath); try { /// Loads the files into the local storage. await Request.Content.ReadAsMultipartAsync(provider); /// Check is exist valid file. if (provider.FileData.Count == 0) { return(BadRequest(Messages.FUE0001)); } IList <FileDto> modelList = new List <FileDto>(); foreach (MultipartFileData file in provider.FileData) { string originalName = file.Headers.ContentDisposition.FileName; if (originalName.StartsWith("\"") && originalName.EndsWith("\"")) { originalName = originalName.Trim('"'); } if (originalName.Contains(@"/") || originalName.Contains(@"\")) { originalName = Path.GetFileName(originalName); } FileDto fileDto = new FileDto { RefId = refId, ScreenCode = screenCode, OriginalName = Path.GetFileNameWithoutExtension(originalName), StorageName = Path.GetFileName(file.LocalFileName), Extension = Path.GetExtension(originalName).ToLower(), Size = new FileInfo(file.LocalFileName).Length }; modelList.Add(fileDto); } if (useCloud) { await fileService.SendCloud(modelList, localPath); } await fileService.Add(modelList, IdentityClaimsValues.UserId <Guid>()); return(Ok(Messages.Ok)); } catch (Exception exMessage) { return(Content(HttpStatusCode.InternalServerError, exMessage)); } }
public async Task <HttpResponseMessage> Import() { if (!Request.Content.IsMimeMultipartContent()) { return(Request.CreateErrorResponse(HttpStatusCode.UnsupportedMediaType, "Định dạng không được server hỗ trợ")); } var root = HttpContext.Current.Server.MapPath("~/UploadedFiles/FilePdf"); if (!Directory.Exists(root)) { Directory.CreateDirectory(root); } var provider = new MultipartFormDataStreamProvider(root); var result = await Request.Content.ReadAsMultipartAsync(provider); //Byte[] test = File.ReadAllBytes(provider.FileData[0].LocalFileName); bool status = Boolean.Parse(result.FormData["status"].ToString().Trim('"')); var dt = result.FormData["timeStarted"].ToString().Trim('"'); DateTime timeStarted = Convert.ToDateTime(dt); string folder = result.FormData["folders"].ToString().Trim('"'); string cateId = result.FormData["categoryId"].ToString().Trim('"'); string createdBy = result.FormData["createdBy"].ToString().Trim('"'); var folderRoot = HttpContext.Current.Server.MapPath("~/UploadedFiles/FilePdf/" + folder + "-" + cateId); if (!Directory.Exists(folderRoot)) { Directory.CreateDirectory(folderRoot); } foreach (MultipartFileData fileData in result.FileData) { if (fileData.Headers.ContentType.MediaType != "application/pdf" || string.IsNullOrEmpty(fileData.Headers.ContentDisposition.FileName)) { System.IO.File.Delete(fileData.LocalFileName); return(Request.CreateResponse(HttpStatusCode.NotAcceptable, "Yêu cầu không đúng định dạng")); } string fileName = fileData.Headers.ContentDisposition.FileName; if (fileName.StartsWith("\"") && fileName.EndsWith("\"")) { fileName = fileName.Trim('"'); } if (fileName.Contains(@"/") || fileName.Contains(@"\")) { fileName = Path.GetFileName(fileName); } var fullPath = Path.Combine(folderRoot, fileName); if (System.IO.File.Exists(fullPath)) { System.IO.File.Delete(fileData.LocalFileName); return(Request.CreateResponse(HttpStatusCode.NotAcceptable, "Tên file đã có trong hệ thống.")); } else { await Task.Run(() => _fileService.Add(new Model.Models.File { Name = fileName, Alias = StringHelper.ToUnsignString(fileName), NewCategoryID = int.Parse(cateId), CreatedDate = DateTime.Now, CreatedBy = createdBy, Status = status, TimeStarted = timeStarted, Path = CommonConstants.FileUpload + folder + "-" + cateId + "/" + fileName }) ).ContinueWith((finishedTask) => { _fileService.Save(); }); await Task.Run(() => System.IO.File.Copy(fileData.LocalFileName, fullPath, false) ).ContinueWith((finishedTask) => { System.IO.File.Delete(fileData.LocalFileName); }); //System.IO.File.Copy(fileData.LocalFileName, fullPath, false); //System.IO.File.Delete(fileData.LocalFileName); //_fileService.Add(new Model.Models.File //{ // Name = fileName, // Alias = StringHelper.ToUnsignString(fileName), // NewCategoryID = int.Parse(cateId), // CreatedDate = DateTime.Now, // Status = status, // TimeStarted = timeStarted, // Path = CommonConstants.FileUpload + folder + "-" + cateId + "/" + fileName //}); //_fileService.Save(); //MimeMapping.GetMimeMapping(filename) } } return(Request.CreateResponse(HttpStatusCode.OK, "Upload thành công.")); }