示例#1
0
        private async Task <IImage> UploadImageBinary(byte[] bytes)
        {
            ImageEndpoint endpoint = new ImageEndpoint(_imgurClient);
            IImage        image    = await endpoint.UploadImageBinaryAsync(bytes);

            return(image);
        }
示例#2
0
        public async Task <string> UploadImageBinaryToImgurAsync(ImgurImageRequest request)
        {
            var imageEndpoint = new ImageEndpoint(_imgurClient);
            var image         = await imageEndpoint.UploadImageBinaryAsync(request.Content, title : request.Title, description : request.Description);

            return(image == null ? null : image.Link);
        }
示例#3
0
        public async Task UploadImageAsync(IList <IFormFile> files)
        {
            try
            {
                ApplicationUser _applicationUser = await _userManager.FindByNameAsync(User.Identity.Name);

                var    client   = new ImgurClient("01bd44056654677", "8a9f05a8ce2dc6321cb64fe735cbc41cdbca02da");
                var    endpoint = new ImageEndpoint(client);
                IImage image;
                foreach (var file in files)
                {
                    if (file.Length > 0)
                    {
                        _applicationUser.AskVerified = true;
                        using (var fileStream = file.OpenReadStream())
                            using (var ms = new MemoryStream())
                            {
                                fileStream.CopyTo(ms);
                                var    fileBytes = ms.ToArray();
                                string s         = Convert.ToBase64String(fileBytes);
                                image = await endpoint.UploadImageBinaryAsync(fileBytes);
                            }
                        Debug.Write("Image uploaded. Image Url: " + image.Link);
                        _applicationUser.ImagePasport = image.Link;
                        await _userManager.UpdateAsync(_applicationUser);
                    }
                }
            }
            catch (ImgurException imgurEx)
            {
                Debug.Write("An error occurred uploading an image to Imgur.");
                Debug.Write(imgurEx.Message);
            }
        }
示例#4
0
        public async Task UploadImageAsync(IList <IFormFile> files)
        {
            try
            {
                var user = await _userManager.GetUserAsync(User);

                var    client   = new ImgurClient("556830a80ac5829", "9438948e5e7df4b5151a61b882626c499ef4925e");
                var    endpoint = new ImageEndpoint(client);
                IImage image;
                foreach (var file in files)
                {
                    if (file.Length > 0)
                    {
                        user.AskVerified = true;
                        using (var fileStream = file.OpenReadStream())
                            using (var ms = new MemoryStream())
                            {
                                fileStream.CopyTo(ms);
                                var    fileBytes = ms.ToArray();
                                string s         = Convert.ToBase64String(fileBytes);
                                image = await endpoint.UploadImageBinaryAsync(fileBytes);
                            }
                        Debug.Write("Image uploaded. Image Url: " + image.Link);
                        user.ProfilePicture = image.Link;
                        await _userManager.UpdateAsync(user);
                    }
                }
            }
            catch (ImgurException imgurEx)
            {
                Debug.Write("An error occurred uploading an image to Imgur.");
                Debug.Write(imgurEx.Message);
            }
        }
示例#5
0
        public async Task UploadImageBinaryAsync_Equal()
        {
            var mockUrl      = "https://api.imgur.com/3/image";
            var mockResponse = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(MockImageEndpointResponses.Imgur.UploadImage)
            };

            var client   = new ImgurClient("123", "1234");
            var endpoint = new ImageEndpoint(client, new HttpClient(new MockHttpMessageHandler(mockUrl, mockResponse)));
            var image    = await endpoint.UploadImageBinaryAsync(new byte[9]).ConfigureAwait(false);

            Assert.NotNull(image);
            Assert.Equal(true, image.Animated);
            Assert.Equal(0, image.Bandwidth);
            Assert.Equal(new DateTimeOffset(new DateTime(2015, 8, 23, 23, 43, 31, DateTimeKind.Utc)), image.DateTime);
            Assert.Equal("nGxOKC9ML6KyTWQ", image.DeleteHash);
            Assert.Equal("Description Test", image.Description);
            Assert.Equal(false, image.Favorite);
            Assert.Equal("http://i.imgur.com/kiNOcUl.gifv", image.Gifv);
            Assert.Equal(189, image.Height);
            Assert.Equal("kiNOcUl", image.Id);
            Assert.Equal("http://i.imgur.com/kiNOcUl.gif", image.Link);
            Assert.Equal(true, image.Looping);
            Assert.Equal("http://i.imgur.com/kiNOcUl.mp4", image.Mp4);
            Assert.Equal("", image.Name);
            Assert.Equal(null, image.Nsfw);
            Assert.Equal(null, image.Section);
            Assert.Equal(1038889, image.Size);
            Assert.Equal("Title Test", image.Title);
            Assert.Equal("image/gif", image.Type);
            Assert.Equal(0, image.Views);
            Assert.Equal(null, image.Vote);
            Assert.Equal(290, image.Width);
        }
        /// <summary>
        /// Uploads image to imgur and returns the display url
        /// </summary>
        /// <param name="fileImage"></param>
        /// <param name="imgurToken"></param>
        /// <returns></returns>
        public static async Task <string> UploadImageAsync(IFormFile fileImage, string imgurToken)
        {
            try
            {
                var token    = new OAuth2Token(imgurToken, "", "", "", "", 0);
                var client   = new ImgurClient(ClientId, ClientSecret, token);
                var endpoint = new ImageEndpoint(client);

                IImage image;

                using (var ms = new MemoryStream())
                {
                    fileImage.CopyTo(ms);
                    image = await endpoint.UploadImageBinaryAsync(ms.ToArray());
                }

                return(image.Link);
            }
            catch (ImgurException ex)
            {
                throw new InvalidOperationException(ex.Message, ex);
            }
            catch (MashapeException ex)
            {
                throw new InvalidOperationException(ex.Message, ex);
            }
            catch (ArgumentNullException ex)
            {
                throw new InvalidOperationException(ex.Message, ex);
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException(ex.Message, ex);
            }
        }
示例#7
0
        public async Task <IImage> UploadImageAsync(IFormFile imageToUpload)
        {
            try
            {
                byte[] imageByteArray;
                await using (var fileStream = imageToUpload.OpenReadStream())
                    await using (var memoryStream = new MemoryStream())
                    {
                        fileStream.CopyTo(memoryStream);
                        imageByteArray = memoryStream.ToArray();
                    }

                var client   = new ImgurClient(_imgurSettings.ClientId);
                var endpoint = new ImageEndpoint(client);
                //var file = File.ReadAllBytes(@"IMAGE_LOCATION");
                var image = await endpoint.UploadImageBinaryAsync(imageByteArray);

                _logger.LogInformation("UserName: {0} | UserId: {1} | Request: {2} | PostMessage: {3}",
                                       _appUser != null ? _appUser.UserName : "******",
                                       _appUser != null ? _appUser.Id : "Null",
                                       _httpContextAccessor.HttpContext.Request.GetRawTarget(),
                                       $"Image was success-fully uploaded.");

                return(image);
            }
            catch (Exception e)
            {
                _logger.LogError("UserName: {0} | UserId: {1} | Request: {2} | PostMessage: {3}",
                                 _appUser != null ? _appUser.UserName : "******",
                                 _appUser != null ? _appUser.Id : "Null",
                                 _httpContextAccessor.HttpContext.Request.GetRawTarget(),
                                 $"Error on uploading picture. Error: {e.Message}; Inner exception: {e.InnerException?.Message}; Stacktrace:\n{e.StackTrace};");
                return(null);
            }
        }
        public async Task UploadImageAsync(IList <IFormFile> files)
        {
            await GetProjectIdAsync();

            try
            {
                var    client   = new ImgurClient("01bd44056654677", "8a9f05a8ce2dc6321cb64fe735cbc41cdbca02da");
                var    endpoint = new ImageEndpoint(client);
                IImage image;
                foreach (var file in files)
                {
                    if (file.Length > 0)
                    {
                        using (var fileStream = file.OpenReadStream())
                            using (var ms = new MemoryStream())
                            {
                                fileStream.CopyTo(ms);
                                var    fileBytes = ms.ToArray();
                                string s         = Convert.ToBase64String(fileBytes);
                                image = await endpoint.UploadImageBinaryAsync(fileBytes);
                            }
                        Debug.Write("Image uploaded. Image Url: " + image.Link);
                        Change_ImageTitle(image.Link);
                    }
                }
            }
            catch (ImgurException imgurEx)
            {
                Debug.Write("An error occurred uploading an image to Imgur.");
                Debug.Write(imgurEx.Message);
            }
        }
示例#9
0
        private static async Task <IImage> SendToImgUr(byte[] file)
        {
            var imgUrClient   = new ImgurClient("CLIENT ID", "CLIENT SECRET");
            var imgUrEndpoint = new ImageEndpoint(imgUrClient);

            var imgUr = await imgUrEndpoint.UploadImageBinaryAsync(file);

            return(imgUr);
        }
示例#10
0
        private static async Task <IImage> Upload(string imgPath)
        {
            var imgUrClient = new ImgurClient("16c839efcf373b3", "9146e6c83a57507b5818e108f78d264dffa06038");
            var endpoint    = new ImageEndpoint(imgUrClient);

            var localImg = File.ReadAllBytes(imgPath);

            var img = await endpoint.UploadImageBinaryAsync(localImg);

            return(img);
        }
 public static async Task <IImage> UploadImage(Image image)
 {
     try {
         var client   = new ImgurClient(Config["imgurClientId"].Value, Config["imgurClientSecret"].Value);
         var endpoint = new ImageEndpoint(client);
         return(await endpoint?.UploadImageBinaryAsync(image.ToByteArray()));
     } catch (ImgurException ie) {
         Debug.WriteLine("An error occured while uploading to ImgurIntegration");
         Debug.WriteLine(ie.Message);
         throw;
     }
 }
示例#12
0
        private async Task <object> Post(IOwinContext context)
        {
            string contentType = context.Request.ContentType;

            if (!contentType.StartsWith("multipart/form-data;"))
            {
                return("error: not multipart form content type");
            }
            object titleValue;
            object fileValue;
            var    form = await MultipartFormParserasdf.ParseMultipartForm(contentType, context.Request.Body);

            if (!form.TryGetValue("title", out titleValue) || !(titleValue is string))
            {
                return("error: missing title");
            }
            if (!form.TryGetValue("file", out fileValue) || !(fileValue is FileUpload))
            {
                return("error: missing file");
            }

            var     session   = context.GetSession();
            var     community = context.GetCommunity();
            Account user      = await community.Accounts.GetBySessionAsync(session);

            if (user == null)
            {
                throw new InvalidOperationException("not logged in");
            }

            string     title = (string)titleValue;
            FileUpload file  = (FileUpload)fileValue;

            if (ConfigurationManager.AppSettings["Imgur.ClientID"] == null)
            {
                throw new InvalidOperationException("Imgur.API not configured");
            }

            var    client   = new ImgurClient(ConfigurationManager.AppSettings["Imgur.ClientID"], ConfigurationManager.AppSettings["Imgur.ClientSecret"]);
            var    endpoint = new ImageEndpoint(client);
            IImage image    = await endpoint.UploadImageBinaryAsync(file.Contents);

            Tech newTech = community.Techs.Create();

            newTech.Owner    = user;
            newTech.Title    = title;
            newTech.ImageUrl = image.Link;
            community.Techs.Add(newTech);
            await community.SaveChangesAsync();

            return(newTech.ID);
        }
示例#13
0
        private void btn_OnClick(object sender, EventArgs eventArgs)
        {
            var title       = FindViewById <EditText>(Resource.Id.txtiTitleUpload);
            var description = FindViewById <EditText>(Resource.Id.txtiDescriptionUpload);
            var endpoint    = new ImageEndpoint(currentUser);
            var file        = System.IO.File.ReadAllBytes(imagePath);

            ThreadPool.QueueUserWorkItem(o => endpoint.UploadImageBinaryAsync(file, title: title.Text, description: description.Text));
            Intent returnIntent = new Intent();

            SetResult(Result.Ok, returnIntent);
            Finish();
        }
示例#14
0
        public static async Task <string> UploadScreenShot(string location)
        {
            const string _secret = "29a9c0cdbda3f744c293b5654bd5dfb974b5ea58";
            const string _id     = "3a282605f7d510e";
            string       url;
            var          client        = new ImgurClient(_id, _secret);
            var          imageEndpoint = new ImageEndpoint(client);
            var          localImage    = File.ReadAllBytes(location);
            var          image         = await imageEndpoint.UploadImageBinaryAsync(localImage);

            url = image.Link;
            return(url);
        }
示例#15
0
        public async Task UploadImageBinaryAsync_WithImageNull_ThrowsArgumentNullException()
        {
            var client   = new ImgurClient("123", "1234");
            var endpoint = new ImageEndpoint(client);

            var exception =
                await
                Record.ExceptionAsync(
                    async() => await endpoint.UploadImageBinaryAsync(null).ConfigureAwait(false))
                .ConfigureAwait(false);

            Assert.NotNull(exception);
            Assert.IsType <ArgumentNullException>(exception);
        }
示例#16
0
 public string UploadImage(byte[] file)
 {
     try
     {
         var    client   = new ImgurClient("1c3d2dc52ecfa75", "157c59d9c9e52a7097376878b4e6b6867d934427");
         var    endpoint = new ImageEndpoint(client);
         IImage image;
         image = endpoint.UploadImageBinaryAsync(file).GetAwaiter().GetResult();
         return(image.Link);
     }
     catch (ImgurException imgurEx)
     {
         return(imgurEx.Message);
     }
 }
        public async Task UploadImageBinaryAsync_WithImage_AreEqual()
        {
            var client   = new ImgurClient(ClientId, ClientSecret);
            var endpoint = new ImageEndpoint(client);

            var file  = File.ReadAllBytes("banana.gif");
            var image = await endpoint.UploadImageBinaryAsync(file, null, "binary test title!", "binary test desc!");

            Assert.IsFalse(string.IsNullOrEmpty(image.Id));
            Assert.AreEqual("binary test title!", image.Title);
            Assert.AreEqual("binary test desc!", image.Description);

            await GetImageAsync_WithImage_AreEqual(image);
            await UpdateImageAsync_WithImage_AreEqual(image);
            await DeleteImageAsync_WithImage_IsTrue(image);
        }
        public async Task <IActionResult> UploadImageAsync(IList <IFormFile> files)
        {
            var id = HttpContext.Request.Query["id"].ToString();

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

                var    client   = new ImgurClient("556830a80ac5829", "9438948e5e7df4b5151a61b882626c499ef4925e");
                var    endpoint = new ImageEndpoint(client);
                IImage image;
                foreach (var file in files)
                {
                    if (file.Length > 0)
                    {
                        user.AskVerified = true;
                        using (var fileStream = file.OpenReadStream())
                            using (var ms = new MemoryStream())
                            {
                                fileStream.CopyTo(ms);
                                var    fileBytes = ms.ToArray();
                                string s         = Convert.ToBase64String(fileBytes);
                                image = await endpoint.UploadImageBinaryAsync(fileBytes);
                            }
                        Debug.Write("Image uploaded. Image Url: " + image.Link);
                        var current = _context.Posts.SingleOrDefault(a => a.Id == id);
                        current.Picture = image.Link;
                        _context.SaveChanges();
                    }
                }
            }
            catch (ImgurException imgurEx)
            {
                Debug.Write("An error occurred uploading an image to Imgur.");
                Debug.Write(imgurEx.Message);
            }
            return(null);
        }
示例#19
0
        public async Task UploadImageBinaryAsync_AreEqual()
        {
            var fakeHttpMessageHandler = new FakeHttpMessageHandler();
            var fakeResponse           = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(ImageEndpointResponses.Imgur.UploadImageResponse)
            };

            fakeHttpMessageHandler.AddFakeResponse(new Uri("https://api.imgur.com/3/image"), fakeResponse);

            var client   = new ImgurClient("123", "1234");
            var endpoint = new ImageEndpoint(client, new HttpClient(fakeHttpMessageHandler));
            var image    = await endpoint.UploadImageBinaryAsync(File.ReadAllBytes("banana.gif"));

            Assert.IsNotNull(image);
            Assert.AreEqual(true, image.Animated);
            Assert.AreEqual(0, image.Bandwidth);
            Assert.AreEqual(new DateTimeOffset(new DateTime(2015, 8, 23, 23, 43, 31, DateTimeKind.Utc)), image.DateTime);
            Assert.AreEqual("nGxOKC9ML6KyTWQ", image.DeleteHash);
            Assert.AreEqual("Description Test", image.Description);
            Assert.AreEqual(false, image.Favorite);
            Assert.AreEqual("http://i.imgur.com/kiNOcUl.gifv", image.Gifv);
            Assert.AreEqual(189, image.Height);
            Assert.AreEqual("kiNOcUl", image.Id);
            Assert.AreEqual("http://i.imgur.com/kiNOcUl.gif", image.Link);
            Assert.AreEqual(true, image.Looping);
            Assert.AreEqual("http://i.imgur.com/kiNOcUl.mp4", image.Mp4);
            Assert.AreEqual("", image.Name);
            Assert.AreEqual(null, image.Nsfw);
            Assert.AreEqual(null, image.Section);
            Assert.AreEqual(1038889, image.Size);
            Assert.AreEqual("Title Test", image.Title);
            Assert.AreEqual("image/gif", image.Type);
            Assert.AreEqual(0, image.Views);
            Assert.AreEqual(null, image.Vote);
            Assert.AreEqual("http://i.imgur.com/kiNOcUl.webm", image.Webm);
            Assert.AreEqual(290, image.Width);
        }
示例#20
0
 public async Task UploadImageBinaryAsync_WithImageNull_ThrowsArgumentNullException()
 {
     var client   = new ImgurClient("123", "1234");
     var endpoint = new ImageEndpoint(client);
     await endpoint.UploadImageBinaryAsync(null);
 }
示例#21
0
        public async Task <IActionResult> UploadFile(string type = "image")
        {
            await CheckIsSignoutedAsync();

            // Get file Upload from HttpRequest FormData
            FileModel postedFile = Request.File();

            // Check has file
            if (postedFile == null)
            {
                throw new ApiException("File không tồn tại, Vui lòng chọn lại file!", (int)HttpStatusCode.BadRequest);
            }

            // is upload image
            if (type == "image")
            {
                postedFile.Name = "image";
                // Extention image
                if (!AcceptedImageFormats.MineTypes.Contains(postedFile.ContentType.ToLower()))
                {
                    throw new ApiException($"File chỉ hỗ trợ định dạng {string.Join(",", AcceptedImageFormats.MineTypes)}", (int)HttpStatusCode.BadRequest);
                }
                // Photo FileSize Upto 10 MB
                if (postedFile.Length > 10 * 1024 * 1024)
                {
                    throw new ApiException("Dung lượng file ảnh không được vượt quá 10 MB!", (int)HttpStatusCode.BadRequest);
                }
            }
            // is upload video
            else if (type == "video")
            {
                postedFile.Name = "video";
                // Extention Video
                if (!AcceptedVideoFormats.MineTypes.Contains(postedFile.ContentType.ToLower()))
                {
                    throw new ApiException($"File chỉ hỗ trợ định dạng {string.Join(",", AcceptedVideoFormats.MineTypes)}", (int)HttpStatusCode.BadRequest);
                }
                // Photo FileSize Upto 10 MB
                if (postedFile.Length > 200 * 1024 * 1024)
                {
                    throw new ApiException("Dung lượng file video không được vượt quá 200 MB!", (int)HttpStatusCode.BadRequest);
                }
            }
            // not support media type
            else
            {
                throw new ApiException("not support media type", (int)HttpStatusCode.BadRequest);
            }

            // Save postedFile to ImgUr API
            try
            {
                var client = new ImgurClient(this.imgUrUploadSettings.ClientID, this.imgUrUploadSettings.ClientSecret);
                // state=#access_token=d9cb9143c19c67696e26f4ac59b2f7424af7650c&expires_in=315360000&token_type=bearer&refresh_token=ddd479acc0fa1b91b099599f864ac0a9afa82801&account_username=ngnamB&account_id=96736173
                var token = new OAuth2Token(
                    accessToken: "d9cb9143c19c67696e26f4ac59b2f7424af7650c",
                    refreshToken: "ddd479acc0fa1b91b099599f864ac0a9afa82801",
                    tokenType: "bearer",
                    accountId: "96736173",
                    accountUsername: "******",
                    expiresIn: 315360000);
                //var endpoint = new OAuth2Endpoint(client);
                //var token = endpoint.GetTokenByRefreshTokenAsync("REFRESH_TOKEN");
                client.SetOAuth2Token(token);
                var albumEndpoint = new AlbumEndpoint(client);
                // https://imgur.com/a/Dsoqayj
                IAlbum album = await albumEndpoint.GetAlbumAsync("Dsoqayj");

                var    imageEndpoint = new ImageEndpoint(client);
                IImage imageOrVideo  = await imageEndpoint.UploadImageBinaryAsync(image : postedFile.Bytes, albumId : album.Id);

                //Debug.Write("Image retrieved. Image Url: " + image.Link);
                return(Ok(imageOrVideo));
            }
            catch (ImgurException imgurEx)
            {
                _logger.LogError("UploadFile---", imgurEx);
#if !DEBUG
                throw new ApiException("An error occurred getting an image from Imgur.");
#else
                throw new ApiException(imgurEx);
#endif
            }
        }