Beispiel #1
0
        public async Task <IActionResult> Index()
        {
            ViewBag.Title = "Upload Files";
            UploadViewModel model = new UploadViewModel();

            model.CurrentSub       = Subdomain;
            model.Encrypt          = false;
            model.ExpirationLength = 1;
            model.ExpirationUnit   = ExpirationUnit.Days;
            model.MaxUploadSize    = _config.UploadConfig.MaxUploadSize;
            if (User.Identity.IsAuthenticated)
            {
                User user = UserHelper.GetUser(_dbContext, User.Identity.Name);
                if (user != null)
                {
                    model.Encrypt          = user.UploadSettings.Encrypt;
                    model.ExpirationLength = user.UploadSettings.ExpirationLength;
                    model.ExpirationUnit   = user.UploadSettings.ExpirationUnit;
                    model.Vaults           = user.Vaults.ToList();

                    model.MaxUploadSize = _config.UploadConfig.MaxUploadSizeBasic;
                    IdentityUserInfo userInfo = await IdentityHelper.GetIdentityUserInfo(_config, User.Identity.Name);

                    if (userInfo.AccountType == AccountType.Premium)
                    {
                        model.MaxUploadSize = _config.UploadConfig.MaxUploadSizePremium;
                    }
                }
            }
            return(View(model));
        }
        public async Task <ActionResult> Send(UploadViewModel uploadViewModel)
        {
            //retrieving the data submitted
            var    file      = Request.Form.Files["File"];
            string group     = uploadViewModel.Group;
            string firstName = uploadViewModel.FirstName;
            string lastName  = uploadViewModel.LastName;

            ApplicationUser applicationUser = applicationUserRepository.GetUserByNames(firstName, lastName).FirstOrDefault();

            var filePath = Path.Combine(webHostEnvironment.WebRootPath, "uploads");

            if (!Directory.Exists(filePath))
            {
                Directory.CreateDirectory(filePath);
            }

            using (var fileStream = System.IO.File.Create(Path.Combine(filePath, file.FileName)))
            {
                file.CopyTo(fileStream);
            }

            FileHandler fileHandler = new FileHandler(configuration);
            await fileHandler.UploadFile(Path.Combine(filePath, file.FileName).ToString(), applicationUser);

            System.IO.File.Delete(Path.Combine(filePath, file.FileName));

            //the lists will be empty on post and we need to repopulate them
            uploadViewModel.ApplicationUsers = this.applicationUserRepository.AllApplicationUsers;
            uploadViewModel.StudyPrograms    = this.studyProgramRepository.AllStudyPrograms;
            uploadViewModel.Groups           = this.groupRepository.AllGroups;

            return(View(uploadViewModel));
        }
Beispiel #3
0
        public async Task <IActionResult> UploadImage(UploadViewModel model)
        {
            var file = model.File;

            if (file.Length > 0)
            {
                string path = Path.Combine(_env.WebRootPath, "images");

                using (var fs = new FileStream(Path.Combine(path, file.FileName), FileMode.Create))
                {
                    await file.CopyToAsync(fs);
                }
                model.Source    = $"/images{file.FileName}";
                model.Extension = Path.GetExtension(file.FileName).Substring(1);
                return(Ok(model));
            }

            return(BadRequest());

            //if (file == null) throw new Exception("File is null");
            //if (file.Length == 0) throw new Exception("File is empty");

            //using (Stream stream = file.OpenReadStream())
            //{
            //    using (var binaryReader = new BinaryReader(stream))
            //    {
            //        var fileContent = binaryReader.ReadBytes((int)file.Length);
            //        await _uploadService.AddFile(fileContent, file.FileName, file.ContentType);
            //    }
            //}
        }
        public async Task <bool> UploadImageAsync(UploadViewModel upload, string userId)
        {
            try
            {
                string filename = upload.Image.FileName + Guid.NewGuid().ToString() + Path.GetExtension(upload.Image.FileName);
                // Create a URI to the blob
                Uri blobUri = new Uri("https://" +
                                      _configuration.GetValue <string>("Azure:StorageAccount:Name") +
                                      ".blob.core.windows.net/" +
                                      _configuration.GetValue <string>("Azure:StorageAccount:BlobContainer") +
                                      "/" + filename);

                // Create StorageSharedKeyCredentials object by reading
                // the values from the configuration (appsettings.json)
                StorageSharedKeyCredential storageCredentials = new StorageSharedKeyCredential(
                    _configuration.GetValue <string>("Azure:StorageAccount:Name"), _configuration.GetValue <string>("Azure:StorageAccount:Key"));

                // Create the blob client.
                BlobClient blobClient = new BlobClient(blobUri, storageCredentials);

                // Upload the file
                using (Stream file = upload.Image.OpenReadStream())
                {
                    var res = await blobClient.UploadAsync(file);
                    await RecordImageUploadAsync(upload.Image.FileName, filename, userId);
                }
                return(true);
            }
            catch (Exception ex)
            {
                return(false);
            }
        }
Beispiel #5
0
        public void Insert(UploadViewModel vmod)
        {
            DokumenOrmawa dokumen = new DokumenOrmawa();

            dokumen.Nama           = vmod.Nama;
            dokumen.Urldokumen     = vmod.Urldokumen;
            dokumen.JenisDokumenId = vmod.JenisDokumenId;
            _context.DokumenOrmawa.Add(dokumen);

            PengajuanProposalKegiatan pengajuan = new PengajuanProposalKegiatan();

            pengajuan.DanaAnggaran          = vmod.DanaAnggaran;
            pengajuan.Kegiatan              = vmod.Kegiatan;
            pengajuan.AnggotaOrmawaId       = 2;
            pengajuan.TipeKegiatanOrmawaId  = vmod.TipeKegiatanOrmawaId;
            pengajuan.JenisKegiatanOrmawaId = vmod.JenisKegiatanOrmawaId;
            pengajuan.PenanggungJawabId     = 7;
            _context.PengajuanProposalKegiatan.Add(pengajuan);

            DaftarDokumenOrmawa daftar = new DaftarDokumenOrmawa();

            daftar.PengajuanProposalKegiatanId = pengajuan.Id;
            daftar.DokumenOrmawaId             = dokumen.Id;
            _context.DaftarDokumenOrmawa.Add(daftar);
            _context.SaveChanges();
        }
Beispiel #6
0
        public IActionResult Upload(IFormFile imageFile, string password)
        {
            Guid   guid           = Guid.NewGuid();
            string actualFileName = $"{guid}-{imageFile.FileName}";
            string finalFileName  = Path.Combine(_environment.WebRootPath, "uploads", actualFileName);

            using var fs = new FileStream(finalFileName, FileMode.CreateNew);
            imageFile.CopyTo(fs);

            var db    = new Imagesdb(_connectionString);
            var image = new Image
            {
                Name     = actualFileName,
                Password = password,
                View     = +1
            };

            db.Add(image);
            var vm = new UploadViewModel
            {
                Image = image
            };

            return(View(vm));
        }
Beispiel #7
0
        public ActionResult PostAPet(UploadViewModel model, HttpPostedFileBase[] images = null)
        {
            if (model != null && images != null)
            {
                int i = 1; string imageFileString = "";
                var imgList = new Dictionary <int, string>();
                foreach (var image in images)
                {
                    var imgBin = new byte[image.ContentLength];
                    image.InputStream.Read(imgBin, 0, image.ContentLength);
                    var base64Img = Convert.ToBase64String(imgBin);
                    imageFileString = string.Format("data:image/jpg;base64,{0}", base64Img);
                    imgList.Add(i++, imageFileString);
                }

                var lastId = TroyHack.MvcApplication.AllPostings.Max(p => p.PostingId);

                var posting = new PostViewModel
                {
                    Age            = model.Age,
                    Breed          = model.Breed,
                    Characteristic = model.Characteristic,
                    Health         = model.Health,
                    Images         = imgList,
                    PostingId      = lastId + 1,
                    SpecialNeeds   = model.SpecialNeeds,
                    Status         = model.Status,
                    Story          = model.Story
                };

                TroyHack.MvcApplication.AllPostings.Add(posting);
                return(RedirectToAction("Index"));
            }
            return(RedirectToAction("PostAPet"));
        }
Beispiel #8
0
        /// <summary>
        /// Initiate a new upload operation by creating a new UploadViewModel, setting its properties,
        /// saving its local upload file and finall publishing an UploadActionMessage with a UploadAction.Create
        /// property for the new UploadViewModel to handle.
        /// </summary>
        /// <param name="newLocalUpload"></param>
        /// <param name="newArchive"></param>
        /// <returns></returns>
        private void InitiateNewUpload(Archive newArchive, IList <ArchiveFileInfo> archiveFilesInfo)
        {
            _log.Info("Initiating a new upload in the upload manager.");

            // create a new UploadViewModel.
            UploadViewModel newUploadVM = this.CreateNewUploadVM() as UploadViewModel;

            // create a new local upload
            var newLocalUpload = new LocalUpload()
            {
                ArchiveFilesInfo          = archiveFilesInfo.ToList(),
                IsArchiveManifestUploaded = false
            };

            newUploadVM.Archive     = newArchive;
            newUploadVM.LocalUpload = newLocalUpload;

            this._localUploads.Add(newUploadVM.LocalUpload);

            // add the new UploadViewModel at the beginning of the Uploads list.
            PendingUploads.Insert(0, newUploadVM);

            NotifyOfPropertyChange(() => TotalPendingUploadsText);
            NotifyOfPropertyChange(() => this.HasUploads);

            // activate the new uploadviewmodel before sending the create message.
            this.ActivateItem(newUploadVM);

            IUploadActionMessage uploadActionMessage = IoC.Get <IUploadActionMessage>();

            uploadActionMessage.UploadAction = Enumerations.UploadAction.Create;
            uploadActionMessage.UploadVM     = newUploadVM;

            this._eventAggregator.PublishOnBackgroundThread(uploadActionMessage);
        }
        /// <summary>
        /// Uploads CSV file containg Vehicle sale data in the format provided by  Data Track
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool UploadVehicleData(UploadViewModel model)
        {
            bool ret = true;

            if (model.FileToUpload != null)
            {
                try
                {
                    //File name and folder name has been hard coded for Demo
                    Guid   gid         = Guid.NewGuid();
                    string folderPath  = Path.Combine(appPath, "VehicleData");
                    string filePath    = Path.Combine(folderPath, "DefaultData.csv");
                    string oldFileName = Path.Combine(folderPath, $"DefaultData{gid}.csv");
                    if (File.Exists(filePath))
                    {
                        File.Move(filePath, oldFileName);
                    }
                    using (var fileStream = File.Create(filePath))
                    {
                        fileStream.Position = 0;
                        model.FileToUpload.CopyTo(fileStream);
                    }
                }
                catch
                {
                    ret = false;
                }
            }
            return(ret);
        }
Beispiel #10
0
        public IActionResult Edit(Guid id, UploadViewModel model)
        {
            var fileInfo = _fileData.Get(id);

            var companyId = GetNonAdminUserCompanyId();

            if (!companyId.IsNullOrWhiteSpace() && !fileInfo.ContainerName.Equals(companyId, StringComparison.OrdinalIgnoreCase) ||
                fileInfo.ReadOnly)
            {
                return(RedirectToAction(nameof(AccountController.AccessDenied), nameof(AccountController).GetControllerName(),
                                        new { returnUrl = Request.Path }));
            }

            if (ModelState.IsValid)
            {
                fileInfo.Description = model.Description;
                fileInfo.ContentType = model.ContentType;
                fileInfo.ReadOnly    = model.ReadOnly;
                _fileData.Commit();

                SendFileNotification(FileOperations.ModifiedMetadata, fileInfo.FileName,
                                     User.Claims.FirstOrDefault(_ => _.Type.Equals(AuthConstants.CompanyClaim)).Value);

                return(RedirectToAction(nameof(Details), new { id = fileInfo.Id }));
            }

            return(View(fileInfo));
        }
Beispiel #11
0
 public async Task <BaseResult <string> > UploadPhoto(UploadViewModel request)
 {
     try
     {
         var baseDir = Path.Combine(Constants.DocumentBaseDirectory);
         smbFileOperationHelper.CreateFolder(baseDir);
         var hotelDir = Path.Combine(baseDir, request.HotelCode);
         smbFileOperationHelper.CreateFolder(hotelDir);
         var photosDir = Path.Combine(hotelDir, Constants.DocumentPhotosDirectory);
         smbFileOperationHelper.CreateFolder(photosDir);
         var rand         = new Random();
         var fileToUpload = Path.Combine(photosDir, rand.Next().ToString(CultureInfo.InvariantCulture));
         smbFileOperationHelper.CreateFile(fileToUpload, request.Extension.Value, request.Bytes.ToArray(), true);
         return(new BaseResult <string>()
         {
             Result = fileToUpload + Constants.FileExtensions.GetFileExtentions(request.Extension.Value)
         });
     }
     catch (Exception e)
     {
         return(new BaseResult <string>()
         {
             IsError = true, ExceptionMessage = e
         });
     }
 }
        public async Task <IActionResult> MultipleFiles(UploadViewModel vmod)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    if (vmod.FileDokumen == null || vmod.FileDokumen.Length == 0)
                    {
                        return(Content("file not selected"));
                    }

                    var namaFile = Path.GetFileName(vmod.FileDokumen.FileName);
                    var dok      = namaFile.Substring(0, namaFile.IndexOf('.'));

                    vmod.Urldokumen = $"https://{await _fileService.UploadDokumen($"test_{dok}", vmod.FileDokumen)}";

                    _repo.Insert(vmod);

                    //return RedirectToAction(nameof(Daftaranggota));
                    SetSuccessNotification("Dokumen Berhasil di Upload");
                    return(RedirectToAction("Index", "Upload"));
                }
                return(RedirectToAction("Index"));
            }
            catch (Exception e)
            {
                SetErrorNotification(e.Message);
                return(RedirectToAction("Index", "Upload"));
            }
        }
 public ActionResult Index(UploadViewModel model, HttpPostedFileBase file)
 {
     var scanner = VirusScannerFactory.GetVirusScanner();
     var result = scanner.ScanStream(file.InputStream);
     ViewBag.Message = result.Message;
     return View(model);
 }
Beispiel #14
0
        public IActionResult Upload()
        {
            var viewModel = new UploadViewModel();

            viewModel.Categories = DbContext.Categories.ToList();
            return(View(viewModel));
        }
Beispiel #15
0
        public async Task <UploadViewModel> ShowChooser()
        {
            UploadViewModel uploadViewModel = null;

            var openPicker = new FileOpenPicker {
                ViewMode = PickerViewMode.Thumbnail, SuggestedStartLocation = PickerLocationId.PicturesLibrary
            };

            openPicker.FileTypeFilter.Add(".jpg");
            openPicker.FileTypeFilter.Add(".jpeg");
            openPicker.FileTypeFilter.Add(".png");
            openPicker.FileTypeFilter.Add(".bmp");
            var file = await openPicker.PickSingleFileAsync();

            if (file != null)
            {
                uploadViewModel               = new UploadViewModel();
                uploadViewModel.PictureFile   = file;
                uploadViewModel.PictureStream = await file.OpenReadAsync();

                uploadViewModel.ImageIdentifier = Guid.NewGuid() + file.FileType;
            }

            return(uploadViewModel);
        }
        public async Task AdminController_POST_Upload_When_FileName_Length_Is_Zero_Returns_No_Content_Found()
        {
            // Arrange
            var someFileName = "SomeFilename.csv";
            var uploadObject = new UploadViewModel.Upload {
                Filepath = someFileName
            };

            var uploadViewModel = new UploadViewModel();

            uploadViewModel.Uploads.Add(uploadObject);

            _TestAdminController.StashModel(uploadViewModel);

            var fileToUpload = Mock.Of <IFormFile>(
                f => f.FileName == someFileName &&
                f.Length == 0         // Setting needed to make sure the method fails the way this test expects it to
                );

            var listOfFiles = new List <IFormFile>();

            listOfFiles.Add(fileToUpload);

            // Act
            IActionResult result = await _TestAdminController.Uploads(listOfFiles, UPLOAD_COMMAND);

            // Assert
            Assert.NotNull(result, "Expected an object returning from the POST call to 'Uploads'");
            Assert.GreaterOrEqual(
                1,
                _TestAdminController.ModelState[""].Errors.Count,
                "Expected at least one error object to have been returned from 'Uploads', since this test is sending an invalid file to upload.");
            Assert.AreEqual($"No content found in '{fileToUpload.FileName}'", _TestAdminController.ModelState[""].Errors[0].ErrorMessage);
        }
Beispiel #17
0
        public ActionResult Upload(UploadViewModel formData)
        {
            //Save File and Create Path
            var    uploadedFile = Request.Files[0];
            string filename     = $"{DateTime.Now.Ticks}{uploadedFile.FileName}";
            var    serverPath   = Server.MapPath(@"~\Upload");
            var    fullPath     = Path.Combine(serverPath, filename);

            uploadedFile.SaveAs(fullPath);

            Upload existing = db.Uploads
                              .Where(u => u.RefId == formData.refId && u.TypeRef == formData.type)
                              .FirstOrDefault();

            if (existing == null)
            {
                var uploadModel = new Upload
                {
                    File    = filename,
                    RefId   = formData.refId,
                    TypeRef = formData.type
                };

                db.Uploads.Add(uploadModel);
            }
            else
            {
                existing.File            = filename;
                db.Entry(existing).State = EntityState.Modified;
            }

            db.SaveChanges();

            return(Redirect(formData.ReturnUrl));
        }
Beispiel #18
0
 public UploadPage()
 {
     InitializeComponent();
     BindingContext      = new UploadViewModel();
     imagePreview.Source = URL;
     test += URL;
 }
        public async Task AdminController_POST_Upload_When_FileName_Does_Not_Match_Returns_Invalid_Filename()
        {
            // Arrange
            var someFileName = "SomeFilename";
            var uploadObject = new UploadViewModel.Upload {
                Filepath = someFileName + "InvalidFilename" + ".csv"
            };

            var uploadViewModel = new UploadViewModel();

            uploadViewModel.Uploads.Add(uploadObject);

            _TestAdminController.StashModel(uploadViewModel);

            var fileToUpload = Mock.Of <IFormFile>(f => f.FileName == someFileName);

            var listOfFiles = new List <IFormFile>();

            listOfFiles.Add(fileToUpload);

            // Act
            IActionResult result = await _TestAdminController.Uploads(listOfFiles, UPLOAD_COMMAND);

            // Assert
            Assert.NotNull(result, "Expected an object returning from the POST call to 'Uploads'");
            Assert.GreaterOrEqual(
                1,
                _TestAdminController.ModelState[""].Errors.Count,
                "Expected at least one error object to have been returned from 'Uploads', since this test is sending an invalid file to upload.");
            Assert.AreEqual($"Invalid filename '{fileToUpload.FileName}'", _TestAdminController.ModelState[""].Errors[0].ErrorMessage);
        }
Beispiel #20
0
        public ActionResult AddRoom()
        {
            if (Session["account"] == null)
            {
                return(RedirectToAction("Index", "Home"));
            }
            else
            {
                Account account = Session["account"] as Account;
                if (account.Role == 0)
                {
                    return(RedirectToAction("AllPost", "Admin"));
                }
                else if (account.Role == 2)
                {
                    return(RedirectToAction("ChangeInfo", "Account"));
                }
            }
            var cityList        = db.Provinces.OrderBy(c => c.ProvinceName).ToList();
            var uploadViewModel = new UploadViewModel()
            {
                ListProvince  = cityList,
                ListCriterion = db.Criteria.ToList()
            };

            return(View(uploadViewModel));
        }
Beispiel #21
0
        /// <summary>
        /// Create UploadViewModels based on the LocalUpload List,
        /// which should already be populated with all local uploads
        /// started from this client. This method runs at each application start
        /// and only then. Its purpose is to populate the client's uploads list.
        /// </summary>
        /// <param name="localUploads"></param>
        /// <returns>Task</returns>
        private void CreateUploadViewModels(IList <LocalUpload> localUploads)
        {
            IList <Task <UploadViewModel> > tasks = new List <Task <UploadViewModel> >();

            foreach (LocalUpload localUpload in localUploads)
            {
                //tasks.Add(InstatiateUploadViewModel(localUpload));

                UploadViewModel u = CreateNewUploadVM() as UploadViewModel;
                u.LocalUpload = localUpload;

                if (String.IsNullOrEmpty(localUpload.Status))
                {
                    localUpload.Status = Enumerations.Status.Pending.GetStringValue();
                }

                this.ActivateItem(u);

                Enumerations.Status status = Enumerations.GetStatusFromString(localUpload.Status);

                if (status == Enumerations.Status.Completed)
                {
                    this.CompletedUploads.Add(u);
                }
                else
                {
                    this.PendingUploads.Add(u);
                }
            }

            _log.Info("Created " + this.PendingUploads.Count + " UploadViewModels for the upload manager.");
        }
Beispiel #22
0
        public async Task <IActionResult> ProductsDataPost(long?id = 0)
        {
            if (id == null || id == 0)
            {
                return(Redirect("/Admin/Products/Index"));
            }

            var up = new UploadViewModel();

            up.idpost = id.ToString();

            var pro = await _context.Products.Include(a => a.IdmenuNavigation)
                      .Where(p => p.Id == id).FirstOrDefaultAsync();

            if (pro == null)
            {
                return(Redirect("/Admin/Products/Index"));
            }

            ViewData["product"]  = pro;
            ViewData["Datatype"] = new SelectList(_context.Productdatatypes, "Id", "Name");


            return(View(up));
        }
Beispiel #23
0
        public async Task <IActionResult> UpdateCustomer(UploadViewModel listofcustomers)
        {
            int?CustomerUploaded = listofcustomers.CustomersList.ToList().Count();

            foreach (var customer in listofcustomers.CustomersList)
            {
                _db.Customers.Add(customer);
            }
            string message;
            await _db.SaveChangesAsync();

            if (CustomerUploaded == null)
            {
                // Loads page "Nothing" in data folder.
                return(View("Nothing"));
            }
            if (CustomerUploaded == 1)
            {
                message = "1 customer uploaded";
            }
            else
            {
                message = CustomerUploaded.ToString() + " customers uploaded";
            }
            // Displays page saving it has been successful and reporting how many customers have been uploaded
            return(View("UploadSuccess", message));
        }
Beispiel #24
0
        public async Task <IActionResult> Upload(UploadViewModel model)
        {
            if (!this.ModelState.IsValid)
            {
                return(this.View(model));
            }

            var product = await this.productsRepository.Get(model.ProductId).ConfigureAwait(false);

            if (model.Photos != null)
            {
                var photoUris = await this.SaveFiles(model.Photos.ToArray()).ConfigureAwait(false);

                foreach (var photo in photoUris.Select(x => new Photo {
                    Uri = x
                }))
                {
                    product.Photos.Add(photo);
                }
            }

            if (model.Thumbnail != null)
            {
                var thumbnailUri = await this.SaveFiles(model.Thumbnail).ConfigureAwait(false);

                product.Thumbnail = thumbnailUri.Single();
            }

            await this.productsRepository.Update(product);

            return(this.RedirectToAction("CreateOrEdit", new { id = model.ProductId }));
        }
        public UploadViewModel Upload(IFormFile file, string virtualPath)
        {
            UploadViewModel result;

            var fileExtension = string.Empty;

            if (file.ContentType != null)
            {
                fileExtension = Helpers.GetExtension(file.ContentType).Replace(".", "");
            }
            else
            {
                string[] split = file.FileName.Split(".");
                fileExtension = split[split.Length - 1];
            }

            var filename = Guid.NewGuid().ToString() + "." + fileExtension;
            var fullPath = Path.Combine(pathToSave, filename);

            using (var stream = new FileStream(fullPath, FileMode.Create))
            {
                file.CopyTo(stream);
            }

            result = new UploadViewModel(virtualPath, filename, fileExtension);
            return(result);
        }
        public ActionResult Main(UploadViewModel upload)
        {
            portfolioContext context = new portfolioContext();

            if (!ModelState.IsValid)
            {
                return(View("Index", upload));
            }
            int id          = Convert.ToInt32(upload.Works.Filter);
            var filtervalue = context.filters.SingleOrDefault(x => x.Id == id);

            HttpPostedFileBase image = Request.Files["Image"];

            byte[] bytes = null;
            using (BinaryReader br = new BinaryReader(image.InputStream))
            {
                bytes = br.ReadBytes(image.ContentLength);
            }
            Works work = new Works
            {
                Image       = bytes,
                Description = upload.Works.Description,
                Title       = upload.Works.Title,
                Filter      = filtervalue.Filter,
                DT          = DateTime.Now
            };

            context.Works.Add(work);
            context.SaveChanges();
            return(RedirectToAction("Main", "Admin"));
        }
        public HttpResponseMessage CvPhoto([FromBody] UploadViewModel model)
        {
            String uploadFolder = ConfigurationManager.AppSettings["PhotoUploadPath"];
            String path         = HttpContext.Current.Server.MapPath("~/" + uploadFolder); //Path

            if (!System.IO.Directory.Exists(path))
            {
                System.IO.Directory.CreateDirectory(path); //Create directory if it doesn't exist
            }

            string imageName = Guid.NewGuid() + ".jpg";

            string imgPath       = Path.Combine(path, imageName);
            var    stringContent = model.Content
                                   .Replace("data:image/jpeg;base64,", "")
                                   .Replace("data:image/png;base64,", "");

            byte[] imageBytes = Convert.FromBase64String(stringContent);

            File.WriteAllBytes(imgPath, imageBytes);

            var dataReturn = new
            {
                Photo = string.Format("/{0}/{1}", uploadFolder, imageName),
            };

            return(Request.CreateResponse(HttpStatusCode.OK, dataReturn));
        }
Beispiel #28
0
        public IActionResult Upload(UploadViewModel model)
        {
            List <UploadResult> result = new List <UploadResult>();

            #region Form.Files 文件

            IFormFileCollection files = HttpContext.Request.Form.Files;

            if (null != files && files.Count > 0)
            {
                FormFileUploadViewModel fileModel = new FormFileUploadViewModel();

                foreach (IFormFile file in files)
                {
                    model.CopyTo(fileModel);

                    fileModel.File = file;

                    var itemResult = UploadItemByFormFile(fileModel);

                    result.Add(itemResult);
                }
            }

            #endregion

            #region Form.Base64 文件

            Dictionary <string, string> base64Dictionary = new Dictionary <string, string>();

            var formCollection = Request.Form;

            foreach (var fc in formCollection)
            {
                if (_regexBase64.IsMatch(fc.Value))
                {
                    base64Dictionary.Add(fc.Key, fc.Value);
                }
            }

            if (null != base64Dictionary && base64Dictionary.Count > 0)
            {
                Base64UploadViewModel base64Model = null;

                foreach (var file in base64Dictionary)
                {
                    model.CopyTo(base64Model);
                    base64Model.Data      = file.Value;
                    base64Model.FieldName = file.Key;

                    var itemResult = UploadItemByBase64(base64Model);

                    result.Add(itemResult);
                }
            }

            #endregion

            return(Json(result));
        }
        public UploadPage()
        {
            InitializeComponent();

            _viewModel  = ServiceLocator.Current.GetInstance <UploadViewModel>();
            DataContext = _viewModel;

            Loaded += UploadPage_Loaded;

            // We need to prevent the virtual keyboard covering the textbox control
            InputPane.GetForCurrentView().Showing += (s, args) =>
            {
                RenderTransform = new TranslateTransform {
                    Y = -args.OccludedRect.Height
                };
                args.EnsuredFocusedElementInView = true;
            };

            InputPane.GetForCurrentView().Hiding += (s, args) =>
            {
                RenderTransform = new TranslateTransform {
                    Y = 0
                };
                args.EnsuredFocusedElementInView = false;
            };
        }
        private async Task <bool> IsValid(UploadViewModel uploadForm)
        {
            if (uploadForm.PictureFile == default(StorageFile))
            {
                var messageBox = new Windows.UI.Popups.MessageDialog("You must select a picture before uploading.", "Warning!");
                await messageBox.ShowAsync();

                return(false);
            }

            if ((uploadForm.SelectedAlbum.UniqueId == string.Empty) && string.IsNullOrWhiteSpace(uploadForm.NewAlbumName))
            {
                var messageBox = new Windows.UI.Popups.MessageDialog("You must provide an album name.", "Warning!");
                await messageBox.ShowAsync();

                return(false);
            }

            if (string.IsNullOrWhiteSpace(uploadForm.PictureName))
            {
                var messageBox = new Windows.UI.Popups.MessageDialog("You must provide a picture title.", "Warning!");
                await messageBox.ShowAsync();

                return(false);
            }

            return(true);
        }
        public IActionResult Create(UploadViewModel model)
        {
            string statusMessage = string.Empty;

            ViewBag.Error = string.Empty;
            if (ModelState.IsValid)
            {
                //TODO: Accept attribute not working. Need to verify and remove code below
                if (!model.FileToUpload.FileName.ToLower().EndsWith("csv"))
                {
                    // ViewBag.Error = "Only .CSV files allowed";
                    ViewBag.Error = "Only .CSV files allowed !";
                    return(View());
                }
                if (model.FileToUpload.Length == 0)
                {
                    ViewBag.Error = "Empty file Not allowed";
                    return(View());
                }

                var  data        = _repository.GetDataService(VehicleDataStore.File_CSV);
                bool writeStatus = data.UploadVehicleData(model);
                statusMessage = writeStatus == true ? "File Successfully uploaded" : "There is error uploading file";
                return(View("UploadData", statusMessage));
            }
            else
            {
                ViewBag.Error = string.Empty;
                return(View());
            }
        }
        public RootViewModel(Window window)
        {
            if (window == null)
                throw new ArgumentNullException("window");

            this.window = window;

            Upload = new UploadViewModel();

            ConnectCommand = new AnonymousCommand(OnConnect);
            CloseCommand = new AnonymousCommand(App.Current.Shutdown);

            AboutCommand = new AnonymousCommand(OnAbout);
        }
        public ActionResult Upload()
        {
            _logger.Debug("Upload init");

            if (!_permissionService.Authorize(StandardPermissionProvider.ManageProducts))
                return AccessDeniedView();

            //a vendor cannot import products
            if (_workContext.CurrentVendor != null)
                return AccessDeniedView();

            var viewModel = new UploadViewModel { };

            return View("~/Plugins/Anko.Plugin.Admin.Uploader/Views/Upload/Upload.cshtml");
        }
        public ActionResult Upload(int showId)
        {
            var show = DatabaseSession.Get<Show>(showId);

            var viewModel = new UploadViewModel();
            viewModel.ParentName = show.DisplayTitleWithYear;
            viewModel.ParentLinkURL = this.GetURL<ShowController>(c => c.ShowDetails(showId));
            viewModel.PhotoCount = DatabaseSession.Query<ShowPhoto>().Where(x => x.Show == show).Count();
            viewModel.PhotoListLinkURL = Url.GetUrl(ListShowPhotos, showId, (int?)null);
            viewModel.UploadFormURL = Url.GetUrl(Upload, showId, (PhotosController.UploadPOSTParameters)null);

            return new ViewModelResult(viewModel);
        }