public void Setup() { _session.Transact(session => { var defaultMediaCategory = new MediaCategory { Name = "Default", UrlSegment = "default", }; session.Save(defaultMediaCategory); var mediaSettings = _configurationProvider.GetSiteSettings <MediaSettings>(); _configurationProvider.SaveSettings(mediaSettings); string logoPath = HttpContext.Current.Server.MapPath("/Apps/Core/Content/images/mrcms-logo.png"); var fileStream = new FileStream(logoPath, FileMode.Open); MediaFile dbFile = _fileService.AddFile(fileStream, Path.GetFileName(logoPath), "image/png", fileStream.Length, defaultMediaCategory); string logoPath1 = HttpContext.Current.Server.MapPath("/Apps/Core/Content/Images/mrcms-hat.gif"); var fileStream1 = new FileStream(logoPath1, FileMode.Open); MediaFile dbFile1 = _fileService.AddFile(fileStream1, Path.GetFileName(logoPath1), "image/gif", fileStream1.Length, defaultMediaCategory); }); }
public string ImportPictures(NopCommerceDataReader dataReader, NopImportContext nopImportContext) { var pictureData = dataReader.GetPictureData(); var mediaCategory = _documentService.GetDocumentByUrl <MediaCategory>(NopProductImages); if (mediaCategory == null) { mediaCategory = new MediaCategory { Name = "Nop Product Images", UrlSegment = NopProductImages, IsGallery = false, HideInAdminNav = false }; _documentService.AddDocument(mediaCategory); } foreach (var data in pictureData) { using (var fileData = data.GetData()) { var memoryStream = new MemoryStream(); fileData.CopyTo(memoryStream); memoryStream.Position = 0; var mediaFile = _fileService.AddFile(memoryStream, data.FileName, data.ContentType, memoryStream.Length, mediaCategory); nopImportContext.AddEntry(data.Id, mediaFile); } } return(string.Format("{0} pictures imported", pictureData.Count)); }
//async: In an asynchronous process, the application can continue with other work that doesn't depend on the web resource until the potentially blocking task finishes. public async Task <HttpResponseMessage> AddFile(string directory) { //kytodo fix userid //string userId = GetUserID(); string userId = ""; HttpContent content = Request.Content; string model = ""; List <Tag> tags = new List <Tag>(); // Check if the request contains multipart/form-data. if (!Request.Content.IsMimeMultipartContent()) { throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); } InMemoryMultipartStreamProviderService provider = await content.ReadAsMultipartAsync(new InMemoryMultipartStreamProviderService()); if (provider.FormData["base64Image"] == null) { throw new HttpResponseException(HttpStatusCode.BadRequest); } ItemResponse <bool> response = new ItemResponse <bool>(); response.Item = await _fileService.AddFile(provider, directory, userId); return(Request.CreateResponse(response)); }
/// <summary> /// Add image to Product Gallery /// </summary> /// <param name="fileLocation"></param> /// <param name="mediaCategory"></param> public bool ImportImageToGallery(string fileLocation, MediaCategory mediaCategory) { // rather than using webclient, this has been refactored to use HttpWebRequest/Response // so that we can get the content type from the response, rather than assuming it try { var httpWebRequest = HttpWebRequest.Create(fileLocation) as HttpWebRequest; var httpWebResponse = httpWebRequest.GetResponse() as HttpWebResponse; using (var responseStream = httpWebResponse.GetResponseStream()) { var memoryStream = new MemoryStream(); responseStream.CopyTo(memoryStream); memoryStream.Position = 0; var fileName = Path.GetFileName(fileLocation); _fileService.AddFile(memoryStream, fileName, httpWebResponse.ContentType, (int)memoryStream.Length, mediaCategory); } return(true); } catch (Exception) { return(false); } }
public IActionResult AddFile(IFormFile csvfile) { var bytearray = _fileService.AddFile(csvfile); _jobDataService.AddJobData(bytearray); return(RedirectToAction("Index", "Home")); }
public ViewDataUploadFilesResult AddFile(Stream stream, string fileName, string contentType, long contentLength, MediaCategory mediaCategory) { MediaFile mediaFile = _fileService.AddFile(stream, fileName, contentType, contentLength, mediaCategory); return(mediaFile.GetUploadFilesResult()); }
private string SaveFile(Webpage webpage, FormPosting formPosting, HttpPostedFileBase file) { var mediaCategory = _documentService.GetDocumentByUrl <MediaCategory>("file-uploads") ?? CreateFileUploadMediaCategory(); var result = _fileService.AddFile(file.InputStream, webpage.Id + "-" + formPosting.Id + "-" + file.FileName, file.ContentType, file.ContentLength, mediaCategory); return(result.FileUrl); }
/// <summary> /// First auxiliary method of the SearchEmployees method /// </summary> /// <param name="file"> /// File to be searched and added to the sql database /// </param> /// <param name="filePath"> /// File path where the file is located /// </param> /// <param name="text"> /// Text of the file /// </param> /// <returns> /// Dictionary with the results found /// </returns> private Dictionary <string, int> SearchEmployeesAux1(D.Models.File file, string filePath, string text) { text = text.Replace(Environment.NewLine, " "); File.Delete(filePath); _fileService.AddFile(file); var doc = NLPAnalysis(text).Result; return(SearchEmployeesAux2(doc)); }
public async Task <IActionResult> UploadFile(IFormFile file) { if (file.Length > 0) { return(Ok(new FileViewModel { FileName = await _fileService.AddFile(file) })); } return(BadRequest(file)); }
public void AddNewFile(string filename) { _fileService.AddFile( new FileEntity { FileName = filename, FileUploadDate = DateTime.Now, Status = "Pending" } ); }
public async Task <ActionResult <string> > AddFile([FromForm] FileUploaded File, CancellationToken Cancel) { try { return(Ok(await FileService.AddFile(File, Environment.WebRootPath, Cancel))); } catch { return(BadRequest()); } }
public FileMessageModel SendFileMessage(User sender, uint chatId, IFormFile uploadedFile) { var chat = _repository.GetChat(chatId); ValidateUserInChat(chat, sender.Name); var fileInfo = _fileService.AddFile(uploadedFile); var message = new FileMessage { Date = DateTime.UtcNow, FromUser = sender, File = fileInfo }; _repository.AddMessage(chat, message); _updatesService.NotifyAddMessage(message, chat); return(FileMessageToModel(message)); }
public async Task <ActionResult> Post(IFormFile formFile) { logger.LogInformation($"{nameof(FilesController)}: - Request Type:GET, Request:{nameof(Post)}"); // TODO Could cause alot of Memory usage use a temp file using (var fileStream = new MemoryStream()) { await formFile.CopyToAsync(fileStream); await fileService.AddFile(formFile.FileName, formFile.ContentType, fileStream); } return(NoContent()); }
public async Task <Guid> Save(Stream input, MetaDataRequest request, string fileName, string contentType, string serviceName) { var obj = await _fileStorageHelper.SaveFile(input, serviceName); await _fileService.AddFile(new FileModel() { ContentType = _fileHelper.DetectMimeType(request?.FileName ?? fileName), FileName = request?.FileName ?? fileName, Bucket = serviceName, Created = DateTime.Today, Id = obj }); return(obj); }
public async Task <ActionResult> SaveFile(int orderid) { try { await _fileService.AddFile(orderid); return(Ok()); } catch (NotFoundException) { return(NotFound()); } catch (Exception ex) { return(BadRequest()); } }
public async Task <IActionResult> UploadFile(IFormFile file) { try { if (file == null) { throw new Exception("Пустой файл"); } string userId = await _userService.GetUserId(User.Identity.Name); await _fileService.AddFile(file, _appEnvironment.WebRootPath, userId); } catch (Exception ex) { ViewBag.EmptyFile = true; } return(new LocalRedirectResult("/")); }
public void Setup() { _session.Transact(session => { var defaultMediaCategory = new MediaCategory { Name = "Default", UrlSegment = "default", }; session.Save(defaultMediaCategory); string logoPath = HttpContext.Current.Server.MapPath("/Apps/Core/Content/images/logo.png"); var fileStream = new FileStream(logoPath, FileMode.Open); MediaFile dbFile = _fileService.AddFile(fileStream, Path.GetFileName(logoPath), "image/png", fileStream.Length, defaultMediaCategory); }); }
public void AnalyzeFile([FromBody] File file) { try { _fileService.AddFile(file); string text = _analysisService.GetText(file.Name, file.Container, _azureBlobStorageConfig.ConnectionString); var files = _fileService.GetFiles(); int fileId = -1; foreach (var sFile in files) { if (sFile.Name == file.Name) { fileId = sFile.Id; break; } } _mongoFileService.InsertResults(fileId); QueueItem queueItem = new() { Id = fileId, Name = file.Name, Text = text }; _publisherService.PublishToQueue(queueItem, _rabbitMQConfig.SentimentQueue); _publisherService.PublishToQueue(queueItem, _rabbitMQConfig.NameQueue); _publisherService.PublishToQueue(queueItem, _rabbitMQConfig.SwearQueue); return; } catch (Exception ex) { Debug.WriteLine(ex); return; } }
public async Task <Result <FileInfoObject> > AddFiles() { FileInfoObject toReturn = null; var form = await Request.ReadFormAsync(); var fullRelativeUrl = form.Keys.FirstOrDefault(); List <MessageInfo> messages = new List <MessageInfo>(); foreach (var file in form.Files) { var parsedContentDisposition = ContentDispositionHeaderValue.Parse(file.ContentDisposition); using (var stream = file.OpenReadStream()) { var fileContent = stream.ReadFully(); try { toReturn = fileService.AddFile(fullRelativeUrl, parsedContentDisposition.FileName.Replace("\"", ""), fileContent); } catch (AppValidationException ex) { messages.AddRange(ex.Messages); } catch (Exception ex) { this.logger.LogError(ex.ToString()); } } } if (messages.Count > 0) { throw new AppValidationException(messages); } return(toReturn); }
public async Task <IActionResult> RequestFromClientFormDoc() { FullRequestForm fullRequestForm = new FullRequestForm(Request); if (ModelState.IsValid) { int?count = 1; if (fullRequestForm.Files.Count > 5) { return(null); } foreach (var items in fullRequestForm.Files) { if (items != null && items.Length > 0) { using (var reader = new System.IO.BinaryReader(items.OpenReadStream())) { var binData = new BinaryDataDTO { Content = reader.ReadBytes(Convert.ToInt32(items.Length)) }; var fileVm = new FileDTO { BinaryData = binData, FileName = Path.GetFileName(items.FileName), ContentType = items.ContentType, RequestFormToken = fullRequestForm.Token, FileIndex = count++ }; fileService.AddFile(fileVm); } } } } return(Ok(new { count = fullRequestForm.Files.Count })); }
public ActionResult UploadFile() { try { var userId = User.Claims.GetUserId(); IFormFile file = Request.Form.Files.First(); FileInfoModel fileInfo = _fileHelper.SaveFile(file); _fileService.AddFile(new File() { Id = fileInfo.UniqueName, Extension = fileInfo.Extension, FileName = fileInfo.UploadName, UserId = userId }); return(new JsonResult("Upload Successful.")); } catch (System.Exception ex) { return(new JsonResult("Upload Failed: " + ex.Message)); } }
public async Task <ActionResult> Upload(HttpPostedFileBase[] uploads) { int added_files = 0; int exist_files = 0; string userName = User.Identity.Name; await storageService.CreateStorage(userName); int storageId = await storageService.GetStorageIdByUserName(userName); if (uploads == null || uploads[0] == null || uploads.Length > 10) { TempData["ValidationMessage"] = "Choose from 1 to 10 files"; } else { int total_size = 0; foreach (var upload in uploads) { total_size += upload.ContentLength; } if (total_size >= 524288000) { TempData["ValidationMessage"] = "Total size should not exceed 500MB"; } else { foreach (var upload in uploads) { var storageSize = await storageService.GetStorageSize(storageId); if (storageSize + upload.ContentLength > MAX_STORAGE_SIZE) { TempData["ValidationMessage"] = "Storage size reached the limit in 5GB"; break; } string fileName = Path.GetFileName(upload.FileName); int length = upload.ContentLength; string type = upload.ContentType; string path = "~/Files/" + Guid.NewGuid(); if (!await fileService.IsFileExist(fileName, storageId)) { FileDto fileModel = new FileDto() { Name = fileName, Path = path, Length = length, StorageId = storageId, Type = type }; await fileService.AddFile(fileModel); await storageService.IncreaseStorageSize(storageId, length); upload.SaveAs(Server.MapPath(path)); added_files++; } else { exist_files++; } } TempData["UploadInfo"] = added_files > 0 ? $"Added {added_files} new file(s)." : ""; TempData["UploadInfo"] += exist_files > 0 ? $" {exist_files} file(s) already exist." : ""; } } return(RedirectToAction("Index")); }
public MediaModel Setup() { var model = new MediaModel(); var defaultMediaCategory = _documentService.GetDocumentByUrl <MediaCategory>("default"); try { var memoryStream = new MemoryStream(EcommerceInstallHelper.GetFileFromUrl(EcommerceInstallInfo.LogoImageUrl)); model.Logo = _fileService.AddFile(memoryStream, "logo.png", "image/png", memoryStream.Length, defaultMediaCategory); memoryStream = new MemoryStream(EcommerceInstallHelper.GetFileFromUrl(EcommerceInstallInfo.Slide1ImageUrl)); model.SliderImage1 = _fileService.AddFile(memoryStream, "slide1.jpg", "image/jpeg", memoryStream.Length, defaultMediaCategory); memoryStream = new MemoryStream(EcommerceInstallHelper.GetFileFromUrl(EcommerceInstallInfo.Slide2ImageUrl)); model.SliderImage2 = _fileService.AddFile(memoryStream, "slide2.jpg", "image/jpeg", memoryStream.Length, defaultMediaCategory); memoryStream = new MemoryStream(EcommerceInstallHelper.GetFileFromUrl(EcommerceInstallInfo.DeliveryIcon)); model.DeliveryIcon = _fileService.AddFile(memoryStream, "delivery.gif", "image/gif", memoryStream.Length, defaultMediaCategory); memoryStream = new MemoryStream(EcommerceInstallHelper.GetFileFromUrl(EcommerceInstallInfo.ReturnIcon)); model.ReturnIcon = _fileService.AddFile(memoryStream, "return.gif", "image/gif", memoryStream.Length, defaultMediaCategory); memoryStream = new MemoryStream(EcommerceInstallHelper.GetFileFromUrl(EcommerceInstallInfo.LocationIcon)); model.LocationIcon = _fileService.AddFile(memoryStream, "location.gif", "image/gif", memoryStream.Length, defaultMediaCategory); memoryStream = new MemoryStream(EcommerceInstallHelper.GetFileFromUrl(EcommerceInstallInfo.ContactIcon)); model.ContactIcon = _fileService.AddFile(memoryStream, "contact.gif", "image/gif", memoryStream.Length, defaultMediaCategory); //featured category images memoryStream = new MemoryStream(EcommerceInstallHelper.GetFileFromUrl(FeaturedCategoriesInfo.Category1ImageUrl)); model.FeaturedCategory1 = _fileService.AddFile(memoryStream, "cat1.jpg", "image/jpeg", memoryStream.Length, defaultMediaCategory); memoryStream = new MemoryStream(EcommerceInstallHelper.GetFileFromUrl(FeaturedCategoriesInfo.Category2ImageUrl)); model.FeaturedCategory2 = _fileService.AddFile(memoryStream, "cat2.jpg", "image/jpeg", memoryStream.Length, defaultMediaCategory); memoryStream = new MemoryStream(EcommerceInstallHelper.GetFileFromUrl(FeaturedCategoriesInfo.Category3ImageUrl)); model.FeaturedCategory3 = _fileService.AddFile(memoryStream, "cat3.jpg", "image/jpeg", memoryStream.Length, defaultMediaCategory); memoryStream = new MemoryStream(EcommerceInstallHelper.GetFileFromUrl(FeaturedCategoriesInfo.Category4ImageUrl)); model.FeaturedCategory4 = _fileService.AddFile(memoryStream, "cat4.jpg", "image/jpeg", memoryStream.Length, defaultMediaCategory); memoryStream = new MemoryStream(EcommerceInstallHelper.GetFileFromUrl(FeaturedCategoriesInfo.SecureCheckout)); model.SecureCheckout = _fileService.AddFile(memoryStream, "secure-checkout.png", "image/png", memoryStream.Length, defaultMediaCategory); } catch (Exception ex) { } var imgPath = HttpContext.Current.Server.MapPath(EcommerceInstallInfo.AwatingImageUrl); var fileStream = new FileStream(imgPath, FileMode.Open); model.AwatiginImage = _fileService.AddFile(fileStream, Path.GetFileName(imgPath), "image/jpeg", fileStream.Length, defaultMediaCategory); return(model); }