Ejemplo n.º 1
0
        public override Task <UploadImageResponse> UploadImage(UploadImageRequest request, ServerCallContext context)
        {
            var resp        = new UploadImageResponse();
            var accessToken = _redis.StringGet(CacheKey.UserAccessTokenPrefix + request.AppId);

            if (accessToken.HasValue)
            {
                var result = WxWebApi.UploadImage(accessToken, request.File.ToByteArray());
                if (result.ErrCode != 0)
                {
                    resp.Error = new Error
                    {
                        ErrCode = result.ErrCode,
                        ErrMsg  = result.ErrMsg
                    };
                }
                else
                {
                    resp.ImageId = result.MediaId;
                    resp.Url     = result.Url;
                }
            }
            else
            {
                resp.Error = new Error
                {
                    ErrCode = 99999,
                    ErrMsg  = "AccessToken Missing"
                };
            }
            return(Task.FromResult(resp));
        }
Ejemplo n.º 2
0
        public async Task <string> UploadDPAsync(string base64)
        {
            string Id  = string.Empty;
            string url = string.Empty;

            byte[] myFileContent;
            try
            {
                UploadImageRequest uploadImageRequest = new UploadImageRequest();
                uploadImageRequest.ImageInfo = new FileMeta();
                uploadImageRequest.IsAsync   = false;
                string base64Norm = base64.Replace("data:image/png;base64,", "");
                myFileContent = System.Convert.FromBase64String(base64Norm);
                uploadImageRequest.ImageByte          = myFileContent;
                uploadImageRequest.ImageInfo.FileType = "jpg";
                uploadImageRequest.ImageInfo.FileName = String.Format("dp_{0}.{1}", ViewBag.UId, uploadImageRequest.ImageInfo.FileType);
                uploadImageRequest.ImageInfo.Length   = uploadImageRequest.ImageByte.Length;

                Id = this.ServiceClient.Post <string>(uploadImageRequest);
                if (ViewBag.cid == "expressbase")
                {
                    url = string.Format("http://localhost:5000/static/dp/dp_{0}.jpg", ViewBag.UId);
                }
                else
                {
                    url = string.Format("http://{0}.localhost:5000/static/dp_{1}.{2}", ViewBag.cid, ViewBag.UId, uploadImageRequest.ImageInfo.FileType);
                }
            }
            catch (Exception e)
            {
                return("upload failed");
            }

            return(url);
        }
Ejemplo n.º 3
0
        public async Task <UserProfileResponse> SetProfilePicture(UploadImageRequest req, int userId)
        {
            var profileModel = await _dbContext.UserProfiles.Include(prof => prof.User).Where(x => x.User.Id == userId).FirstOrDefaultAsync();

            if (profileModel == null)
            {
                var errorResp = new UserProfileResponse {
                    Succes = false, Errors = new List <string>()
                };
                errorResp.Errors.Add("User with such id does not exist!");
                return(errorResp);
            }

            var newAvatarName = await _imageService.UploadImage(Enums.ImageTypeEnum.PROFILE_PICTURE, req);

            if (profileModel.ProfilePicturePath != "\\images\\avatars\\default.png")
            {
                _imageService.DeleteImage(profileModel.ProfilePicturePath);
            }

            profileModel.ProfilePicturePath = newAvatarName;
            _dbContext.Update(profileModel);
            _dbContext.SaveChanges();

            var response = _mapper.Map <UserProfileResponse>(profileModel);

            return(response);
        }
        /// <summary>
        /// Takes an UploadImageRequest type object and tries to save the image in it
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task <UploadImageResponse> UploadImageAsync(UploadImageRequest request)
        {
            IFormFile           file     = request.File;
            ImageWriterResponse response = await _imageWriter.WriteFile(file);

            return(response.ToModel());
        }
Ejemplo n.º 5
0
        public async Task <UploadImageResponse> UploadImage(UploadImageRequest request)
        {
            if (request.Image == null)
            {
                throw new ValidationException().AddError("Image", "Image is required");
            }

            using (var fs = new FileStream(request.Name, FileMode.Create, FileAccess.Write))
            {
                await request.Image.CopyToAsync(fs);

                await fs.FlushAsync();
            }

            request.Image.Position = 0;
            var hash = await Task.Run(() => new SymetricCryptoService().ComputeHash(request.Image));

            var checkSum = CryptoService.ToStringX2(hash);

            return(new UploadImageResponse
            {
                Url = "http://localhost/image.jpg",
                M5checksum = checkSum
            });
        }
Ejemplo n.º 6
0
 public IActionResult UploadImage(UploadImageRequest uploadRequest)
 {
     if (uploadRequest.FormFile == null)
     {
         return(BadRequest("Image is bad format or null"));
     }
     using (var stream = uploadRequest.FormFile.OpenReadStream())
     {
         var image = new byte[stream.Length];
         stream.Read(image, 0, (int)stream.Length);
         var picture = new Picture()
         {
             Image = image
         };
         var location = _imageService.ExtractLocationFromImage(picture);
         if (!double.IsNaN(location.Item1) || !double.IsNaN(location.Item2))
         {
             uploadRequest.Latitude  = location.Item1;
             uploadRequest.Longitude = location.Item2;
         }
         stream.Read(image, 0, (int)stream.Length);
         _teamService.UploadImage(uploadRequest.GameId, uploadRequest.TeamId, uploadRequest.Latitude, uploadRequest.Longitude, image, uploadRequest.ImageName);
         return(Ok());
     }
 }
Ejemplo n.º 7
0
        public async Task <IActionResult> UploadImage([FromForm] UploadImageRequest request)
        {
            if (request.Name == null)
            {
                return(ControllerResultWithToast.FailureWithResourceMesg("NameNotSet", this));
            }
            if (request.Description == null)
            {
                return(ControllerResultWithToast.FailureWithResourceMesg("DescriptionNotSet", this));
            }
            if (request.Source == null)
            {
                return(ControllerResultWithToast.FailureWithResourceMesg("SourceNotSet", this));
            }
            if (request.File == null)
            {
                return(ControllerResultWithToast.FailureWithResourceMesg("FileNotSet", this));
            }

            var userId = await UserServices.UserIdFromContextAsync(HttpContext, userManager);

            using var stream = request.File.OpenReadStream();
            using var reader = new BinaryReader(stream);
            var fileContent        = reader.ReadBytes((int)request.File.Length);
            var applicationRequest = new StoreImage.Request(userId, request.Name.Trim(), request.Description.Trim(), request.Source.Trim(), request.File.ContentType, fileContent);

            await new StoreImage(callContext).RunAsync(applicationRequest);
            return(ControllerResultWithToast.Success($"{Get("ImageSavedWithName")} '{applicationRequest.Name.Trim()}'", this));
        }
Ejemplo n.º 8
0
        public Task <String> UploadImage(ImageTypeEnum type, UploadImageRequest req)
        {
            var newfileName = RandomName() + Path.GetExtension(req.Image.FileName);
            var path        = GetPath(type, newfileName);


            var imagePath = UploadImageToServer(req.Image, path);

            return(Task.FromResult(GetRelativePath(type, newfileName)));
        }
Ejemplo n.º 9
0
        public static UploadImageRequest ToEntity(this Microsoft.AspNetCore.Http.HttpRequest httpRequest)//(this IFormFile file)
        {
            IFormFile file = httpRequest.Form.Files[0];

            var request = new UploadImageRequest()
            {
                File = file
            };

            return(request);
        }
Ejemplo n.º 10
0
        public Response UploadImage(UploadImageRequest request)
        {
            var filePath = Path.Combine("images", request.ImageUrl.FileName);

            if (request.ImageUrl.Length > 0)
            {
                using (var fileStream = new FileStream(filePath, FileMode.Create))
                {
                    request.ImageUrl.CopyTo(fileStream);
                }
            }
            return(new UploadImageResponseOK(filePath, request.ImageUrl.FileName));
        }
Ejemplo n.º 11
0
        public override Task <UploadImageReply> UploadImage(UploadImageRequest request, ServerCallContext context)
        {
            Console.WriteLine("Called upload image method");

            var data = Convert.FromBase64String(request.Image);

            File.WriteAllBytes("../../../fromClient.jpg", data);

            return(Task.FromResult(new UploadImageReply
            {
                Result = "Success"
            }));
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Upload image from the stream.
        /// </summary>
        /// <param name="request">The upload image request.</param>
        /// <returns>The upload image response.</returns>
        public UploadImageResponse Post(UploadImageRequest request)
        {
            MediaFolder parentFolder = null;

            if (request.Data.FolderId.HasValue)
            {
                parentFolder = repository.AsQueryable <MediaFolder>()
                               .Where(c => c.Id == request.Data.FolderId.Value && !c.IsDeleted)
                               .FirstOne();

                if (parentFolder.Type != Module.MediaManager.Models.MediaType.Image)
                {
                    throw new CmsApiValidationException("Folder must be type of an image.");
                }
            }

            var maxLength = configuration.Storage.MaximumFileNameLength > 0 ? configuration.Storage.MaximumFileNameLength : 100;
            // Fix for IIS express + IE (if full path is returned)
            var fileName = Path.GetFileName(request.Data.FileName);

            if (fileName.Length > maxLength)
            {
                fileName = string.Concat(Path.GetFileNameWithoutExtension(fileName.Substring(0, maxLength)), Path.GetExtension(fileName));
            }

            var mediaImage = new MediaImage
            {
                Id                    = request.Data.Id.GetValueOrDefault(),
                Type                  = Module.MediaManager.Models.MediaType.Image,
                Caption               = request.Data.Caption,
                Title                 = request.Data.Title ?? fileName,
                Description           = request.Data.Description,
                Size                  = request.Data.FileStream.Length,
                Folder                = parentFolder,
                OriginalFileName      = fileName,
                OriginalFileExtension = Path.GetExtension(fileName)
            };

            var savedImage = mediaImageService.UploadImageWithStream(request.Data.FileStream, mediaImage, request.Data.WaitForUploadResult);

            if (savedImage != null)
            {
                Events.MediaManagerEvents.Instance.OnMediaFileUploaded(savedImage);
            }

            return(new UploadImageResponse
            {
                Data = savedImage.Id,
            });
        }
        public UploadAsyncResponse Post(UploadImageAsyncRequest request)
        {
            UploadAsyncResponse res = new UploadAsyncResponse();

            Log.Info("Inside ImageAsyncUpload");
            IUploadImageRequest req = null;

            if (request.ImageInfo.FileCategory == EbFileCategory.Dp)
            {
                req = new UploadDpRequest();
            }
            else if (request.ImageInfo.FileCategory == EbFileCategory.Images)
            {
                req = new UploadImageRequest();
            }
            else if (request.ImageInfo.FileCategory == EbFileCategory.SolLogo)
            {
                req = new UploadLogoRequest();
            }
            else if (request.ImageInfo.FileCategory == EbFileCategory.LocationFile)
            {
                req = new UploadLocRequest();
            }

            try
            {
                string context = string.IsNullOrEmpty(request.ImageInfo.Context) ? StaticFileConstants.CONTEXT_DEFAULT : request.ImageInfo.Context;
                req.Byte           = request.ImageByte;
                req.FileCategory   = request.ImageInfo.FileCategory;
                req.SolutionId     = request.SolutionId;
                req.SolnId         = request.SolnId;
                req.UserId         = (req is UploadDpRequest) ? request.UserIntId : request.UserId;
                req.UserAuthId     = request.UserAuthId;
                req.BToken         = (!String.IsNullOrEmpty(this.Request.Authorization)) ? this.Request.Authorization.Replace("Bearer", string.Empty).Trim() : String.Empty;
                req.RToken         = (!String.IsNullOrEmpty(this.Request.Headers["rToken"])) ? this.Request.Headers["rToken"] : String.Empty;
                req.SubscriptionId = (!String.IsNullOrEmpty(this.Request.Headers[TokenConstants.SSE_SUBSCRIP_ID])) ? this.Request.Headers[TokenConstants.SSE_SUBSCRIP_ID] : String.Empty;

                req.ImageRefId = GetFileRefId(request.UserId, request.ImageInfo.FileName, request.ImageInfo.FileType, request.ImageInfo.MetaDataDictionary.ToJson(), request.ImageInfo.FileCategory, request.ImageInfo.Context);

                this.MessageProducer3.Publish(req);
                res.FileRefId = req.ImageRefId;
            }
            catch (Exception e)
            {
                Log.Info("Exception:" + e.ToString());
                res.FileRefId = 0;
                res.ResponseStatus.Message = e.Message;
            }
            return(res);
        }
Ejemplo n.º 14
0
        public void ToDictionary_Works()
        {
            var request = new UploadImageRequest()
            {
                ImageSignature = new byte[] { 1, 2, 3, 4 },
                ImageSize      = 4,
                ImageType      = "Developer",
            }.ToDictionary();

            Assert.Equal("ReceiveBytes", Assert.Contains("Command", request).ToObject());
            Assert.Equal(new byte[] { 1, 2, 3, 4 }, Assert.Contains("ImageSignature", request).ToObject());
            Assert.Equal(4, Assert.Contains("ImageSize", request).ToObject());
            Assert.Equal("Developer", Assert.Contains("ImageType", request).ToString());
        }
Ejemplo n.º 15
0
        public ActionResult Upload(TestUploadViewModel model)
        {
            if (model != null && model.File != null)
            {
                using (var api = ApiFactory.Create())
                {
                    if (model.Type == "file")
                    {
                        var uploadRequest = new UploadFileRequest();
                        uploadRequest.Data.FileStream          = model.File.InputStream;
                        uploadRequest.Data.FileName            = model.File.FileName;
                        uploadRequest.Data.WaitForUploadResult = model.Method == "sync";

                        var uploadResponse = api.Media.Files.Upload.Post(uploadRequest);

                        var getRequest = new GetFileRequest {
                            FileId = uploadResponse.Data.Value
                        };
                        var getResponse = api.Media.File.Get(getRequest);

                        model.Result = string.Format(
                            "<h2 style='color; green'>File upload successful!</h2> File can be downloaded here: <div><a href='{0}' />{1}</a></div>",
                            getResponse.Data.FileUrl,
                            getResponse.Data.Title);
                    }
                    else
                    {
                        var uploadRequest = new UploadImageRequest();
                        uploadRequest.Data.FileStream          = model.File.InputStream;
                        uploadRequest.Data.FileName            = model.File.FileName;
                        uploadRequest.Data.WaitForUploadResult = model.Method == "sync";

                        var uploadResponse = api.Media.Images.Upload.Post(uploadRequest);

                        var getRequest = new GetImageRequest {
                            ImageId = uploadResponse.Data.Value
                        };
                        var getResponse = api.Media.Image.Get(getRequest);

                        model.Result = string.Format(
                            "<h2 style='color; green'>Image upload successful!</h2> <div><img src='{0}' alt='{1}' /></div>",
                            getResponse.Data.ImageUrl,
                            getResponse.Data.Title);
                    }
                }
            }

            return(View(model));
        }
Ejemplo n.º 16
0
        private async Task <string> Upload(UploadImageRequest model)
        {
            Account ac = new(model.Cloud, model.ApiKey, model.Secret);

            Cloudinary c = new(ac);

            var uploadParams = new ImageUploadParams()
            {
                File   = new FileDescription(model.ImageName, model.Image),
                Folder = "RoutineApp",
            };
            var uploadResult = await c.UploadAsync(uploadParams);

            return(uploadResult.SecureUrl.ToString());
        }
Ejemplo n.º 17
0
 public async Task <NodeResponse> UploadImage(UploadImageRequest uploadImageRequest)
 {
     using (var content = new MultipartFormDataContent())
     {
         content.Add(new StringContent(uploadImageRequest.GameId.ToString()), "gameId");
         content.Add(new StringContent(uploadImageRequest.TeamId.ToString()), "teamId");
         content.Add(new StringContent(uploadImageRequest.Latitude.ToString()), "latitude");
         content.Add(new StringContent(uploadImageRequest.Longitude.ToString()), "longitude");
         using (var fileStream = uploadImageRequest.FormFile.OpenReadStream())
         {
             content.Add(new StreamContent(fileStream), "formFile", "image.jpg");
             return(await PostAsync <NodeResponse>($"{_httpClient.BaseAddress}api/Team/UploadImage/", content));
         }
     }
 }
Ejemplo n.º 18
0
        /// <summary>
        /// 本接口 ( UploadImage ) 用于证件图片上传 。
        /// </summary>
        /// <param name="req"><see cref="UploadImageRequest"/></param>
        /// <returns><see cref="UploadImageResponse"/></returns>
        public UploadImageResponse UploadImageSync(UploadImageRequest req)
        {
            JsonResponseModel <UploadImageResponse> rsp = null;

            try
            {
                var strResp = this.InternalRequestSync(req, "UploadImage");
                rsp = JsonConvert.DeserializeObject <JsonResponseModel <UploadImageResponse> >(strResp);
            }
            catch (JsonSerializationException e)
            {
                throw new TencentCloudSDKException(e.Message);
            }
            return(rsp.Response);
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Upload image from the stream.
        /// </summary>
        /// <param name="request">The upload image request.</param>
        /// <returns>The upload image response.</returns>
        public UploadImageResponse Post(UploadImageRequest request)
        {
            MediaFolder parentFolder = null;
            if (request.Data.FolderId.HasValue)
            {
                parentFolder = repository.AsQueryable<MediaFolder>()
                    .Where(c => c.Id == request.Data.FolderId.Value && !c.IsDeleted)
                    .FirstOne();

                if (parentFolder.Type != Module.MediaManager.Models.MediaType.Image)
                {
                    throw new CmsApiValidationException("Folder must be type of an image.");
                }
            }

            var maxLength = configuration.Storage.MaximumFileNameLength > 0 ? configuration.Storage.MaximumFileNameLength : 100;
            // Fix for IIS express + IE (if full path is returned)
            var fileName = Path.GetFileName(request.Data.FileName);
            if (fileName.Length > maxLength)
            {
                fileName = string.Concat(Path.GetFileNameWithoutExtension(fileName.Substring(0, maxLength)), Path.GetExtension(fileName));
            }

            var mediaImage = new MediaImage
            {
                Id = request.Data.Id.GetValueOrDefault(),
                Type = Module.MediaManager.Models.MediaType.Image,
                Caption = request.Data.Caption,
                Title = request.Data.Title ?? fileName,
                Description = request.Data.Description,
                Size = request.Data.FileStream.Length,
                Folder = parentFolder,
                OriginalFileName = fileName,
                OriginalFileExtension = Path.GetExtension(fileName)
            };

            var savedImage = mediaImageService.UploadImageWithStream(request.Data.FileStream, mediaImage, request.Data.WaitForUploadResult);

            if (savedImage != null)
            {
                Events.MediaManagerEvents.Instance.OnMediaFileUploaded(savedImage);
            }

            return new UploadImageResponse
            {
                Data = savedImage.Id,
            };
        }
Ejemplo n.º 20
0
        public async Task <IActionResult> UploadImage([FromForm] UploadImageRequest request)
        {
            if (request.Name == null)
            {
                return(BadRequest(UploadImageResultViewModel.Failure(localizer["NameNotSet"].Value, false, localizer)));
            }
            if (request.Description == null)
            {
                return(BadRequest(UploadImageResultViewModel.Failure(localizer["DescriptionNotSet"].Value, false, localizer)));
            }
            if (request.Source == null)
            {
                return(BadRequest(UploadImageResultViewModel.Failure(localizer["SourceNotSet"].Value, false, localizer)));
            }
            if (request.File == null)
            {
                return(BadRequest(UploadImageResultViewModel.Failure(localizer["FileNotSet"].Value, false, localizer)));
            }

            try
            {
                var user = await userManager.GetUserAsync(HttpContext.User);

                if (user == null)
                {
                    return(BadRequest(UploadImageResultViewModel.Failure(localizer["NeedLogin"].Value, false, localizer)));
                }

                using (var stream = request.File.OpenReadStream())
                    using (var reader = new BinaryReader(stream))
                    {
                        var fileContent        = reader.ReadBytes((int)request.File.Length);
                        var applicationRequest = new StoreImage.Request(user, request.Name, request.Description, request.Source, request.File.ContentType, fileContent);
                        var id = await new StoreImage(dbContext, localizer).RunAsync(applicationRequest);
                        if (id == Guid.Empty)
                        {
                            throw new ApplicationException("Stored image with empty GUID as id");
                        }
                        return(Ok(UploadImageResultViewModel.Success(localizer["ImageSavedWithName"].Value + $" '{applicationRequest.Name}'", localizer)));
                    }
            }
            catch (Exception e)
            {
                return(ControllerError.BadRequest(e, this));
            }
        }
Ejemplo n.º 21
0
        public void UploadImageWithTitle()
        {
            // Arrange
            var formFile           = A.Fake <IFormFile>();
            var uploadImageRequest = new UploadImageRequest()
            {
                FormFile = formFile, GameId = 1, TeamId = 1, Longitude = 15, Latitude = 15, ImageName = "3"
            };

            // Act
            var result = _target.UploadImage(uploadImageRequest);

            // Assert
            Check.That(result).InheritsFrom <IActionResult>();
            A.CallTo(() => _teamService.UploadImage(uploadImageRequest.GameId, uploadImageRequest.TeamId, uploadImageRequest.Latitude, uploadImageRequest.Longitude, A <byte[]> ._, uploadImageRequest.ImageName))
            .MustHaveHappened();
        }
Ejemplo n.º 22
0
        public void UploadImage()
        {
            // Arrange
            var formFile           = A.Fake <IFormFile>();
            var uploadImageRequest = new UploadImageRequest()
            {
                FormFile = formFile, GameId = 1, TeamId = 1, Longitude = 15, Latitude = 15
            };

            // Act
            var result = _target.UploadImage(uploadImageRequest);

            // Assert
            Check.That(result).InheritsFrom <IActionResult>();
            A.CallTo(() => _teamService.UploadImage(A <int> ._, A <int> ._, A <double> ._, A <double> ._, A <byte[]> ._, A <string> ._))
            .MustHaveHappened();
        }
Ejemplo n.º 23
0
        public JsonResult Upload([FromBody] UploadImageRequest requestData)
        {
            List <Task <string> > tasks = new List <Task <string> >();

            foreach (string url in requestData.ImagesUrls)
            {
                tasks.Add(imageUploader.Upload(url));
            }

            Task <string[]> continuation = Task.WhenAll(tasks);

            try
            {
                continuation.Wait();
            }
            catch (AggregateException) {}

            List <string> failed = new List <string>();
            Dictionary <string, UploadedImagesData> uploaded = new Dictionary <string, UploadedImagesData>();

            for (int i = 0; i < tasks.Count; i++)
            {
                if (tasks[i].Status == TaskStatus.RanToCompletion)
                {
                    string originalUrl = "/original/" + tasks[i].Result + ".jpg";
                    string previewUrl  = "/preview/" + tasks[i].Result + ".jpg";

                    uploaded.Add(requestData.ImagesUrls[i], new UploadedImagesData
                    {
                        Original = originalUrl,
                        Preview  = previewUrl
                    });
                }
                else
                {
                    failed.Add(requestData.ImagesUrls[i]);
                }
            }

            return(new JsonResult(new
            {
                Uploaded = uploaded,
                Failed = failed
            }));
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Upload image from the stream.
        /// </summary>
        /// <param name="request">The upload image request.</param>
        /// <returns>The upload image response.</returns>
        public UploadImageResponse Post(UploadImageRequest request)
        {
            IEnumerable <MediaFolder> parentFolderFuture = null;

            if (request.Data.FolderId.HasValue)
            {
                parentFolderFuture = repository.AsQueryable <MediaFolder>()
                                     .Where(c => c.Id == request.Data.FolderId.Value && !c.IsDeleted)
                                     .ToFuture();
            }


            MediaFolder parentFolder = null;

            if (parentFolderFuture != null)
            {
                parentFolder = parentFolderFuture.First();
                if (parentFolder.Type != Module.MediaManager.Models.MediaType.Image)
                {
                    throw new CmsApiValidationException("Folder must be type of an image.");
                }
            }

            var mediaImage = new MediaImage
            {
                Id          = request.Data.Id.GetValueOrDefault(),
                Type        = Module.MediaManager.Models.MediaType.Image,
                Caption     = request.Data.Caption,
                Title       = request.Data.Title,
                Description = request.Data.Description
            };

            var savedImage = mediaImageService.UploadImage(
                parentFolder != null ? parentFolder.Id : Guid.Empty,
                request.Data.FileName,
                request.Data.FileStream.Length,
                request.Data.FileStream,
                Guid.Empty,
                mediaImage);

            return(new UploadImageResponse
            {
                Data = savedImage.Id
            });
        }
Ejemplo n.º 25
0
        public ActionResult Upload(TestUploadViewModel model)
        {
            if (model != null && model.File != null)
            {
                using (var api = ApiFactory.Create())
                {
                    if (model.Type == "file")
                    {
                        var uploadRequest = new UploadFileRequest();
                        uploadRequest.Data.FileStream = model.File.InputStream;
                        uploadRequest.Data.FileName = model.File.FileName;
                        uploadRequest.Data.WaitForUploadResult = model.Method == "sync";

                        var uploadResponse = api.Media.Files.Upload.Post(uploadRequest);

                        var getRequest = new GetFileRequest { FileId = uploadResponse.Data.Value };
                        var getResponse = api.Media.File.Get(getRequest);

                        model.Result = string.Format(
                            "<h2 style='color; green'>File upload successful!</h2> File can be downloaded here: <div><a href='{0}' />{1}</a></div>",
                            getResponse.Data.FileUrl,
                            getResponse.Data.Title);
                    }
                    else
                    {
                        var uploadRequest = new UploadImageRequest();
                        uploadRequest.Data.FileStream = model.File.InputStream;
                        uploadRequest.Data.FileName = model.File.FileName;
                        uploadRequest.Data.WaitForUploadResult = model.Method == "sync";

                        var uploadResponse = api.Media.Images.Upload.Post(uploadRequest);

                        var getRequest = new GetImageRequest { ImageId = uploadResponse.Data.Value };
                        var getResponse = api.Media.Image.Get(getRequest);

                        model.Result = string.Format(
                            "<h2 style='color; green'>Image upload successful!</h2> <div><img src='{0}' alt='{1}' /></div>",
                            getResponse.Data.ImageUrl,
                            getResponse.Data.Title);
                    }
                }
            }

            return View(model);
        }
Ejemplo n.º 26
0
        public async Task UploadImage()
        {
            // Arrange
            byte[] data = new byte[15];
            FakeResponse("ImageHuntWebServiceClientTest.Data.StartTeamFirstNode.json");
            using (var stream = new MemoryStream(Encoding.ASCII.GetBytes("toto")))
            {
                var uploadrequest = new UploadImageRequest()
                {
                    FormFile = new FormFile(stream, 0, stream.Length, "formFile", "toto.txt")
                };
                var response = await _target.UploadImage(uploadrequest);
            }

            // Act
            // Assert
            //A.CallTo(() => _fakeHttpMessageHandler.(A<string>._, A<HttpContent>._, A<CancellationToken>._)).MustHaveHappened();
        }
Ejemplo n.º 27
0
 public Response UploadImage(UploadImageRequest request)
 {
     try
     {
         UploadImageResponse retval = new UploadImageResponseInvalidImageFile();
         var imageUrl = _imageWriter.UploadImage(request.Image);
         if (imageUrl.Result != "")
         {
             retval = new UploadImageResponseOK(imageUrl.Result);
             _dal.UpdateImageUrl(request.DocId, imageUrl.Result);
         }
         return(retval);
     }
     catch (Exception ex)
     {
         return(new ResponseError(ex.Message));
     }
 }
        public async Task <ActionResult <string> > UploadImage([FromBody] UploadImageRequest request)
        {
            try
            {
                var requestUid = await HttpContext.Request.AuthorizeWithFirebase();

                if (requestUid == null)
                {
                    return(Unauthorized());
                }

                return(Ok(await _googleCloudStorage.UploadFile(request)));
            }
            catch (Exception e)
            {
                _logger.LogError(e, "Error uploading file");
                throw;
            }
        }
Ejemplo n.º 29
0
        public async Task <IActionResult> Upload([FromForm] IFormFile file)
        {
            var request = new UploadImageRequest()
            {
                Image    = file,
                Username = User.Identity.Name
            };

            var response = await _images.UploadAsync(request);

            if (!response.Success)
            {
                return(BadRequest(response.ErrorMessage));
            }

            var id = response.Result;

            return(StatusCode(StatusCodes.Status201Created, new { UploadedImageId = id }));
        }
Ejemplo n.º 30
0
        public ServiceResult <IdentityResultCode> SetAvatar(UploadImageRequest request)
        {
            var photo = request.Files.FirstOrDefault();

            if (photo == null || photo.Length == 0)
            {
                return(BuildResult(false, IdentityResultCode.SaveImageFailure, EmptyFileErrorMsg));
            }

            var uploadResult = _blobStorage.UploadPhoto(photo);

            // Todo: update database
            if (uploadResult.IsSuccess)
            {
                return(BuildResult(true, IdentityResultCode.Success, resultObj: uploadResult.JsonObj));
            }

            return(BuildResult(false, IdentityResultCode.SaveImageFailure, uploadResult.ErrorMessage));
        }
Ejemplo n.º 31
0
        public async Task <ImageInfo> MakeAnalysisRequestAsync(UploadImageRequest model)
        {
            var imageInfo = new ImageInfo();

            try
            {
                HttpClient client = new HttpClient();
                // Request headers.
                client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", _computerVisionConfiguration.SubscriptionKey);
                // Assemble the URI for the REST API Call.
                var uri = string.Format("{0}?visualFeatures={1}", _computerVisionConfiguration.ApiUrl, string.Join(",", _requestParams));

                HttpResponseMessage response;

                using (var stream = new MemoryStream())
                {
                    await model.Body.CopyToAsync(stream);

                    var fileContent = stream.ToArray();
                    using (ByteArrayContent content = new ByteArrayContent(fileContent))
                    {
                        // This example uses content type "application/octet-stream".
                        // The other content types you can use are "application/json"
                        // and "multipart/form-data".
                        content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                        // Make the REST API call.
                        response = await client.PostAsync(uri, content);
                    }
                }

                if (response.IsSuccessStatusCode)
                {
                    imageInfo = JsonConvert.DeserializeObject <ImageInfo>(await response.Content.ReadAsStringAsync());
                }
            }
            catch (Exception e)
            {
                throw;
            }

            return(imageInfo);
        }
Ejemplo n.º 32
0
        public async Task <ActionResult <ImageInfo> > Post(UploadImageRequest uploadImageRequest)
        {
            if (!Uri.IsWellFormedUriString(uploadImageRequest.ImageUrl, UriKind.Absolute))
            {
                return(BadRequest(IncorrectUrlFormat));
            }

            _logger.LogDebug(DownloadingByUrl, uploadImageRequest.ImageUrl);

            var imageStream = await _imageDownloadClient.GetMemoryStream(uploadImageRequest.ImageUrl);

            if (imageStream == null)
            {
                return(BadRequestAndLog(string.Format(CouldNotDownloadImage, uploadImageRequest.ImageUrl)));
            }

            _logger.LogDebug(DownloadedByUrl, uploadImageRequest.ImageUrl);

            return(await UploadImage(imageStream, uploadImageRequest.PartitionKey));
        }
Ejemplo n.º 33
0
        /// <summary>
        /// Upload image from the stream.
        /// </summary>
        /// <param name="request">The upload image request.</param>
        /// <returns>The upload image response.</returns>
        public UploadImageResponse Post(UploadImageRequest request)
        {
            MediaFolder parentFolder = null;
            if (request.Data.FolderId.HasValue)
            {
                parentFolder = repository.AsQueryable<MediaFolder>()
                    .Where(c => c.Id == request.Data.FolderId.Value && !c.IsDeleted)
                    .FirstOne();

                if (parentFolder.Type != Module.MediaManager.Models.MediaType.Image)
                {
                    throw new CmsApiValidationException("Folder must be type of an image.");
                }
            }

            var mediaImage = new MediaImage
            {
                Id = request.Data.Id.GetValueOrDefault(),
                Type = Module.MediaManager.Models.MediaType.Image,
                Caption = request.Data.Caption,
                Title = request.Data.Title ?? Path.GetFileName(request.Data.FileName),
                Description = request.Data.Description,
                Size = request.Data.FileStream.Length,
                Folder = parentFolder,
                OriginalFileName = request.Data.FileName,
                OriginalFileExtension = Path.GetExtension(request.Data.FileName)
            };

            var savedImage = mediaImageService.UploadImageWithStream(request.Data.FileStream, mediaImage, request.Data.WaitForUploadResult);

            if (savedImage != null)
            {
                Events.MediaManagerEvents.Instance.OnMediaFileUploaded(savedImage);
            }

            return new UploadImageResponse
            {
                Data = savedImage.Id,
            };
        }