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); }
public async Task UploadImageProgressStream_UploadsImage() { var totalProgress = 0; var apiClient = _fixture.GetApiClientWithKey(); var httpClient = new HttpClient(); var filePath = Path.Combine(Directory.GetCurrentDirectory(), "banana.jpg"); using var fileStream = File.OpenRead(filePath); void report(int progress) { totalProgress += progress; } var uploadProgress = new Progress <int>(report); var imageEndpoint = new ImageEndpoint(apiClient, httpClient); var imageUpload = await imageEndpoint.UploadImageAsync(fileStream, progress : uploadProgress, bufferSize : 4096); var imageDeleted = await imageEndpoint.DeleteImageAsync(imageUpload.DeleteHash); Assert.NotNull(imageUpload); Assert.True(imageDeleted); _output.WriteLine($"{totalProgress} of {fileStream.Length} reported."); }
private async Task UploadImage(ImageViewModel imageViewModel, ImageEndpoint imageEndpoint) { IImage imageData = await imageEndpoint.UploadImageAsync(imageViewModel.Image.OpenReadStream()); imageViewModel.ImagePath = imageData.Link; imageViewModel.ImageId = imageData.Id; }
public async Task GetImageAsync_Equal() { var mockUrl = "https://api.imgur.com/3/image/zVpyzhW"; var mockResponse = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(MockImageEndpointResponses.Imgur.GetImage) }; var client = new ImgurClient("123", "1234"); var endpoint = new ImageEndpoint(client, new HttpClient(new MockHttpMessageHandler(mockUrl, mockResponse))); var image = await endpoint.GetImageAsync("zVpyzhW").ConfigureAwait(false); Assert.NotNull(image); Assert.Equal("zVpyzhW", image.Id); Assert.Equal("Look Mom, it's Bambi!", image.Title); Assert.Equal(null, image.Description); Assert.Equal(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(1440259938), image.DateTime); Assert.Equal("image/gif", image.Type); Assert.Equal(true, image.Animated); Assert.Equal(426, image.Width); Assert.Equal(240, image.Height); Assert.Equal(26270273, image.Size); Assert.Equal(3185896, image.Views); Assert.InRange(image.Bandwidth, 1, long.MaxValue); Assert.Equal(VoteOption.Up, image.Vote); Assert.Equal(false, image.Favorite); Assert.Equal(false, image.Nsfw); Assert.Equal("Eyebleach", image.Section); Assert.Equal("http://i.imgur.com/zVpyzhW.gifv", image.Gifv); Assert.Equal("http://i.imgur.com/zVpyzhW.mp4", image.Mp4); Assert.Equal("http://i.imgur.com/zVpyzhWh.gif", image.Link); Assert.Equal(true, image.Looping); Assert.Equal(true, image.InGallery); Assert.Equal(595876, image.Mp4Size); }
private async Task UploadImageToImgur() { try { uploadingLabel.Visible = true; // Create connection to API var apiClient = new ApiClient("21d68b39c14c68e"); var httpClient = new HttpClient(); // Select image for upload var filePath = photoBrowser.FileName; using var fileStream = File.OpenRead(filePath); // Create end point and upload image var imageEndpoint = new ImageEndpoint(apiClient, httpClient); var imageUpload = await imageEndpoint.UploadImageAsync(fileStream); // Save the image url to the database await SettingController.UpdateImageLink(imageUpload.Link, "account", Account.GetAccountInstance().Id); uploadingLabel.Visible = false; } catch { CustomMessageBox.Show(@"Something went wrong, please try again."); } }
public async Task TestCreateAlbum() { var imgurClient = await AuthenticationHelpers.CreateOAuth2AuthenticatedImgurClient(); var albumEndpoint = new AlbumEndpoint(imgurClient); var imageEndpoint = new ImageEndpoint(imgurClient); var filePath = VariousFunctions.GetTestsAssetDirectory() + @"\upload-image-example.jpg"; var imageBinary = File.ReadAllBytes(filePath); var title = String.Format("dicks-{0}", new Random().Next(100, 1337)); var description = String.Format("black dicks, yo-{0}", new Random().Next(100, 1337)); var uploadedImages = new List <Image>(); for (var i = 0; i < 2; i++) { uploadedImages.Add((await imageEndpoint.UploadImageFromBinaryAsync(imageBinary)).Data); } var createdAlbum = await albumEndpoint.CreateAlbumAsync(uploadedImages.ToArray(), uploadedImages[0], title, description); // Assert the Reponse Assert.IsNotNull(createdAlbum.Data); Assert.AreEqual(createdAlbum.Success, true); Assert.AreEqual(createdAlbum.Status, HttpStatusCode.OK); // Assert the data Assert.AreEqual(createdAlbum.Data.Title, title); Assert.AreEqual(createdAlbum.Data.Description, description); }
public string UploadImage(byte[] msgArray, string user_id, string display_name) { var today = timeService.GetLocalDateTime(LocalTimeService.CHINA_STANDARD_TIME); var client = new ImgurClient(IMGUR_CLIENT_ID, IMGUR_CLIENT_SECRET); var endpoint = new ImageEndpoint(client); IImage image; Stream stream = new MemoryStream(msgArray); using (stream) { image = endpoint.UploadImageStreamAsync(stream).GetAwaiter().GetResult(); } using (var db = new LineModel()) { var instance = new UploadImage { addTime = today, flg = false, imageUrl = image.Link, userId = user_id, userName = display_name }; db.UploadImage.Add(instance); db.SaveChanges(); var status = db.UploadStatus.Where(x => x.UserId == user_id && x.CommandStr == "--upload").ToList(); db.UploadStatus.RemoveRange(status); db.SaveChanges(); } return(image.Link); }
public APIResult TestImgur() { var client = new ImgurClient("2f3ed3db83e866d", "62a894b5e1dd5ed77cc5b4f10eea25e3ebc3e816" , new OAuth2Token("654c446bd2f20543284db4a2d986ea234d81b98b" , "e3100d2d2fc8b14e9131dc1aad5b9a24ca8ee22c" , "bearer" , "132433023" , "frankimg" , 315360000)); var endpoint = new ImageEndpoint(client); var endpointAlbum = new AlbumEndpoint(client); IImage image; bool success = false; //取得圖片檔案FileStream using (var fs = new FileStream(@"D:\Documents\build_school\project\finalProject1\SurvivalGameVer2\SurvivalGame\Assets\images\Product1.png", FileMode.Open)) { image = endpoint.UploadImageStreamAsync(fs).GetAwaiter().GetResult(); success = endpointAlbum.AddAlbumImagesAsync("ZeSZMYK", new List <string>() { image.Id }).GetAwaiter().GetResult(); } return(new APIResult() { IsSuccess = true, //顯示圖檔位置 Data = $"Image uploaded.Image Url: + {image.Link} ,ImgId:{image.Id} ,success: {success}" }); }
public static async Task <IImage> UploadImageAsync(string url, string albumId = null, string name = null, string description = null) { var endpoint = new ImageEndpoint(Client); var image = await endpoint.UploadImageUrlAsync(url, albumId, name, description); return(image); }
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); } }
public async Task UpdateRateLimit_WithImgurClientHeadersAndFakeResponse_Equal() { var mockUrl = "https://api.imgur.com/3/image/zVpyzhW/favorite"; var mockResponse = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(MockImageEndpointResponses.Imgur.FavoriteImageFalse) }; mockResponse.Headers.TryAddWithoutValidation("X-RateLimit-ClientLimit", "123"); mockResponse.Headers.TryAddWithoutValidation("X-RateLimit-ClientRemaining", "345"); var client = new ImgurClient("123", "1234", MockOAuth2Token); var endpoint = new ImageEndpoint(client, new HttpClient(new MockHttpMessageHandler(mockUrl, mockResponse))); await endpoint.FavoriteImageAsync("zVpyzhW").ConfigureAwait(false); Assert.Equal(123, endpoint.ApiClient.RateLimit.ClientLimit); Assert.Equal(345, endpoint.ApiClient.RateLimit.ClientRemaining); mockResponse.Headers.Remove("X-RateLimit-ClientLimit"); mockResponse.Headers.Remove("X-RateLimit-ClientRemaining"); mockResponse.Headers.TryAddWithoutValidation("X-RateLimit-ClientLimit", "122"); mockResponse.Headers.TryAddWithoutValidation("X-RateLimit-ClientRemaining", "344"); await endpoint.FavoriteImageAsync("zVpyzhW").ConfigureAwait(false); Assert.Equal(122, endpoint.ApiClient.RateLimit.ClientLimit); Assert.Equal(344, endpoint.ApiClient.RateLimit.ClientRemaining); }
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); } }
/// <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); } }
public async Task <string> UploadImage(IFormFile image) { try { var clientId = _config.GetSection("ImgurSettings").GetValue <string>("ClientId"); var clientSecret = _config.GetSection("ImgurSettings").GetValue <string>("ClientSecret"); var client = new ImgurClient(clientId, clientSecret); var endpoint = new ImageEndpoint(client); if (image.Length > 0) { var fileStream = image.OpenReadStream(); IImage uploadImage = await endpoint.UploadImageStreamAsync(fileStream); return(uploadImage.Link); } else { throw new ImgurException("Image size = 0"); } } catch (ImgurException imgurEx) { throw imgurEx; } }
public ImgurBackImageResolver(string imgurClientKey) { var apiClient = new ApiClient(imgurClientKey); var httpClient = new HttpClient(); _imageEndpoint = new ImageEndpoint(apiClient, httpClient); }
public async Task <IActionResult> Get(string url = "https://silverdimond.tk") { var imageEndpoint = new ImageEndpoint(ApiClient, HttpClient); var imageUpload = await imageEndpoint.UploadImageAsync(new MemoryStream(await Browser.RenderUrlAsyncAsByteArray(url))); return(Redirect(imageUpload.Link)); }
public async Task TestAddImagesToAlbum() { var imgurClient = await AuthenticationHelpers.CreateOAuth2AuthenticatedImgurClient(); var albumEndpoint = new AlbumEndpoint(imgurClient); var imageEndpoint = new ImageEndpoint(imgurClient); var filePath = VariousFunctions.GetTestsAssetDirectory() + @"\upload-image-example.jpg"; var imageBinary = File.ReadAllBytes(filePath); var createdAlbum = await albumEndpoint.CreateAlbumAsync(); await albumEndpoint.AddImageToAlbumAsync(createdAlbum.Data.Id, (await imageEndpoint.UploadImageFromBinaryAsync(imageBinary)).Data.Id); var updatedAlbum = await albumEndpoint.GetAlbumDetailsAsync(createdAlbum.Data.Id); // Assert the Reponse Assert.IsNotNull(updatedAlbum.Data); Assert.AreEqual(updatedAlbum.Success, true); Assert.AreEqual(updatedAlbum.Status, HttpStatusCode.OK); // Assert the data Assert.AreEqual(createdAlbum.Data.ImagesCount + 1, updatedAlbum.Data.ImagesCount); }
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); } }
private static async Task InitiateClient(bool getPin = true) { if (disable) { return; } var data = File.OpenText(Program.DataPath("imgflip pins", "txt")).ReadToEnd().Split('|'); client = new ImgurClient($"{data[0]}", $"{data[1]}"); end = new OAuth2Endpoint(client); string g = end.GetAuthorizationUrl(Imgur.API.Enums.OAuth2ResponseType.Token); //System.Net.WebClient wc = new System.Net.WebClient(); //byte[] raw = wc.DownloadData(g); //string webData = System.Text.Encoding.UTF8.GetString(raw); //Console.WriteLine(g); //ExtensionMethods.WriteToLog(ExtensionMethods.LogType.CustomMessage, null, g + "\n\n\n" + webData); if (getPin) { token = await end.GetTokenByPinAsync($"{data[2]}"); client.SetOAuth2Token(token); } endpoint = new ImageEndpoint(client); disable = true; }
private async Task <IImage> UploadImageBinary(byte[] bytes) { ImageEndpoint endpoint = new ImageEndpoint(_imgurClient); IImage image = await endpoint.UploadImageBinaryAsync(bytes); return(image); }
public async Task <string> UploadImg2(ImguploadDto dto) { if (dto != null) { //convert base64 to byte[] byte[] imageBytes = Convert.FromBase64String(dto.base64String); //convert byte[] to imgStream // var imgStream = System.Text.Encoding.UTF8.GetString(imageBytes); var imgStream = new MemoryStream(imageBytes); //Imgurapi var apiClient = new ApiClient("0a9f2fb7434821b", "60f9a494f1607de3b90582298fc88c8e29560199"); var httpClient = new HttpClient(); var imageEndpoint = new ImageEndpoint(apiClient, httpClient); var imageUpload = await imageEndpoint.UploadImageAsync(imgStream); return(imageUpload.Link); } else { return("dataURL= null"); } }
private async Task UploadImageToImgur() { try { _isUploaded = false; uploadingLabel.Visible = true; // Create connection to API var apiClient = new ApiClient("21d68b39c14c68e"); var httpClient = new HttpClient(); // Select image for upload var filePath = photoBrowser.FileName; using var fileStream = File.OpenRead(filePath); // Create end point and upload image var imageEndpoint = new ImageEndpoint(apiClient, httpClient); var imageUpload = await imageEndpoint.UploadImageAsync(fileStream); _movie.Picture = imageUpload.Link; _isUploaded = true; uploadingLabel.Visible = false; if (_isNew) { return; } // Save the image url to the database await SettingController.UpdateImageLink(_movie.Picture, "movie", _movie.Id); } catch { uploadingLabel.Visible = false; CustomMessageBox.Show(@"Something went wrong, please try again."); } }
public async Task UploadImageUrlAsync_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.UploadImageUrlAsync("http://i.imgur.com/kiNOcUl.gif").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); }
public async Task <string> UpLoadImg(HttpPostedFile file) { //HttpFileCollection files = HttpContext.Current.Request.Files; //HttpPostedFile file = files[0]; if (file == null || file.ContentLength == 0) { return(null); } try { BinaryReader binaryReader = new BinaryReader(file.InputStream); byte[] byteArray = binaryReader.ReadBytes(file.ContentLength); var apiClient = new ApiClient("7cc84057ff7498d"); var httpClient = new HttpClient(); var imageEndpoint = new ImageEndpoint(apiClient, httpClient); var imageUpload = await imageEndpoint.UploadImageAsync(new MemoryStream(byteArray)); return("成功" + imageUpload.Link); } catch (Exception ex) { return("失敗" + ex.ToString()); } }
/* * public async Task<string> PomfImageUpload(Image<Rgba32> img) * { * string hostUrl = "https://mixtape.moe/upload.php"; * MemoryStream imgStream = new MemoryStream(); * img.Save(imgStream); * imgStream.Seek(0, SeekOrigin.Begin); * using (var client = new HttpClient()) * using (var formData = new MultipartFormDataContent()) * { * formData.Add(new StreamContent(imgStream), "files", "filename.png"); * var resp = await client.PostAsync(hostUrl, formData); * if (resp.IsSuccessStatusCode) * { * string jsonStr = await resp.Content.ReadAsStringAsync(); * var uploadJson = JsonConvert.DeserializeObject<Dictionary<dynamic, dynamic>>(jsonStr); * string uploadUrl = uploadJson["files"][0]["url"]; * Console.WriteLine("Uploaded success to pomf, url is : " + uploadUrl); * return uploadUrl; * } * else * { * Console.WriteLine("Failed upload."); * return ""; * } * } * //string res = await Provider.GetService<HttpService>().Post(hostUrl, $"files: [{imgStream.To}]"); * var uploadJson = JsonConvert.DeserializeObject<Dictionary<dynamic, dynamic>>(res); * string uploadUrl = uploadJson["files"][0]["url"]; * Console.WriteLine("Uploaded success to pomf, url is : " + uploadUrl); * return uploadUrl; * }*/ public async Task <IImage> UploadImage(Image <Rgba32> img) { MemoryStream imgStream = new MemoryStream(); img.Save(imgStream); imgStream.Seek(0, SeekOrigin.Begin); string imgSize = Provider.GetService <MathService>().BytesToNiceSize(imgStream.Length); try { ImgurClient client = new ImgurClient(Provider.GetService <Config>().ImgurClientId, Provider.GetService <Config>().ImgurClientSecret); ImageEndpoint endpoint = new ImageEndpoint(client); IImage imgData = await endpoint.UploadImageStreamAsync(imgStream); ConsoleEx.WriteColoredLine(Discord.LogSeverity.Info, ConsoleTextFormat.TimeAndText, $"Successfully uploaded image to Imgur. [{imgSize}]"); imgStream.Dispose(); return(imgData); } catch (Exception ex) { string failMessage = $"Failed uploading image to Imgur. [{imgSize}];\n{ex.Message}"; ConsoleEx.WriteColoredLine(Discord.LogSeverity.Critical, ConsoleTextFormat.TimeAndText, failMessage); imgStream.Dispose(); return(null); } }
public async Task Upload([Optional] string url) { if (string.IsNullOrWhiteSpace(url)) { url = Context.Message.Attachments.FirstOrDefault().Url; } else if (string.IsNullOrWhiteSpace(url) && Context.Message.Attachments.FirstOrDefault() == null) { await ReplyAsync($"Don't be a Howard! You need to link an image or attach an image!"); } var apiclient = new ApiClient("853f0d7b758b42b", "9c1c12e7e7f370e81e8f49d83b283b52ca04b006"); var httpclient = new HttpClient(); string filename = ""; if (url.EndsWith("f")) { filename = "1.gif"; } else { filename = "1.png"; } webClient.DownloadFile(url, filename); var filepath = $@"{filename}"; using var fileStream = File.OpenRead(filepath); var imageEndpoint = new ImageEndpoint(apiclient, httpclient); var imageUpload = await imageEndpoint.UploadImageAsync(fileStream); await Utilities.SendEmbed(Context.Channel, "Imgur Upload", $"Your image can be found here {imageUpload.Link}", Discord.Color.Blue, "", imageUpload.Link); File.Delete($@"{filename}"); }
public async Task <IHttpActionResult> Upload() { var httpRequest = HttpContext.Current.Request; // var postedFile = httpRequest.Files[file]; if (httpRequest != null) { // ImgstringList = new List<string>(); // var files = Request.files; var File = HttpContext.Current.Request.Files[0]; //Imgurapi var apiClient = new ApiClient("0a9f2fb7434821b", "60f9a494f1607de3b90582298fc88c8e29560199"); var httpClient = new HttpClient(); // var fileName = File.FileName;/*C:\Users\User\source\repos\mikeyeh40709\Xboox\Xboox\Assets\Image\Pics\*/ // session["fileName"]=1 //從這裡開始可以用imgur // var path = Path.Combine(Server.MapPath("../Assets/Pics"), fileName); // files[0].SaveAs(path); var imageEndpoint = new ImageEndpoint(apiClient, httpClient); var imageUpload = await imageEndpoint.UploadImageAsync(File.InputStream); ProductService.GetImg().Add(imageUpload.Link); } //; //return Json($"fileUpload {Session["fileName"]}"); return(Json(ProductService.GetImg())); }
public bool SetFavorite(string id) { var endpoint = new ImageEndpoint(Imgur); endpoint.FavoriteImageAsync(id); return(true); }
public async Task Create(PostBLL post) //post { if (post == null) { throw new Exception("Post is null"); } string path; var rand = new Random(); do { path = @"C:\data\Projects\Finalv2\photo_archive\WebAPI\App_Data\" + rand.Next(1000).ToString() + ".jpg"; }while (File.Exists(path)); string base64 = post.Content.Substring(post.Content.LastIndexOf(',') + 1); File.WriteAllBytes(path, Convert.FromBase64String(base64)); var client = new ImgurClient("", ""); var endpoint = new ImageEndpoint(client); IImage image; using (var fs = new FileStream(path, FileMode.Open)) { image = await endpoint.UploadImageStreamAsync(fs); } post.Url = image.Link; //File.Delete(path); var mapper = new Mapper(BLLtoDAL); Post postDAL = mapper.Map <PostBLL, Post>(post); db.Post.Create(postDAL); db.Save(); }
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); } }