コード例 #1
0
        public async Task ChangeUserPhoto_Fail_WorngFile()
        {
            //Arrange------------------------------------------------------------------------------------------------------------------------------
            string userHimselfId = UnitTestsDataInput.userLogedInId;

            IFormFile file = new FormFile(new MemoryStream(Encoding.UTF8.GetBytes("dummy image")),
                                          0, 0, "Data", "0d47394e-672f-4db7-898c-bfd8f32e2af7.png");

            byte[] data;
            using (var br = new BinaryReader(file.OpenReadStream()))
                data = br.ReadBytes((int)file.OpenReadStream().Length);

            ByteArrayContent         bytes        = new ByteArrayContent(data);
            MultipartFormDataContent multiContent = new MultipartFormDataContent();

            multiContent.Add(bytes, "File", file.FileName);

            var request = new
            {
                Url  = UnitTestsDataInput.baseRouteV1 + "site/panel/users/" + userHimselfId + "/photos",
                Body = UnitTestsDataInput.photoForProfileDto
            };

            multiContent.Add(ContentHelper.GetStringContent(request.Body));

            _client.DefaultRequestHeaders.Authorization
                = new AuthenticationHeaderValue("Bearer", UnitTestsDataInput.aToken);

            //Act----------------------------------------------------------------------------------------------------------------------------------
            var response = await _client.PostAsync(request.Url, multiContent);

            //Assert-------------------------------------------------------------------------------------------------------------------------------
            Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
        }
コード例 #2
0
        public static bool UploadFileToServer(string filePath)
        {
            IFormFile formFile;

            using (var fs = new FileStream(filePath, FileMode.Open))
            {
                formFile = new FormFile(fs, fs.Position, new FileInfo(filePath).Length, "ProcessingDocument", filePath);
                using (var client = new HttpClient())
                {
                    var fileName = formFile.FileName;
                    using (var content = new MultipartFormDataContent())
                    {
                        content.Add(new StreamContent(formFile.OpenReadStream())
                        {
                            Headers =
                            {
                                ContentLength = formFile.Length,
                                ContentType   = new MediaTypeHeaderValue("multipart/form-data")
                            }
                        }, "File", fileName);

                        var response = client.PostAsync("https://localhost:44345/api/uploadfile", content).Result;
                        return(response.IsSuccessStatusCode);
                    }
                }
            }
        }
コード例 #3
0
        /// <summary>
        /// Upload an image to blob storage
        /// OR
        /// Replace it if a file with the provided guid already exists
        /// </summary>
        /// <param name="container">The container to upload the blob to.
        /// Container is an enum.</param>
        /// <param name="formFile">The FormFile object which contains the byte data and meta-data
        /// for the file being uploaded.</param>
        /// <param name="blobName">The guid which will become the blob filename in azure storage.
        /// </param>
        /// <returns>A Image object which contains the guid filename given to the blob in blob storage.
        /// This object also contains the URL that you can use to access the blob file from online.</returns>
        public async Task <Image> UploadOrReplaceImage(ContainerName container, FormFile formFile, Guid blobName)
        {
            CloudBlockBlob blockBlob;

            if (container == ContainerName.Gallery)
            { // check which container to upload the blob to
                blockBlob = _GalleryContainer.GetBlockBlobReference(blobName.ToString());
            }
            else if (container == ContainerName.Log)
            {
                blockBlob = _LogContainer.GetBlockBlobReference(blobName.ToString());
            }
            else
            {
                throw new ArgumentException("Invalid enum ContainerName value", container.ToString());
            }


            blockBlob.Properties.ContentType = formFile.ContentType; // set the new blob's mime type
            // Create or overwrite the blob with the contents of formFile stream
            await blockBlob.UploadFromStreamAsync(formFile.OpenReadStream());

            Image image = new Image
            {
                Url           = blockBlob.StorageUri.PrimaryUri.ToString(),
                Guid          = blobName,
                Filename      = formFile.FileName,
                ContainerName = container
            };

            return(image);
        }
コード例 #4
0
        /// <summary>
        /// UploadFile
        /// </summary>
        /// <param name="File">HttpPostedFileBase</param>
        /// <param name="extension"> ".jpeg" or ".pdf" </param>
        /// <returns></returns>
        public async Task <string> UploadFile(FormFile File, string extension, string endpoint, string token = "")
        {
            try {
                byte[] data;
                var    notification = new Notification();

                using (Stream inputStream = File.OpenReadStream()) {
                    if (!(inputStream is MemoryStream memoryStream))
                    {
                        memoryStream = new MemoryStream();
                        inputStream.CopyTo(memoryStream);
                    }
                    data = memoryStream.ToArray();
                }
                var fileUploadCommand = new FileUpload {
                    Bytes     = data,
                    Extension = extension
                };

                var content = new MultipartFormDataContent();

                var fileContent = new ByteArrayContent(fileUploadCommand.Bytes);
                fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                {
                    FileName = Guid.NewGuid().ToString() + fileUploadCommand.Extension
                };

                content.Add(fileContent);

                using (var client = new HttpClient()) {
                    client.BaseAddress = new Uri(baseUri);
                    client.Timeout     = TimeSpan.FromMinutes(30);
                    client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);

                    var response = await client.PostAsync(endpoint, content);

                    if (response.IsSuccessStatusCode)
                    {
                        notification.Value = await response.Content.ReadAsStringAsync();

                        var message = JsonConvert.DeserializeObject <Notification>(notification.Value);

                        return(message.Value);
                    }
                    else
                    {
                        var result = await response.Content.ReadAsStringAsync();

                        throw new Exception(result);
                    }
                }
            } catch (Exception ex) {
                throw ex;
            }
        }
コード例 #5
0
        public async Task <IActionResult> Create(List <IFormFile> file, [Bind("image_id,image_name,room_image")] Image image)
        {
            long size     = file.Sum(f => f.Length);
            var  filepath = Path.GetTempFileName();

            System.Diagnostics.Debug.WriteLine("im here");
            foreach (var FormFile in file)
            {
                System.Diagnostics.Debug.WriteLine("im in");
                // Check file format
                if (FormFile.ContentType.ToLower() != "image/jpeg" && FormFile.ContentType.ToLower() != "image/png")
                {
                    return(BadRequest("The " + Path.GetFullPath(filepath) + " is not an image file. Please ensure a correct file format is being uploaded."));
                }
                //Check file size whether it is empty or not
                else if (FormFile.Length <= 0)
                {
                    return(BadRequest("The " + Path.GetFileName(filepath) + " is empty. Please ensure a correct file is being uploaded."));
                }
                // Limit the file size to 1MB
                else if (FormFile.Length > 1048576)
                {
                    return(BadRequest("The " + Path.GetFileName(filepath) + " is more than 1 MB. Please ensure the file is less than 1 MB."));
                }
                else
                {
                    CloudBlobContainer container = GetCloudBlobContainer();
                    CloudBlockBlob     blob      = container.GetBlockBlobReference(image.image_name + "-image.jpg");
                    try
                    {
                        using (var fileStream = FormFile.OpenReadStream())
                        {
                            blob.UploadFromStreamAsync(fileStream).Wait();
                        }
                        //Get URL from blob storage
                        image.room_image = blob.Uri.OriginalString;
                        if (ModelState.IsValid)
                        {
                            _context.Add(image);
                            await _context.SaveChangesAsync();

                            return(RedirectToAction(nameof(Index)));
                        }
                        return(View(image));
                    }
                    catch (Exception e)
                    {
                        return(BadRequest("Failed to create" + e));
                    }
                }
            }
            return(View(image));
        }
コード例 #6
0
        public async Task <IActionResult> Create([Bind("ID,Category,Name,Brand,PurchaseDate,Price,WornTimes,ImageUrl,FileName,UserId")] Wardrobe wardrobe, List <IFormFile> files)
        {
            ViewBag.userid = _userManager.GetUserId(HttpContext.User);
            if (ModelState.IsValid)
            {
                //get temporary filepath
                var filepath = Path.GetTempFileName();

                foreach (var FormFile in files)
                {
                    //chack the file
                    if (FormFile.Length <= 0)
                    {
                        TempData["message"] = "Please upload an image file";
                    }

                    //If file is valid proceed to transfer data
                    {
                        //Get the information of the container
                        CloudBlobContainer container = GetCloudBlobContainer();
                        //create the container if not exist in the storage
                        ViewBag.Success           = container.CreateIfNotExistsAsync().Result;
                        ViewBag.BlobContainerName = container.Name; //get the container name

                        //Give a name for the blob
                        CloudBlockBlob blob = container.GetBlockBlobReference(Path.GetFileName(FormFile.FileName));
                        try
                        {
                            using (var stream = FormFile.OpenReadStream())
                            {
                                await blob.UploadFromStreamAsync(stream);
                            }
                        }
                        catch (Exception ex)
                        {
                            TempData["message"] = ex.ToString();
                        }

                        //get uri of the uploaded blob and save in database
                        var blobUrl = blob.Uri.AbsoluteUri;
                        wardrobe.ImageUrl = blobUrl.ToString();
                        wardrobe.FileName = FormFile.FileName.ToString();
                        _context.Add(wardrobe);
                        await _context.SaveChangesAsync();

                        return(RedirectToAction(nameof(Index)));
                    }
                }
                TempData["createmessage"] = "Please upload an image for your clothes";
                return(RedirectToAction(nameof(Create)));
            }
            return(View(wardrobe));
        }
コード例 #7
0
        public async Task <IActionResult> Post(List <IFormFile> files)
        {
            long sizes = files.Sum(f => f.Length);
            var  filepath = Path.GetTempFileName();
            int  i = 1; string contents = "";

            foreach (var FormFile in files)
            {
                //step 1: before pass the file, check the file content type
                if (FormFile.ContentType.ToLower() != "text/plain")
                {
                    return(BadRequest("The " + Path.GetFileName(filepath) +
                                      "is not a text file! Please upload a correct text file"));
                }

                //step 2: chech whether the file is empty anot
                else if (FormFile.Length <= 0)
                {
                    return(BadRequest("The " + Path.GetFileName(filepath) +
                                      "is empty!"));
                }

                //step 3: check file size got over limit anot
                else if (FormFile.Length > 1048576) //more than 1MB
                {
                    return(BadRequest("The " + Path.GetFileName(filepath) +
                                      "is too big!"));
                }
                //step 4: start to transfer the file to the correct destination
                else
                {
                    //e.g file path
                    var filedest = "file path" + i + ".txt";

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

                    //read file
                    using (var reader = new StreamReader(FormFile.OpenReadStream()))

                    {
                        contents = contents + "\\n" + await reader.ReadToEndAsync();
                    }
                }
            }
            TempData["message"] = "Success Transfer" + contents;
            return(RedirectToAction("Index"));
        }
        public async Task <IActionResult> ImportEntities([FromBody] ODataActionParameters request)
        {
            if (!this.ModelState.IsValid || request == null)
            {
                return((IActionResult) new BadRequestObjectResult(this.ModelState));
            }
            if (!request.ContainsKey("importFile") || request["importFile"] == null)
            {
                return((IActionResult) new BadRequestObjectResult((object)request));
            }

            IFormFile    formFile     = (IFormFile)request["importFile"];
            MemoryStream memoryStream = new MemoryStream();

            formFile.CopyTo((Stream)memoryStream);
            FormFile file = new FormFile((Stream)memoryStream, 0L, formFile.Length, formFile.Name, formFile.FileName);

            try
            {
                InitializeEnvironment();

                var sb = new StringBuilder();
                using (var reader = new StreamReader(file.OpenReadStream()))
                {
                    while (reader.Peek() >= 0)
                    {
                        sb.AppendLine(reader.ReadLine());
                    }
                }
                var jsonString = sb.ToString();
                var entities   = JsonConvert.DeserializeObject <EntityCollectionModel>(jsonString, new JsonSerializerSettings {
                    TypeNameHandling = TypeNameHandling.All
                });
                var importEntitiesArgument = new ImportEntitiesArgument(entities);

                var command = this.Command <ImportCommerceEntitiesCommand>();
                var result  = await command.Process(this.CurrentContext, importEntitiesArgument);

                return((IActionResult) new ObjectResult((object)this.ExecuteLongRunningCommand(() => command.Process(this.CurrentContext, importEntitiesArgument))));
            }
            catch (Exception ex)
            {
                return(new ObjectResult(ex));
            }
        }
コード例 #9
0
        public async Task <string> saveImageToBlobStorage(FormFile file)
        {
            var blobName = $"{Guid.NewGuid()}{Path.GetExtension(file.FileName)}";

            blobName = blobName.Replace("\"", "");

            var cloudBlockBlob = blobContainer.GetBlockBlobReference(blobName);

            cloudBlockBlob.Properties.ContentType = file.ContentType;
            cloudBlockBlob.Metadata.Add("origName", file.FileName);

            using (var fileStream = file.OpenReadStream())
            {
                await cloudBlockBlob.UploadFromStreamAsync(fileStream);
            }

            return(blobName);
        }
コード例 #10
0
        // Método para subir los blobs a azure (emulador)
        // Contenedor, imagen, ruta
        public async Task <String> SubirImagen(String archivo, String nombre)
        {
            byte[]    data   = Convert.FromBase64String(archivo);
            var       stream = new MemoryStream(data);
            IFormFile imagen = new FormFile(stream, 0, data.Length, "name", nombre);
            // Recuperamos nuestro contenedor
            CloudBlobContainer container = this.client.GetContainerReference("fotoperfiles");
            // A partir de este contenedor recuperamos el blob, que es una clase de tipo CloudBlockBlob
            CloudBlockBlob blob = container.GetBlockBlobReference(imagen.FileName);

            // Para subir un blob, necesitamos un stream
            using (var str = imagen.OpenReadStream())
            {
                await blob.UploadFromStreamAsync(stream);
            }
            String uri = blob.SnapshotQualifiedUri.AbsoluteUri.Replace("\"", "");

            return(uri);
        }
コード例 #11
0
        public async Task <IActionResult> OnPostUploadAsync()
        {
            if (!ModelState.IsValid)
            {
                await FetchHappinessPerDayViewModel();

                return(Page());
            }

            try
            {
                await using var stream = FormFile.OpenReadStream();
                await _pictureStorageClient.SaveAsync(stream);
            }
            catch (Exception ex)
            {
                _logger.LogError(null, ex);
            }
            return(RedirectToPage());
        }
コード例 #12
0
        public async Task OnPostAsync()
        {
            if (FormFile == null)
            {
                return;
            }

            var request = new PostMeterReadingsRequest();

            try
            {
                using var reader = FormFile.OpenReadStream();
                using var csv    = new CsvReader(new ExcelParser(reader, "in"));
                var meterReadings = csv.GetRecordsAsync <MeterReading>();

                request.MeterReadings = new List <PostMeterReadingsRequest.MeterReading>();

                await foreach (var meterReading in meterReadings)
                {
                    request.MeterReadings.Add(new PostMeterReadingsRequest.MeterReading
                    {
                        AccountId            = meterReading.AccountId,
                        MeterReadValue       = meterReading.MeterReadValue,
                        MeterReadingDateTime = DateTime.Parse(meterReading.MeterReadingDateTime)
                    });
                }
            }
            catch (Exception)
            {
                UploadError = true;
                return;
            }

            var response = await _meterReadingsClient.Upload(request, CancellationToken.None);

            TotalSuccessCount = response.TotalSuccessCount;
            TotalFailCount    = response.TotalFailCount;
        }
コード例 #13
0
        public ObjectId saveSRTBucket(string srtPath)
        {
            using (var stream = File.OpenRead(srtPath))
            {
                FormFile formFile = new FormFile(stream, 0, stream.Length, "SrtFile", Path.GetFileName(stream.Name))
                {
                    Headers     = new HeaderDictionary(),
                    ContentType = "text/srt"
                };

                //get the bytes from the content stream of the file
                byte[] theFileAsBytes = new byte[formFile.Length];
                using (BinaryReader theReader = new BinaryReader(formFile.OpenReadStream()))
                {
                    theFileAsBytes = theReader.ReadBytes((int)formFile.Length);
                }

                //כיון ששמירת קבצים במונגו נשמר באחסון GridFSBucket  בתוך המונגו
                ObjectId srtFile = bucket.UploadFromBytes(formFile.FileName, theFileAsBytes);

                return(srtFile);
            }
        }
コード例 #14
0
        public async Task <ActionResult> AddLocatedImage([FromBody] LocatedImageDto locatedImageDto)
        {
            var locationDto = locatedImageDto.LocationDto;

            var       byteArray    = Convert.FromBase64String(locatedImageDto.Base64);
            var       memoryStream = new MemoryStream(byteArray);
            IFormFile file         = new FormFile(memoryStream, 0, byteArray.Length, "name", "fileName.jpg");

            if (file.Length > 0 && locationDto != null)
            {
                var randomName = GetRandomBlobName(file.FileName);
                var blob       = _blobContainer.GetBlockBlobReference(randomName);

                using (var stream = file.OpenReadStream())
                {
                    await blob.UploadFromStreamAsync(stream);
                }
                var user          = _context.Users.SingleOrDefault(u => u.Id == Convert.ToInt64(locatedImageDto.UserId));
                var imageLocation = new ImageLocation()
                {
                    Uri       = blob.Uri.ToString(),
                    Latitude  = locationDto.Latitude,
                    Longitude = locationDto.Longitude,
                    User      = user,
                    UserId    = Convert.ToInt64(locatedImageDto.UserId)
                };

                _context.ImageLocations.Add(imageLocation);
                _context.SaveChanges();
                return(Ok());
            }
            else
            {
                return(NoContent());
            }
        }
コード例 #15
0
        public async Task <IActionResult> Edit(int id, [Bind("ID,Category,Name,Brand,PurchaseDate,Price,WornTimes,ImageUrl,FileName,UserId")] Wardrobe wardrobe, List <IFormFile> files, string filename)
        {
            if (id != wardrobe.ID)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                var filepath = Path.GetTempFileName();

                foreach (var FormFile in files)
                {
                    if (FormFile.Length <= 0)
                    {
                        TempData["editmessage"] = "Please upload a proper image file";
                    }

                    else
                    {
                        if (filename != null)
                        {
                            //delete file from blob
                            CloudBlobContainer container1 = GetCloudBlobContainer();
                            CloudBlockBlob     blobfile   = container1.GetBlockBlobReference(filename);
                            string             name       = blobfile.Name;
                            var result = blobfile.DeleteIfExistsAsync().Result;

                            if (result == false)
                            {
                                TempData["message"] = "Unable to delete file";
                            }
                            else
                            {
                                TempData["message"] = "File is deleted";
                            }
                        }
                        //first all, get the container information
                        CloudBlobContainer container = GetCloudBlobContainer();
                        //give a name for the blob
                        CloudBlockBlob blob = container.GetBlockBlobReference(Path.GetFileName(FormFile.FileName));
                        try
                        {
                            using (var stream = FormFile.OpenReadStream())
                            {
                                await blob.UploadFromStreamAsync(stream);
                            }
                        }
                        catch (Exception ex)
                        {
                            TempData["message"] = ex.ToString();
                        }

                        // get the uri of the specific uploaded blob and save it
                        var blobUrl = blob.Uri.AbsoluteUri;
                        wardrobe.ImageUrl = blobUrl.ToString();
                        wardrobe.FileName = FormFile.FileName.ToString();
                        _context.Update(wardrobe);
                        await _context.SaveChangesAsync();

                        return(RedirectToAction(nameof(Index)));
                    }
                }
                try
                {
                    _context.Update(wardrobe);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!WardrobeExists(wardrobe.ID))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            return(View(wardrobe));
        }
コード例 #16
0
        public ActionResult <string> Create
            (Caterer model)
        {
            string json = null;

            var stream2 = new MemoryStream(model.Document);

            IFormFile file = new FormFile(stream2, 0, model.Document.Length, "name", "filename.xlsx");


            string folderName = "UploadExcel";
            //string webRootPath = _hostingEnvironment.WebRootPath;
            //string newPath = Path.Combine(webRootPath, folderName);
            StringBuilder sb = new StringBuilder();
            //if (!Directory.Exists(newPath))
            //{
            //    Directory.CreateDirectory(newPath);
            //}


            string        sFileExtension   = Path.GetExtension(file.FileName).ToLower();
            List <string> ItemLista        = new List <string>();
            List <string> IngredientsLista = new List <string>();

            if (file.Length > 0)
            {
                ISheet sheet;



                using (var stream = file.OpenReadStream())
                {
                    //json = ReadExcelasJSON(stream);
                    stream.Position = 0;
                    if (sFileExtension == ".xls")
                    {
                        HSSFWorkbook hssfwb = new HSSFWorkbook(stream); //This will read the Excel 97-2000 formats
                        sheet = hssfwb.GetSheetAt(0);                   //get first sheet from workbook
                    }
                    else
                    {
                        XSSFWorkbook hssfwb = new XSSFWorkbook(stream); //This will read 2007 Excel format
                        sheet = hssfwb.GetSheetAt(0);                   //get first sheet from workbook
                    }
                    IRow headerRow = sheet.GetRow(0);                   //Get Header Row
                    int  cellCount = headerRow.LastCellNum;
                    sb.Append("<table class='table table-bordered'><tr>");
                    for (int j = 0; j < cellCount; j++)
                    {
                        NPOI.SS.UserModel.ICell cell = headerRow.GetCell(j);
                        if (cell == null || string.IsNullOrWhiteSpace(cell.ToString()))
                        {
                            continue;
                        }
                        sb.Append("<th>" + cell.ToString() + "</th>");
                    }
                    sb.Append("</tr>");
                    sb.AppendLine("<tr>");
                    for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++) //Read Excel File
                    {
                        IRow row = sheet.GetRow(i);
                        if (row == null)
                        {
                            continue;
                        }
                        if (row.Cells.All(d => d.CellType == NPOI.SS.UserModel.CellType.Blank))
                        {
                            continue;
                        }
                        for (int j = row.FirstCellNum; j < cellCount; j++)
                        {
                            if (row.GetCell(j) != null)
                            {
                                sb.Append("<td>" + row.GetCell(j).ToString() + "</td>");
                            }
                        }
                        sb.AppendLine("</tr>");
                    }
                    sb.Append("</table>");
                }
            }
            //return this.Content(sb.ToString());

            List <string> testLista2 = ItemLista;

            return(sb.ToString());
        }
コード例 #17
0
        private Task <Result <Image> > ConvertAndUpload(Image dbImage, FormFile uploadedFile)
        {
            return(GetBytes()
                   .Ensure(AreDimensionsValid,
                           $"Uploading image size must be at least {MinimumImageWidth}×{MinimumImageHeight} pixels and the width mustn't exceed two heights and vice versa")
                   .Bind(Convert)
                   .Bind(Upload));


            Result <byte[]> GetBytes()
            {
                using var binaryReader = new BinaryReader(uploadedFile.OpenReadStream());
                return(Result.Success(binaryReader.ReadBytes((int)uploadedFile.Length)));
            }

            async Task <bool> AreDimensionsValid(byte[] imageBytes)
            {
                var info = await ImageJob.GetImageInfo(new BytesSource(imageBytes));

                return(MinimumImageWidth <= info.ImageWidth &&
                       MinimumImageHeight <= info.ImageHeight &&
                       info.ImageWidth / info.ImageHeight < 2 &&
                       info.ImageHeight / info.ImageWidth < 2);
            }

            async Task <Result <ImageSet> > Convert(byte[] imageBytes)
            {
                var imagesSet = new ImageSet();

                using var imageJob = new ImageJob();
                var jobResult = await imageJob.Decode(imageBytes)
                                .Constrain(new Constraint(ConstraintMode.Within, ResizedLargeImageMaximumSideSize, ResizedLargeImageMaximumSideSize))
                                .Branch(f => f.ConstrainWithin(ResizedSmallImageMaximumSideSize, ResizedSmallImageMaximumSideSize).EncodeToBytes(new MozJpegEncoder(TargetJpegQuality, true)))
                                .EncodeToBytes(new MozJpegEncoder(TargetJpegQuality, true))
                                .Finish().InProcessAsync();

                imagesSet.SmallImage = GetImage(1);
                imagesSet.MainImage  = GetImage(2);

                return(imagesSet.MainImage.Any() && imagesSet.SmallImage.Any()
                    ? Result.Success(imagesSet)
                    : Result.Failure <ImageSet>("Processing of the images failed"));


                byte[] GetImage(int index)
                {
                    var encodeResult = jobResult?.TryGet(index);
                    var bytes        = encodeResult?.TryGetBytes();

                    return(bytes != null?bytes.Value.ToArray() : new byte[]
                    {
                    });
                }
            }

            async Task <Result <Image> > Upload(ImageSet imageSet)
            {
                dbImage.Position = _dbContext.Images.Count(i => i.ReferenceId == dbImage.ReferenceId && i.ImageType == dbImage.ImageType);
                var entry = _dbContext.Images.Add(dbImage);
                await _dbContext.SaveChangesAsync();

                var imageId = entry.Entity.Id;

                SetImageKeys();

                var addToBucketResult = await AddImagesToBucket();

                if (!addToBucketResult)
                {
                    _dbContext.Images.Remove(entry.Entity);

                    await _dbContext.SaveChangesAsync();

                    return(Result.Failure <Image>("Uploading of the image failed"));
                }

                _dbContext.Images.Update(entry.Entity);

                await _dbContext.SaveChangesAsync();

                _dbContext.DetachEntry(entry.Entity);

                return(Result.Success(dbImage));


                void SetImageKeys()
                {
                    var basePartOfKey = $"{S3FolderName}/{dbImage.ServiceSupplierId}/{imageId}";

                    dbImage.Keys.MainImage  = $"{basePartOfKey}-main.jpg";
                    dbImage.Keys.SmallImage = $"{basePartOfKey}-small.jpg";
                }

                async Task <bool> AddImagesToBucket()
                {
                    await using var largeStream = new MemoryStream(imageSet.MainImage);
                    await using var smallStream = new MemoryStream(imageSet.SmallImage);
                    var imageList = new List <(string key, Stream stream)>
                    {
                        (dbImage.Keys.MainImage, largeStream),
                        (dbImage.Keys.SmallImage, smallStream)
                    };

                    var resultList = await _amazonS3ClientService.Add(_bucketName, imageList);

                    foreach (var result in resultList)
                    {
                        if (result.IsFailure)
                        {
                            var keyList = new List <string>
                            {
                                dbImage.Keys.MainImage,
                                dbImage.Keys.SmallImage
                            };
                            await _amazonS3ClientService.Delete(_bucketName, keyList);

                            return(false);
                        }
                    }

                    return(true);
                }
            }
        }
コード例 #18
0
ファイル: Utilities.cs プロジェクト: OICAR/PacketMenuApp
        //public static Tuple<List<string>, List<string>> ReturnMultipleList(int[] array, int number)
        //{
        //    return Tuple.Create(list1, list2);
        //}



        public static List <Item> CreateItem(Caterer model)
        {
            _tempList = new List <Item>();
            _temp     = new Item();
            string json = null;

            var stream2 = new MemoryStream(model.Document);

            IFormFile file = new FormFile(stream2, 0, model.Document.Length, "name", "filename.xlsx");


            string folderName = "UploadExcel";

            string        sFileExtension   = Path.GetExtension(file.FileName).ToLower();
            List <string> ItemLista        = new List <string>();
            List <string> IngredientsLista = new List <string>();

            if (file.Length > 0)
            {
                ISheet sheet;


                using (var stream = file.OpenReadStream())
                {
                    //json = ReadExcelasJSON(stream);
                    stream.Position = 0;
                    if (sFileExtension == ".xls")
                    {
                        HSSFWorkbook hssfwb = new HSSFWorkbook(stream); //This will read the Excel 97-2000 formats
                        sheet = hssfwb.GetSheetAt(0);                   //get first sheet from workbook
                    }
                    else
                    {
                        XSSFWorkbook hssfwb = new XSSFWorkbook(stream); //This will read 2007 Excel format
                        sheet = hssfwb.GetSheetAt(0);                   //get first sheet from workbook
                    }
                    IRow headerRow = sheet.GetRow(0);                   //Get Header Row
                    int  cellCount = headerRow.LastCellNum;

                    for (int j = 0; j < cellCount; j++)
                    {
                        NPOI.SS.UserModel.ICell cell = headerRow.GetCell(j);
                        if (cell == null || string.IsNullOrWhiteSpace(cell.ToString()))
                        {
                            continue;
                        }
                    }

                    for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++) //Read Excel File
                    {
                        IRow row = sheet.GetRow(i);
                        if (row == null)
                        {
                            continue;
                        }
                        if (row.Cells.All(d => d.CellType == NPOI.SS.UserModel.CellType.Blank))
                        {
                            continue;
                        }
                        for (int celNumber = row.FirstCellNum; celNumber < cellCount; celNumber++)
                        {
                            if (row.GetCell(celNumber) != null)
                            {
                                var data = row.GetCell(celNumber).ToString();


                                switch (celNumber)
                                {
                                case 0:

                                    _temp.Name = data;
                                    break;

                                case 1:
                                    _temp.Price = int.Parse(data);

                                    break;

                                case 2:
                                    _temp.Ingredents = parseToList(data, _DELIMITER);
                                    break;

                                default:
                                    return(null);
                                }
                            }
                        }

                        _tempList.Add(_temp);
                    }
                }
            }
            return(_tempList);
        }
コード例 #19
0
        public async Task Invoke(HttpContext context)
        {
            HttpRequest request = context.Request;
            FormFile    file    = null;

            try
            {
                file = (FormFile)request.Form.Files["data"];
            }
            catch (InvalidOperationException)
            {
                // Do nothing because the file isn't available
                // and that doesn't necessary indicate an error.
                // TODO: Find a better solution for this...
            }

            if (file != null)
            {
                Boolean compression = request.Form["c"] == "1";
                Stream  newBody     = file.OpenReadStream();

                if (compression)
                {
                    // GZipStream cannot be reused, so I need to copy the data out of it
                    using (GZipStream gzipStream = new GZipStream(newBody, CompressionMode.Decompress))
                    {
                        newBody = new MemoryStream();
                        await gzipStream.CopyToAsync(newBody);

                        newBody.Seek(0, SeekOrigin.Begin);
                    }
                }

                // The client doesn't inform us of the datatype of the data sent.
                // So I need to attempt to decode the data as JSON, and if it fails, then
                // assume the data is binary.
                try
                {
                    using (var reader = new StreamReader(newBody,
                                                         Encoding.UTF8,
                                                         false,
                                                         1024,
                                                         true
                                                         ))
                    {
                        JToken.ReadFrom(new JsonTextReader(reader));
                    }

                    request.ContentType = "application/json";
                }
                catch (JsonReaderException jex)
                {
                    Console.WriteLine(jex.Message);
                }
                finally
                {
                    newBody.Seek(0, SeekOrigin.Begin);
                }

                context.Request.Body = newBody;
            }

            await _next(context);
        }