public async Task <JObject> UploadImage(HttpPostedFileBase files)
        {
            //var ImageFileProduct = Request.Files;
            //ByteArrayContent fileContent;
            //List<byte[]> productImages = new List<byte[]>();
            //byte[] fileDataProductImage = null;
            //MultipartFormDataContent content = new MultipartFormDataContent();
            //foreach (string fileName in ImageFileProduct)
            //{
            //    HttpPostedFileBase file = ImageFileProduct[fileName];
            //    if (file.ContentLength > 0)
            //    {
            //        using (var binaryReader = new BinaryReader(file.InputStream))
            //        {
            //            fileDataProductImage = binaryReader.ReadBytes(file.ContentLength);
            //            productImages.Add(fileDataProductImage);
            //        }
            //    }
            //}
            //for (int i = 0; i < productImages.Count; i++)
            //{
            //    fileContent = new ByteArrayContent(productImages[i]);
            //    fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = "Product_" + i + Path.GetExtension(ImageFileProduct[0].FileName) };
            //    content.Add(fileContent, "ProductImage");
            //}
            //// JObject response;
            //JObject response = await ApiCall.CallApi("api/Common/UploadImages", User, isMultipart: true, multipartContent: content);
            //return response;

            try
            {
                UploadImageBindingModel model = new UploadImageBindingModel();

                if (Request.Files.Count > 0)
                {
                    var file = Request.Files[0];
                    model.Image = file;
                    //if (file != null && file.ContentLength > 0)
                    //{
                    //    model.Image.FileName = Path.GetFileName(file.FileName);
                    //    var path = Path.Combine(Server.MapPath("~/Images/"), model.Image.FileName);

                    //    byte[] thePictureAsBytes = new byte[file.ContentLength];
                    //    using (BinaryReader theReader = new BinaryReader(file.InputStream))
                    //    {
                    //        model.Image.Buffer = theReader.ReadBytes(file.ContentLength);
                    //    }

                    //}
                }
                JObject response = await ApiCall.CallApi("api/Common/UploadImages", User, model);

                return(response);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Beispiel #2
0
        public async Task <ActionResult> UploadImage(UploadImageBindingModel model)
        {
            var contest = this.Data.Contests.All().FirstOrDefault(c => c.Id == model.ContestId);

            if (!this.ModelState.IsValid || model == null)
            {
                var errorList = ModelState.Values.SelectMany(m => m.Errors)
                                .Select(e => e.ErrorMessage)
                                .ToList();

                TempData["uploadFail"] = "Wrong input. " + string.Join("\n", errorList);
                return(this.RedirectToAction("Details", "Contest", new { id = contest.Id }));
            }

            var userId = User.Identity.GetUserId();

            //var contest = this.Data.Contests.All().FirstOrDefault(c => c.Id == model.ContestId);

            if (!this.RightToParticipate(contest, userId))
            {
                TempData["uploadFail"] = "You have no right to participate in this contest.";
                return(this.RedirectToAction("Details", "Contest", new { id = contest.Id }));
            }

            var fileExtension   = Path.GetExtension(model.PhotoFile.FileName);
            var rawFileName     = Path.GetFileNameWithoutExtension(model.PhotoFile.FileName);
            var uniquePhotoName = Guid.NewGuid() + "-" + rawFileName + fileExtension;

            var folderNameInDropbox = Regex.Replace(contest.Title, "\\s+", "");

            var sharedLink = await DropboxManager.Upload("/" + folderNameInDropbox, uniquePhotoName, model.PhotoFile.InputStream);

            if (sharedLink == null)
            {
                TempData["uploadFail"] = "No connection to the cloud environment. \nPlease try again later";
                return(this.RedirectToAction("Details", "Contest", new { id = contest.Id }));
            }

            var rawSharedLink = sharedLink.Substring(0, sharedLink.IndexOf("?")) + "?raw=1";

            var newImage = new Image()
            {
                Title       = model.Title,
                Description = model.Description,
                ContestId   = model.ContestId,
                CreatedOn   = DateTime.Now,
                ImagePath   = rawSharedLink,
                UserId      = userId,
                FileName    = uniquePhotoName
            };

            this.Data.Images.Add(newImage);
            await this.Data.SaveChangesAsync();

            TempData["successUpload"] = "Image was successfully uploaded.";
            return(this.RedirectToAction("Details", "Contest", new { id = contest.Id }));
        }
Beispiel #3
0
        public IActionResult UploadImage(int Id)
        {
            var model = new UploadImageBindingModel()
            {
                AlbumId = Id
            };

            return(View(model));
        }
        public async Task<ActionResult> UploadImage(UploadImageBindingModel model)
        {
            var contest = this.Data.Contests.All().FirstOrDefault(c => c.Id == model.ContestId);

            if (!this.ModelState.IsValid || model == null)
            {
                var errorList = ModelState.Values.SelectMany(m => m.Errors)
                                 .Select(e => e.ErrorMessage)
                                 .ToList();

                TempData["uploadFail"] = "Wrong input. " + string.Join("\n", errorList);
                return this.RedirectToAction("Details", "Contest", new { id = contest.Id });
            }

            var userId = User.Identity.GetUserId();
            //var contest = this.Data.Contests.All().FirstOrDefault(c => c.Id == model.ContestId);

            if (!this.RightToParticipate(contest, userId))
            {
                TempData["uploadFail"] = "You have no right to participate in this contest.";
                return this.RedirectToAction("Details", "Contest", new { id = contest.Id });
            }

            var fileExtension = Path.GetExtension(model.PhotoFile.FileName);
            var rawFileName = Path.GetFileNameWithoutExtension(model.PhotoFile.FileName);
            var uniquePhotoName = Guid.NewGuid() + "-" + rawFileName + fileExtension;

            var folderNameInDropbox = Regex.Replace(contest.Title, "\\s+", "");

            var sharedLink = await DropboxManager.Upload("/" + folderNameInDropbox, uniquePhotoName, model.PhotoFile.InputStream);

            if (sharedLink == null)
            {
                TempData["uploadFail"] = "No connection to the cloud environment. \nPlease try again later";
                return this.RedirectToAction("Details", "Contest", new { id = contest.Id });
            }

            var rawSharedLink = sharedLink.Substring(0, sharedLink.IndexOf("?")) + "?raw=1";

            var newImage = new Image()
            {
                Title = model.Title,
                Description = model.Description,
                ContestId = model.ContestId,
                CreatedOn = DateTime.Now,
                ImagePath = rawSharedLink,
                UserId = userId,
                FileName = uniquePhotoName
            };

            this.Data.Images.Add(newImage);
            await this.Data.SaveChangesAsync();

            TempData["successUpload"] = "Image was successfully uploaded.";
            return this.RedirectToAction("Details", "Contest", new { id = contest.Id });
        }
Beispiel #5
0
        public async Task <IActionResult> UploadImage(UploadImageBindingModel model)
        {
            try
            {
                if (ModelState.IsValid)

                {
                    //get current album name
                    var album = _context.Albums.Where(a => a.Id == model.AlbumId).FirstOrDefault();

                    if (model.UploadImage.Length > 0)
                    {
                        var ext = Path.GetExtension(model.UploadImage.FileName).ToLowerInvariant();

                        if (string.IsNullOrEmpty(ext) || !Constants.permittedExtensions.Contains(ext))
                        {
                            ModelState.AddModelError("InvoiceFile", "Invalid File Type!");
                            return(View());//todo
                        }
                        else

                        {
                            string fileName = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString().PadLeft(2, '0') + DateTime.Now.Day.ToString().PadLeft(2, '0')
                                              + "_" + DateTime.Now.Hour.ToString().PadLeft(2, '0') + DateTime.Now.Minute.ToString().PadLeft(2, '0') + DateTime.Now.Second.ToString().PadLeft(2, '0')
                                              + "_" + DateTime.Now.Millisecond.ToString().PadLeft(4, '0') + ext;

                            string filePath = Path.Combine(_configuration.GetValue <string>("CustomSettings:UploadPath"), album.AlbumFolderName, fileName);

                            using (var stream = System.IO.File.Create(filePath))
                            {
                                await model.UploadImage.CopyToAsync(stream);

                                UploadImageHelper.ResizeAndSaveImage(stream, Path.Combine(_configuration.GetValue <string>("CustomSettings:UploadPath"), album.AlbumFolderName, "thumb", fileName));
                            }


                            StoreImage image = new StoreImage()
                            {
                                AlbumId    = album.Id,
                                Title      = model.Title,
                                FileName   = fileName,
                                UploadDate = DateTime.Now,
                            };

                            _context.StoreImages.Add(image);
                        }
                    }

                    _context.SaveChanges();
                    return(RedirectToAction("Images", "Albums", new { id = album.Id }));
                }
                else
                {
                    return(View(model));
                }
            }

            catch
            {
                throw;
            }
        }