Ejemplo n.º 1
0
        public async Task <string> UploadFileAsync(byte[] file, string fileName = null)
        {
            fileName ??= Guid.NewGuid().ToString();
            using var stream = new MemoryStream(file);
            var uploadParams = new RawUploadParams()
            {
                File = new FileDescription(fileName, stream),
            };

            var result = await this.cloudinary.UploadAsync(uploadParams);

            return(result.SecureUri.AbsoluteUri);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// A convenient method for uploading a raw resource before testing.
        /// </summary>
        /// <param name="setParamsAction">Action to set custom upload parameters.</param>
        /// <param name="type">The type ("raw" or "auto", last by default).</param>
        /// <param name="storageType">The storage type of the asset.</param>
        /// <returns>The upload result.</returns>
        protected RawUploadResult UploadTestRawResource(
            Action <RawUploadParams> setParamsAction = null,
            string type             = "auto",
            StorageType storageType = StorageType.upload)
        {
            var uploadParams = new RawUploadParams();

            setParamsAction?.Invoke(uploadParams);

            PopulateMissingRawUploadParams(uploadParams, false, storageType);

            return(m_cloudinary.Upload(uploadParams, type));
        }
Ejemplo n.º 3
0
        public void RawUploadParams()
        {
            Cloudinary      cloudinary   = TestUtilities.GetCloudinary();
            RawUploadParams uploadParams = new RawUploadParams
            {
                File     = new FileDescription(TestUtilities.GetImagesFolder() + @"\sample_spreadsheet2.xls"),
                PublicId = "sample_spreadsheet2"
            };
            RawUploadResult uploadResult = cloudinary.Upload(uploadParams, "raw");
            string          buildUrl     = cloudinary.Api.UrlImgUp.ResourceType("raw").BuildUrl("sample_spreadsheet2.xls");

            TestUtilities.LogAndWrite(uploadResult, "RawUploadParams.txt");
            TestUtilities.LogAndWrite(buildUrl, "RawUploadParams-buildUrl.txt");
        }
Ejemplo n.º 4
0
        public string UploadCvFileToCloudinary(Stream cvFileStream)
        {
            Account account = new Account
            {
                Cloud     = "alekskn99",
                ApiKey    = "217256488653521",
                ApiSecret = "JNv29i2PKDHUT8hI_861sL8tQ0s",
            };

            Cloudinary cloudinary   = new Cloudinary(account);
            var        uploadParams = new RawUploadParams()
            {
                File = new FileDescription("thrumbnail", cvFileStream),
            };
            var uploadResult = cloudinary.Upload(uploadParams);

            return(uploadResult.SecureUri.AbsoluteUri);
        }
Ejemplo n.º 5
0
        public async Task <IUploadResult <string> > UploadAsync(Stream stream)
        {
            if (stream == null)
            {
                throw new ArgumentNullException(nameof(stream));
            }

            var parameters = new RawUploadParams
            {
                File           = new FileDescription(Guid.NewGuid().ToString("N"), stream),
                Folder         = _configuration.Directory,
                UniqueFilename = true
            };

            var result = await Task.Run(() => _cloudinary.Upload(parameters));

            string thumbnail, small;

            if (result.ResourceType == ResourceType.Video.ToString().ToLower())
            {
                thumbnail = _cloudinary.Api.UrlVideoUp.Transform(new Transformation()
                                                                 .Width(300).Height(300).Crop("fill")).BuildUrl($"{result.PublicId}.{result.Format}");

                small = _cloudinary.Api.UrlVideoUp.Transform(new Transformation()
                                                             .Width(250).Height(250).Crop("crop").Chain()).BuildUrl($"{result.PublicId}.{result.Format}");
            }
            else
            {
                thumbnail = _cloudinary.Api.UrlImgUp.Transform(new Transformation()
                                                               .Width(300).Height(300).Gravity("face").Crop("fill")).BuildUrl($"{result.PublicId}.{result.Format}");

                small = _cloudinary.Api.UrlImgUp.Transform(new Transformation()
                                                           .Width(250).Height(250).Gravity("face").Radius("max").Crop("crop").Chain()
                                                           .Width(125).Crop("scale")).BuildUrl($"{result.PublicId}.{result.Format}");
            }

            return(new CloudinaryUploadResult
            {
                Identifier = result.PublicId,
                OriginalUri = result.Uri.ToString(),
                Thumbnail = thumbnail,
                Small = small
            });
        }
Ejemplo n.º 6
0
        public async Task <IActionResult> AdjuntosRespuesta(int respuestaId, [FromForm] AdjuntosRespuestaDto fileUploadDto)
        {
            var file = fileUploadDto.File;

            var uploadResult = new RawUploadResult();

            if (file.Length > 0)
            {
                using (var stream = file.OpenReadStream())
                {
                    var uploadParams = new RawUploadParams()
                    {
                        // especifico los parametros para guardar el archivo
                        File           = new FileDescription(file.FileName, stream),
                        UseFilename    = true,
                        UniqueFilename = true,
                        Folder         = "TicketsRespuesta"
                    };

                    // Guarda el archivo en la nube
                    uploadResult = _cloudinary.Upload(uploadParams);
                }
            }
            if (uploadResult.StatusCode.ToString() == "OK")
            {
                // mapeo los resultados devueltos
                fileUploadDto.Nombre            = fileUploadDto.File.FileName;
                fileUploadDto.ArchivoUrl        = uploadResult.Uri.ToString();
                fileUploadDto.PublicId          = uploadResult.PublicId;
                fileUploadDto.TicketRespuestaId = respuestaId;
            }
            // mapeo el dto con la clase
            var adTicket = _mapper.Map <AdjuntosRespuesta>(fileUploadDto);

            _context.Add(adTicket);


            if (await _context.SaveChangesAsync() > 0)
            {
                return(Ok());
            }
            throw new Exception("Ocurrio un error al crear el ticket");
        }
        public async Task <string> UploadFile(IFormFile file, string fileName, string extension, string folder = DEAFULT_FOLDER_NAME)
        {
            byte[] destinationData;

            using (var ms = new System.IO.MemoryStream())
            {
                await file.CopyToAsync(ms);

                destinationData = ms.ToArray();
            }

            UploadResult result = null;

            if (extension != ".pptx" && extension != ".docx" && extension != ".pdf")
            {
                using (var ms = new System.IO.MemoryStream(destinationData))
                {
                    ImageUploadParams uploadParams = new ImageUploadParams
                    {
                        Folder = folder,
                        File   = new FileDescription(fileName, ms),
                    };

                    result = this.cloudinaryUtility.Upload(uploadParams);
                }
            }
            else
            {
                using (var ms = new System.IO.MemoryStream(destinationData))
                {
                    RawUploadParams uploadParams = new RawUploadParams
                    {
                        Folder   = folder,
                        File     = new FileDescription(fileName, ms),
                        PublicId = fileName + extension,
                    };

                    result = this.cloudinaryUtility.Upload(uploadParams);
                }
            }

            return(result?.SecureUrl.AbsoluteUri);
        }
        public string PutBlob(Blob blob)
        {
            String path = null;

            using (MemoryStream ms = new MemoryStream())
            {
                ms.Write(blob.Bytes);
                ms.Position = 0;
                FileDescription fileDescription = new FileDescription(blob.Filename, ms);
                RawUploadParams rawUploadParams = new RawUploadParams()
                {
                    File = fileDescription, Folder = blob.Container, Async = "false"
                };
                RawUploadResult result = cloudinary.Upload(rawUploadParams);
                path = result.Uri.AbsoluteUri;
            }

            return(path);
        }
Ejemplo n.º 9
0
        public virtual async Task <string> UploadAsync(Cloudinary cloudinary, IFormFile file)
        {
            byte[] submittedFile;

            using var memoryStream = new MemoryStream();
            await file.CopyToAsync(memoryStream);

            submittedFile = memoryStream.ToArray();

            using var destinationStream = new MemoryStream(submittedFile);
            var uploadParams = new RawUploadParams()
            {
                File = new FileDescription(file.Name, destinationStream),
            };

            var result = await cloudinary.UploadAsync(uploadParams);

            return(result.Uri.AbsoluteUri);
        }
Ejemplo n.º 10
0
        public void TestDestroyRaw()
        {
            RawUploadParams uploadParams = new RawUploadParams()
            {
                File = new FileDescription(m_testImagePath)
            };

            RawUploadResult uploadResult = m_cloudinary.Upload(uploadParams);

            Assert.NotNull(uploadResult);

            DeletionParams destroyParams = new DeletionParams(uploadResult.PublicId)
            {
                ResourceType = ResourceType.Raw
            };

            DeletionResult destroyResult = m_cloudinary.Destroy(destroyParams);

            Assert.AreEqual("ok", destroyResult.Result);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Writes a stream to the blob.
        /// </summary>
        /// <param name="blobName">Virtual blob name.</param>
        /// <param name="blobStream">The <see cref="Stream"/> with data to be writen to the blob.</param>
        public virtual void WriteStream(string blobName, Stream blobStream)
        {
            blobName   = blobName ?? throw new ArgumentNullException(nameof(blobName), nameof(CloudinaryStorageService));
            blobStream = blobStream ?? throw new ArgumentNullException(nameof(blobStream), nameof(CloudinaryStorageService));

            var blobInfo = BlobInfo.FromName(blobName);

            if (blobInfo == null)
            {
                throw new ArgumentException(nameof(CloudinaryStorageService), nameof(blobName));
            }

            var rawUploadParams = new RawUploadParams();

            rawUploadParams.File = new FileDescription(blobName, blobStream);

            rawUploadParams.PublicId = GetPublicId(blobName);

            var result = _client.Upload(rawUploadParams);
        }
Ejemplo n.º 12
0
        public JsonResult LoadBoobs()
        {
            var jsonString   = new WebClient().DownloadString("http://api.oboobs.ru/noise/1");
            var index        = jsonString.IndexOf("noise_preview/");
            var id           = jsonString.Substring(index + 14, 5);
            var uploadParams = new RawUploadParams
            {
                File = new FileDescription("http://media.oboobs.ru/noise/" + id + ".jpg")
            };

            var    uploadResult  = cloudinary.Upload(uploadParams);
            string currentUserId = User.Identity.GetUserId();

            Context.Pictures.Add(new Picture {
                Url = uploadResult.SecureUri.AbsoluteUri, UserId = currentUserId
            });

            Context.SaveChanges();
            return(Json(uploadResult.SecureUri.AbsoluteUri));
        }
        public void TestDestroyRawAsync()
        {
            RawUploadParams uploadParams = new RawUploadParams()
            {
                File = new FileDescription(m_testImagePath),
                Tags = m_apiTag
            };

            RawUploadResult uploadResult = m_cloudinary.UploadAsync(uploadParams, Api.GetCloudinaryParam(ResourceType.Raw)).Result;

            Assert.NotNull(uploadResult);

            DeletionParams destroyParams = new DeletionParams(uploadResult.PublicId)
            {
                ResourceType = ResourceType.Raw
            };

            DeletionResult destroyResult = m_cloudinary.DestroyAsync(destroyParams).Result;

            Assert.AreEqual("ok", destroyResult.Result);
        }
Ejemplo n.º 14
0
        public async Task <string> UploadAsync(IFormFile file, string folderName)
        {
            byte[] destinationImage;

            using (var memoryStream = new MemoryStream())
            {
                await file.CopyToAsync(memoryStream);

                destinationImage = memoryStream.ToArray();
            }

            UploadResult result = null;

            using (var destinationStream = new MemoryStream(destinationImage))
            {
                var uploadParams = new RawUploadParams();

                if (folderName == "book_covers")
                {
                    uploadParams = new ImageUploadParams
                    {
                        Folder = folderName,
                        File   = new FileDescription(file.Name, destinationStream),
                    };
                }
                else
                {
                    uploadParams = new VideoUploadParams
                    {
                        Folder = folderName,
                        File   = new FileDescription(file.Name, destinationStream),
                    };
                }

                result = await this.cloudinary.UploadAsync(uploadParams);
            }

            return(result?.SecureUri.AbsoluteUri);
        }
Ejemplo n.º 15
0
        public async Task <string> UploadFileToCloudinary(string name, Stream fileStream)
        {
            Account account = new Account
            {
                Cloud     = this.configuration.GetSection("Cloudinary").GetSection("cloudName").Value,
                ApiKey    = this.configuration.GetSection("Cloudinary").GetSection("apiKey").Value,
                ApiSecret = this.configuration.GetSection("Cloudinary").GetSection("apiSecret").Value,
            };

            Cloudinary cloudinary = new Cloudinary(account);

            var index = name.LastIndexOf('.');

            name = "file" + name.Substring(index);
            var uploadParams = new RawUploadParams()
            {
                File = new FileDescription(name, fileStream),
            };

            var uploadResult = await cloudinary.UploadAsync(uploadParams);

            return(uploadResult.SecureUri.AbsoluteUri);
        }
Ejemplo n.º 16
0
        public async Task <RawUploadResult> DocumentUpload(IFormFile file)
        {
            try
            {
                Account    account    = new Account(_cloudinaryConfig.Cloud, _cloudinaryConfig.ApiKey, _cloudinaryConfig.ApiSecret);
                Cloudinary cloudinary = new Cloudinary(account);

                //var path = Path.Combine(Directory.GetCurrentDirectory(), "TempFileUpload", file.FileName);
                var path = Path.Combine(_hostingEnvironment.WebRootPath, file.FileName);

                using (var stream = new FileStream(path, FileMode.Create))
                {
                    await file.CopyToAsync(stream);
                }

                //Uploads the Course Images to cloudinary
                var uploadParams = new RawUploadParams()
                {
                    File     = new FileDescription(path),
                    PublicId = "Softlearn/course_materials/" + file.FileName + "",
                };
                var uploadResult = cloudinary.Upload(uploadParams);

                //deletes the file from the "TempFileUplaod" directory if the status of upload result is okay
                if (uploadResult.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    System.IO.File.Delete(path);
                }

                return(uploadResult);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Ejemplo n.º 17
0
        public static async Task <string> UploadImage(Cloudinary cloudinary, IFormFile image, string name)
        {
            if (image != null)
            {
                byte[] destinationImage;
                using (var memoryStream = new MemoryStream())
                {
                    await image.CopyToAsync(memoryStream);

                    destinationImage = memoryStream.ToArray();
                }

                using (var ms = new MemoryStream(destinationImage))
                {
                    // Cloudinary doesn't work with [?, &, #, \, %, <, >]
                    name = name.Replace("&", "And");
                    name = name.Replace("#", "sharp");
                    name = name.Replace("?", "questionMark");
                    name = name.Replace("\\", "right");
                    name = name.Replace("%", "percent");
                    name = name.Replace(">", "greater");
                    name = name.Replace("<", "lower");

                    var uploadParams = new RawUploadParams()
                    {
                        File     = new FileDescription(name, ms),
                        PublicId = name,
                    };

                    var uploadResult = cloudinary.Upload(uploadParams);
                    return(uploadResult.SecureUri.AbsoluteUri);
                }
            }

            return(null);
        }
 public static RawUploadResult Upload(this Cloudinary cloudinary, RawUploadParams parameters, string type = "auto")
 {
     return(cloudinary.UploadAsync(parameters, type).ExecSync());
 }
Ejemplo n.º 19
0
        public void TestCreateArchiveMultipleResourceTypes()
        {
            var raw = ApiShared.GetCloudinaryParam(ResourceType.Raw);

            var tag = GetMethodTag();

            var rawUploadParams = new RawUploadParams()
            {
                File = new FileDescription(m_testPdfPath),
                Tags = $"{tag},{m_apiTag}"
            };

            var upRes1 = m_cloudinary.Upload(rawUploadParams, raw);

            var imageUploadParams = new ImageUploadParams()
            {
                File = new FileDescription(m_testImagePath),
                Tags = $"{tag},{m_apiTag}"
            };

            var upRes2 = m_cloudinary.Upload(imageUploadParams);

            var videoUploadParams = new VideoUploadParams()
            {
                File = new FileDescription(m_testVideoPath),
                Tags = $"{tag},{m_apiTag}"
            };

            var upRes3 = m_cloudinary.Upload(videoUploadParams);

            var fQPublicIds = new List <string>
            {
                upRes1.FullyQualifiedPublicId,
                upRes2.FullyQualifiedPublicId,
                upRes3.FullyQualifiedPublicId
            };

            var parameters = new ArchiveParams()
                             .UseOriginalFilename(true)
                             .TargetTags(new List <string> {
                tag, m_apiTag
            });

            var ex = Assert.Throws <ArgumentException>(() => m_cloudinary.CreateArchive(parameters));

            StringAssert.StartsWith("At least one of the following", ex.Message);

            parameters.ResourceType("auto").Tags(new List <string> {
                "tag"
            });

            ex = Assert.Throws <ArgumentException>(() => m_cloudinary.CreateArchive(parameters));

            StringAssert.StartsWith("To create an archive with multiple types of assets", ex.Message);

            parameters.ResourceType("").Tags(null).FullyQualifiedPublicIds(fQPublicIds);

            ex = Assert.Throws <ArgumentException>(() => m_cloudinary.CreateArchive(parameters));

            StringAssert.StartsWith("To create an archive with multiple types of assets", ex.Message);

            Assert.AreEqual(fQPublicIds, parameters.FullyQualifiedPublicIds());

            parameters.ResourceType("auto");

            var result = m_cloudinary.CreateArchive(parameters);

            Assert.AreEqual(3, result.FileCount);
        }
Ejemplo n.º 20
0
        public async Task <ActionResult> PostFileUploads([FromForm] FileUploadsCreate fileUploads) //[FromForm]
        {
            var    file = fileUploads.File;
            var    uploadResultImage = new ImageUploadResult();
            var    uploadResultRaw   = new RawUploadResult();
            string url;
            string publicId;

            if (file == null || file.Length == 0)
            {
                return(BadRequest("No file provided"));
            }

            if (file.Length > 400000)
            {
                return(BadRequest("File too big. Please resize it."));
            }

            using (var stream = file.OpenReadStream())
            {
                if (file.ContentType.Contains("image"))
                {
                    var uploadParamsImage = new ImageUploadParams()
                    {
                        File           = new FileDescription(file.Name, stream), // Name = "File", seems to work with images
                        Transformation = new Transformation().Width(400),        // this resizes the image maintaining the same aspect ratio
                    };
                    uploadResultImage = _cloudinary.Upload(uploadParamsImage);
                    if (uploadResultImage.Uri == null)
                    {
                        return(BadRequest("Could not upload file. Wrong file type."));
                    }
                    url      = uploadResultImage.Uri.ToString();
                    publicId = uploadResultImage.PublicId;
                }
                else
                {
                    var uploadParams = new RawUploadParams()
                    {
                        File = new FileDescription(file.FileName, stream), // Name = "File", FileName includes file name inc extension
                    };
                    uploadResultRaw = _cloudinary.Upload(uploadParams);
                    if (uploadResultRaw.Uri == null)
                    {
                        return(BadRequest("Could not upload file. Wrong file type."));
                    }
                    url      = uploadResultRaw.Uri.ToString();
                    publicId = uploadResultRaw.PublicId;
                }
            };

            var newFile = new FileUploads
            {
                URL         = url,
                CaseId      = fileUploads.CaseId,
                TimeStamp   = DateTime.Now,
                PublicId    = publicId,
                Description = fileUploads.Description
            };

            try
            {
                _context.FileUploads.Add(newFile);
                await _context.SaveChangesAsync();
            }
            catch
            {
                // error therefore should the uploaded file be deleted?
                return(StatusCode(StatusCodes.Status500InternalServerError));
            }

            return(CreatedAtAction("GetFileUpload", new { id = newFile.Id }, newFile));
        }
Ejemplo n.º 21
0
 public static RawUploadResult UploadLarge(this Cloudinary cloudinary, RawUploadParams parameters, int bufferSize = 20971520)
 {
     return(cloudinary.UploadLarge <RawUploadResult>(parameters, bufferSize));
 }
Ejemplo n.º 22
0
        public ActionResult UploadFile(int?entityId)  // optionally receive values specified with Html helper
        {
            // here we can send in some extra info to be included with the delete url
            var statuses = new List <ViewDataUploadFileResult>();

            for (var i = 0; i < Request.Files.Count; i++)
            {
                var x = new MvcFileSave();
                x.File = Request.Files[i];
                var filePath   = Server.MapPath("~\\" + x.File.FileName);
                var fileStream = System.IO.File.Create(filePath);
                x.File.InputStream.Seek(0, SeekOrigin.Begin);
                x.File.InputStream.CopyTo(fileStream);
                fileStream.Close();
                //BinaryReader b = new BinaryReader(x.File.InputStream);
                //byte[] binImage = b.ReadBytes(Convert.ToInt32(x.File.InputStream.Length));
                //Stream stream = new MemoryStream(binImage);
                var uploadParams = new RawUploadParams
                {
                    File = new FileDescription(filePath)
                };
                var uploadResult = cloudinary.Upload(uploadParams);
                System.IO.File.Delete(filePath);
                x.UrlPrefix = uploadResult.SecureUri.AbsoluteUri;
                string currentUserId = User.Identity.GetUserId();
                Context.Pictures.Add(new Picture {
                    Url = x.UrlPrefix, UserId = currentUserId
                });

                Context.SaveChanges();
                x.FileName        = Request.Files[i].FileName; // default is filename suffixed with filetimestamp
                x.ThrowExceptions = false;                     //default is false, if false exception message is set in error property
                statuses.Add(new ViewDataUploadFileResult
                {
                    FullPath     = x.UrlPrefix,
                    size         = x.File.ContentLength,
                    deleteUrl    = x.DeleteUrl,
                    thumbnailUrl = x.UrlPrefix,
                    url          = x.UrlPrefix,
                    name         = x.FileName
                });
            }

            //statuses contains all the uploaded files details (if error occurs then check error property is not null or empty)
            //todo: add additional code to generate thumbnail for videos, associate files with entities etc

            //adding thumbnail url for jquery file upload javascript plugin
            statuses.ForEach(x => x.thumbnailUrl = x.url);// + " width=300px height=200px"); // uses ImageResizer httpmodule to resize images from this url
            //setting custom download url instead of direct url to file which is default
            statuses.ForEach(x => x.url = Url.Action("DownloadFile", new { fileUrl = x.url, mimetype = x.type }));

            //server side error generation, generate some random error if entity id is 13
            if (entityId == 13)
            {
                var rnd = new Random();
                statuses.ForEach(x =>
                {
                    //setting the error property removes the deleteUrl, thumbnailUrl and url property values
                    x.error = rnd.Next(0, 2) > 0 ? "We do not have any entity with unlucky Id : '13'" : String.Format("Your file size is {0} bytes which is un-acceptable", x.size);
                    //delete file by using FullPath property
                    if (System.IO.File.Exists(x.FullPath))
                    {
                        System.IO.File.Delete(x.FullPath);
                    }
                });
            }

            var viewresult = Json(new { files = statuses });

            //for IE8 which does not accept application/json
            if (Request.Headers["Accept"] != null && !Request.Headers["Accept"].Contains("application/json"))
            {
                viewresult.ContentType = "text/plain";
            }

            return(viewresult);
        }