public async Task <string> ToBase64StringAsync(IBrowserFile file)
        {
            byte[] buffer = new byte[file.Size];
            await file.OpenReadStream().ReadAsync(buffer);

            return($"data:{file.ContentType};base64,{Convert.ToBase64String(buffer)}");
        }
Пример #2
0
        public async Task <string> UploadFile(IBrowserFile file)
        {
            try
            {
                FileInfo fileInfo        = new FileInfo(file.Name);
                var      fileName        = Guid.NewGuid().ToString() + fileInfo.Extension;
                var      folderDirectory = $"{webHostEnvironment.WebRootPath}\\{imageFolder}";
                var      path            = Path.Combine(webHostEnvironment.WebRootPath, imageFolder, fileName);

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

                if (!Directory.Exists(folderDirectory))
                {
                    Directory.CreateDirectory(folderDirectory);
                }

                await using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write))
                {
                    memoryStream.WriteTo(fs);
                }

                var url      = $"{httpContextAccessor.HttpContext.Request.Scheme}://{httpContextAccessor.HttpContext.Request.Host.Value}/";
                var fullPath = $"{url}{imageFolder}/{fileName}";
                return(fullPath);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Пример #3
0
        public async Task <string> UploadFile(IBrowserFile file)
        {
            try
            {
                FileInfo fileInfo  = new FileInfo(file.Name);
                var      fileName  = Guid.NewGuid().ToString() + fileInfo.Extension;
                var      folderDir = $"{_webHostEnvironment.WebRootPath}\\RoomImages";
                var      path      = Path.Combine(_webHostEnvironment.WebRootPath, "RoomImages", fileName);

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

                if (!Directory.Exists(folderDir))
                {
                    Directory.CreateDirectory(folderDir);
                }

                await using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write))
                {
                    memoryStream.WriteTo(fs);
                }

                var fullPath = $"RoomImages/{fileName}";
                return(fullPath);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Пример #4
0
        protected async Task HandleFileSelection(InputFileChangeEventArgs e)
        {
            file          = e.File;
            isFileChanged = true;
            if (file != null)
            {
                var ext = Path.GetExtension(file.Name);
                if (ext.Contains("jpg") || ext.Contains("png") || ext.Contains("jpeg") || ext.Contains("pdf"))
                {
                    msFile = file.OpenReadStream();

                    var resizedImageFile = await file.RequestImageFileAsync("image/png", 100, 100);

                    var buffer = new byte[resizedImageFile.Size];
                    await resizedImageFile.OpenReadStream().ReadAsync(buffer);

                    var imageBase64Data = Convert.ToBase64String(buffer);
                    imageDataURL      = string.Format("data:image/png;base64,{0}", imageBase64Data);
                    isInvalidFileType = false;
                }
                else
                {
                    isInvalidFileType = true;
                    imageDataURL      = string.Empty;
                }
            }
            else
            {
                isInvalidFileType = false;
            }
        }
Пример #5
0
        private async Task SubmitProfileImageForm(IBrowserFile file)
        {
            videoSaved = false;

            fileName = file.Name;
            stream   = file.OpenReadStream();

            imageSource = Base64ImageEncoder.EncodeImage(stream, file.ContentType);

            if (!string.IsNullOrEmpty(Id))
            {
                try
                {
                    var imageUrl = await ConsultantProfilesClient.UploadProfileImageAsync(Guid.Parse(Id), new FileParameter(stream, fileName));

                    consultant.ProfileImage = imageUrl;

                    videoSaved = true;

                    await imageUploadModal.Close();
                }

                /* catch (ApiException exc)
                 * {
                 * }
                 * catch (HttpRequestException exc)
                 * {
                 * } */
                catch (Exception exc)
                {
                    await JSHelpers.Alert(exc.Message);
                }
            }
        }
        /**
         * upload the file as a static file to our server
         */
        public async Task <string> UploadFile(IBrowserFile file)
        {
            try
            {
                FileInfo fileInfo        = new FileInfo(file.Name);
                var      fileName        = Guid.NewGuid().ToString() + fileInfo.Extension;
                var      folderDirectory = $"{_webHostEnvironment.WebRootPath}/RoomImages";
                var      path            = Path.Combine(_webHostEnvironment.WebRootPath, "RoomImages", fileName);

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

                // create the folder if it doesnt exist - this will run for the first ever image uploaded
                if (!Directory.Exists(folderDirectory))
                {
                    Directory.CreateDirectory(folderDirectory);
                }

                // use the memory stream to write the file into the folder
                await using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write))
                {
                    memoryStream.WriteTo(fs);
                }

                var fullPath = $"RoomImages/{fileName}";
                return(fullPath);
            }
            catch (Exception e)
            {
                throw e;
            }
        }
        public static async Task <string> ReadStreamAsync(this IBrowserFile file)
        {
            var buffer = new byte[file.Size];
            await file.OpenReadStream(MaxFileSize).ReadAsync(buffer);

            return(Convert.ToBase64String(buffer));
        }
Пример #8
0
        public async Task UploadEncounters(IBrowserFile file)
        {
            try
            {
                var ms = new MemoryStream();
                await file.OpenReadStream().CopyToAsync(ms);

                var json = System.Text.Encoding.ASCII.GetString(ms.ToArray());

                var options = new JsonSerializerOptions {
                    PropertyNameCaseInsensitive = true
                };

                var upload = JsonSerializer.Deserialize <FileUpload>(json, options);

                var sort = upload.Encounters.OrderBy(a => a.Name).ToList();

                _bank.Encounters = sort;

                Notify();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        public async Task WriteToStreamAsync(Stream stream)
        {
            var buffer = new byte[fileUploadEntry.Size];

            await fileUploadEntry.OpenReadStream(104857600).ReadAsync(buffer);

            await stream.WriteAsync(buffer);
        }
Пример #10
0
        static async Task <string> ConvertFileToBase64Async(IBrowserFile file, CancellationToken ct = default)
        {
            var buffer = new byte[file.Size];

            await file
            .OpenReadStream(maxFileSize, ct)
            .ReadAsync(buffer, ct);

            return(Convert.ToBase64String(buffer));
        }
Пример #11
0
        private static async Task <byte[]> ConvertStreamToByteArray(IBrowserFile file)
        {
            await using var stream       = file.OpenReadStream();
            await using var memoryStream = new MemoryStream();
            {
                await stream.CopyToAsync(memoryStream);

                return(memoryStream.ToArray());
            }
        }
        private async Task UploadToBlobAsync()
        {
            using var stream = selectedFile.OpenReadStream();
            var content = new StreamContent(stream);

            content.Headers.Add("type", selectedFile.ContentType);
            await HttpClient.PostAsync($"api/uploadData/{selectedFile.Name}", content);

            await PullListAsync();
        }
Пример #13
0
        public async Task <List <Rectangle> > GetRectAsync(IBrowserFile file)
        {
            ms.Close();
            ms = new MemoryStream();
            var t = file.OpenReadStream(file.Size);
            await t.CopyToAsync(ms);

            List <Rectangle> rects = ac.GetRectangles(ms);

            return(rects);
        }
Пример #14
0
        private async Task UploadFileToWebRoot(IBrowserFile files)
        {
            Stream stream = files.OpenReadStream();
            var    path   = $"{WebHostEnvironment.WebRootPath}\\files\\{files.Name}";

            FileStream fileStream = File.Create(path);
            await stream.CopyToAsync(fileStream);

            stream.Close();
            fileStream.Close();
        }
Пример #15
0
        private static async Task <string> ReadStringFromFile(InputFileChangeEventArgs e)
        {
            IBrowserFile file     = e.File;
            long         fileSize = file.Size;

            byte[] buffer = new byte[fileSize];
            await file.OpenReadStream().ReadAsync(buffer);

            var str = Encoding.Default.GetString(buffer);

            return(str.Trim().Trim(new char[] { '\uFEFF' }));
        }
Пример #16
0
        public static async Task <List <T> > ReadCsv <T>(ICsvMapping <T> mapping, IBrowserFile file)
        {
            CsvParserOptions csvParserOptions = new CsvParserOptions(true, ',');
            CsvParser <T>    csvParser        = new CsvParser <T>(csvParserOptions, mapping);

            using var reader = new StreamReader(file.OpenReadStream());
            var line = await reader.ReadToEndAsync();

            CsvReaderOptions csvReaderOptions = new CsvReaderOptions(new string[] { "\r", "\n" });
            var results = csvParser.ReadFromString(csvReaderOptions, line);

            return(results.Select(x => x.Result).ToList());
        }
Пример #17
0
        public async Task <bool> ConvertAndAdd(IBrowserFile browserFile)
        // Skapar tempfil av filen man skickat in, för att läsa in och sedan ta bort då den inte längre behövs.
        // Kopierar tempfilen till en riktig fil. Ökade värdet på OpenReadStream(20000000) då filen är större än värdet som tillåts.
        {
            var dataList = new List <TemperatureReading>();
            var filePath = Path.GetTempFileName();

            using (var stream = File.Create(filePath))
            {
                await browserFile.OpenReadStream(20000000).CopyToAsync(stream); /**/
            }

            var data = await File.ReadAllLinesAsync(filePath);

            File.Delete(filePath);

            for (int i = 0; i < data.Length; i++) // Inläsning av alla rader från filen. Sparar som entiteter i en lista som vi sedan skickar till databasen och sparar.
            {
                var item = data[i];
                if (item != null)
                {
                    var splittedData = item.Split(",");

                    if (splittedData.Length == 4)
                    {
                        try
                        {
                            TemperatureReading temperatureReading = new TemperatureReading()
                            {
                                Date        = DateTime.Parse(splittedData[0].Replace(" ", "T")),
                                Location    = splittedData[1],
                                Temperature = double.Parse(splittedData[2], NumberFormatInfo.InvariantInfo),
                                Humidity    = int.Parse(splittedData[3])
                            };
                            dataList.Add(temperatureReading);
                        }
                        catch (Exception e)
                        {
                            System.Diagnostics.Debug.WriteLine(e.Message);
                            System.Diagnostics.Debug.WriteLine(i + 1);
                            throw;
                        }
                    }
                }
            }
            await _efContext.TemperatureReadings.AddRangeAsync(dataList);

            await _efContext.SaveChangesAsync();

            return(true);
        }
Пример #18
0
        private async Task UploadFile()
        {
            if (SelectedFile != null)
            {
                Stream       stream = SelectedFile.OpenReadStream();
                MemoryStream ms     = new();
                await stream.CopyToAsync(ms);

                FileRequest.Byte     = ms.ToArray();
                FileRequest.FileName = WebUtility.HtmlEncode(SelectedFile.Name);

                await EventCallback.InvokeAsync();
            }
        }
Пример #19
0
        public static async Task LoadXMLfromFile(MonacoEditor editor, IBrowserFile file)
        {
            byte[] bytesOfXML = new byte[file.Size];
            using (Stream strm = file.OpenReadStream())
            {
                await strm.ReadAsync(bytesOfXML);
            }
            string    stringOfXML = Encoding.UTF8.GetString(bytesOfXML);
            TextModel model       = await MonacoEditorBase.CreateModel(stringOfXML, "xml");

            await editor.SetModel(model);

            //List<string> lLines = stringOfXML.Split("\n").ToList<string>();
        }
Пример #20
0
        public async Task UploadFile(string folderPath, IBrowserFile file)
        {
            using var uploadFile = File.OpenWrite(Path.Combine(folderPath, file.Name));
            using var stream     = file.OpenReadStream();
            var    buffer = new byte[4 * 1096];
            int    bytesRead;
            double totalRead = 0;

            while ((bytesRead = await stream.ReadAsync(buffer)) != 0)
            {
                totalRead += bytesRead;
                await uploadFile.WriteAsync(buffer);
            }
        }
Пример #21
0
        /// <summary>
        /// Denna metoden tar in en fil som användaren har valt,
        /// filen läses in som en temporär fil på hårddisken och tas bort så fort den inte behövs mer.
        /// Använder OpenReadStream(20000000) då filen var större än default värdet.
        /// När datan har lästs in från fil, skapar vi upp entiteter som läggs i en lista
        /// som vi sedan skickar in till databasen och sparar.
        /// </summary>
        /// <param name="browserFile">Filen som användaren har valt.</param>
        /// <returns>En boolean på om det lyckats eller inte.</returns>
        public async Task <bool> ConvertAndAdd(IBrowserFile browserFile)
        {
            var dataList = new List <TemperatureReading>();
            var filePath = Path.GetTempFileName();

            using (var stream = File.Create(filePath))
            {
                await browserFile.OpenReadStream(20000000).CopyToAsync(stream);
            }

            var data = await File.ReadAllLinesAsync(filePath);

            File.Delete(filePath);

            for (int i = 0; i < data.Length; i++)
            {
                var item = data[i];
                if (item != null)
                {
                    var splittedData = item.Split(",");

                    if (splittedData.Length == 4)
                    {
                        try
                        {
                            TemperatureReading temperatureReading = new TemperatureReading()
                            {
                                Date        = DateTime.Parse(splittedData[0].Replace(" ", "T")),
                                Thermometer = splittedData[1],
                                Temperature = double.Parse(splittedData[2], NumberFormatInfo.InvariantInfo),
                                Humidity    = int.Parse(splittedData[3])
                            };
                            dataList.Add(temperatureReading);
                        }
                        catch (Exception e)
                        {
                            System.Diagnostics.Debug.WriteLine(e.Message);
                            System.Diagnostics.Debug.WriteLine(i + 1);
                            return(false);
                        }
                    }
                }
            }
            await _weatherDataContext.temperatureReadings.AddRangeAsync(dataList);

            await _weatherDataContext.SaveChangesAsync();

            return(true);
        }
Пример #22
0
        public async Task <string> ReadTextAsync(IBrowserFile browserFile)
        {
            _ = browserFile ?? throw new ArgumentNullException(nameof(browserFile));

            if (!_supportedMimeTypes.Contains(browserFile.ContentType))
            {
                throw new NotSupportedException(
                          $"File type ({browserFile.ContentType}) is not supported.");
            }

            using var file   = browserFile.OpenReadStream();
            using var reader = new StreamReader(file, Encoding.UTF8);

            return(await reader.ReadToEndAsync().ConfigureAwait(false));
        }
Пример #23
0
        public async Task <string> UploadImage(IBrowserFile bfile)
        {
            string uniqueFileName = null;
            var    file           = bfile.OpenReadStream(maxAllowedSize: 4096000);

            if (file is not null)
            {
                string uploadsFolder = Path.Combine(webHostEnvironment.WebRootPath, "images");
                uniqueFileName = Guid.NewGuid().ToString() + "_" + bfile.Name;
                string filePath = Path.Combine(uploadsFolder, uniqueFileName);
                using (var fileStream = new FileStream(filePath, FileMode.Create))
                {
                    await file.CopyToAsync(fileStream);
                }
            }
            return(uniqueFileName);
        }
Пример #24
0
        private async Task SaveSweet()
        {
            try
            {
                bool           success;
                SweetWithImage si = new SweetWithImage(s);
                if (fileToUpload is not null)
                {
                    using Stream stream   = fileToUpload.OpenReadStream();
                    using MemoryStream ms = new MemoryStream();
                    await stream.CopyToAsync(ms);

                    UploadedFile uploadedFile = new UploadedFile(fileToUpload.Name, ms.ToArray());
                    si.ImageFile = uploadedFile;
                }

                if (si.Sweet.Id == default(int))
                {
                    var resp = await http.PostAsJsonAsync("sweet", si);

                    success = resp.IsSuccessStatusCode;
                }
                else
                {
                    var resp = await http.PutAsJsonAsync("sweet/withimage", si);

                    success = resp.IsSuccessStatusCode;
                }

                if (success)
                {
                    s.ImageFileName = fileToUpload.Name;
                    await sw.FireAsync("Success", "Sweet save success.", SweetAlertIcon.Success);

                    TitlePage = "Modify sweet";
                }
                else
                {
                    await sw.FireAsync("Error", "Something is wrong.", SweetAlertIcon.Error);
                }
            }
            catch (AccessTokenNotAvailableException exception)
            {
                exception.Redirect();
            }
        }
    public async Task <(int Count, string Message, Document?Entity)> SaveAsync(ClaimsPrincipal?principal, IBrowserFile file, object?documentedObject, string?fileExtension, int maxFileSizeKb)
    {
        if (principal.IsAuthenticated())
        {
            using var dbContext = Factory.CreateDbContext();
            var fileSize = (int)file.Size;

            using var stream = file.OpenReadStream(maxFileSizeKb * 1024);
            var(Id, DocumentId, TypeName) = DocumentedObject(documentedObject, fileExtension);
            if (DocumentId.HasValue)
            {
                var existing = await dbContext.Documents.FindAsync(DocumentId);

                if (existing is null)
                {
                    return(principal.NothingToUpdate <Document>());
                }
                existing.Content = new byte[fileSize];
                var bytes = await stream.ReadAsync(existing.Content.AsMemory(0, fileSize));

                existing.LastModifiedTime = TimeProvider.Now;
                var count = await dbContext.SaveChangesAsync();

                return(count.SaveResult(existing));
            }
            else
            {
                var document = new Document
                {
                    FileExtension    = fileExtension,
                    ContentType      = ContentType(fileExtension),
                    Content          = new byte[file.Size],
                    LastModifiedTime = TimeProvider.Now
                };
                var bytes = await stream.ReadAsync(document.Content.AsMemory(0, fileSize));

                dbContext.Documents.Add(document);
                var count = await dbContext.SaveChangesAsync();

                count += await UpdateDocumentReference(dbContext, document, documentedObject);

                return(count.SaveResult(document));
            };
        }
        return(principal.SaveNotAuthorised <Document>());
Пример #26
0
        public async Task <string> Upload(IBrowserFile file)
        {
            string uploadFolder = Path.Combine(webHostEnvironment.WebRootPath, "images", "products");

            string uniqueFileName = Guid.NewGuid().ToString() + "-" + file.Name;
            string filePath       = Path.Combine(uploadFolder, uniqueFileName);

            using (Stream stream = file.OpenReadStream(maxFileSize))
            {
                using (MemoryStream memoryStream = new())
                {
                    await stream.CopyToAsync(memoryStream);

                    await File.WriteAllBytesAsync(filePath, memoryStream.ToArray());
                }
            }
            return(uniqueFileName);
        }
Пример #27
0
        private async Task OnFileSelection(InputFileChangeEventArgs e)
        {
            IBrowserFile imgFile = e.File;
            var          buffers = new byte[imgFile.Size];
            await imgFile.OpenReadStream(maxFileSize).ReadAsync(buffers);

            string imageType = imgFile.ContentType;

            imgUrl = $"data:{imageType};base64,{Convert.ToBase64String(buffers)}";

            //todo
            //IBrowserFile file = e.File;
            //  //var buffers = new byte[imgFile.Size];
            //  using var reader = new StreamReader(file.OpenReadStream(maxFileSize));
            //  await reader.ReadAsync(content);
            //  string imageType = file.ContentType;
            //  imgUrl =$"data:{imageType};base64,{Convert.ToBase64String(loadedFileContent)}";
        }
Пример #28
0
        public async Task <string> PublishFile(IBrowserFile file)
        {
            using MultipartFormDataContent formContent = new();
            using StreamContent streamContent          = new(file.OpenReadStream(MaxFileSize));
            formContent.Add(streamContent, "\"files\"", file.Name);

            await _apiClient.EnsureAuthorizationHeader();

            HttpResponseMessage response = await _apiClient.HttpClient.PostAsync("", formContent);

            using Stream contentStream = await response.Content.ReadAsStreamAsync();

            var result = await JsonSerializer.DeserializeAsync <FileUploadResult>(contentStream, options : new()
            {
                PropertyNameCaseInsensitive = true
            });

            return(result.LocalPath);
        }
Пример #29
0
        public async Task <string> UploadFile(IBrowserFile WebFile, Models.File CirrusFile)
        {
            var DirectoryClient           = FileSystemClient.GetDirectoryClient(CirrusFile.UserId);
            DataLakeFileClient FileClient = null;

            foreach (Category Category in CirrusFile.Categories)
            {
                FileClient = DirectoryClient.CreateSubDirectoryAsync(Category.CategoryName).Result.Value.CreateFileAsync(CirrusFile.FileName).Result.Value;
                using (var MS = new MemoryStream())
                {
                    await WebFile.OpenReadStream(10485760).CopyToAsync(MS);

                    MS.Position = 0;
                    await FileClient.AppendAsync(MS, 0);

                    await FileClient.FlushAsync(position : MS.Length);
                }
            }
            return(FileClient == null ? null : FileClient.Path + "/" + CirrusFile.FileName);
        }
Пример #30
-1
        public async Task <string> UploadFile(IBrowserFile file)
        {
            try
            {
                var fileInfo        = new FileInfo(file.Name);
                var fileName        = Guid.NewGuid().ToString() + fileInfo.Extension;
                var folderDirectory = $"{_webHostEnvironment.WebRootPath}\\flatimages";
                var path            = Path.Combine(_webHostEnvironment.WebRootPath, "flatimages", fileName);
                var memoryStream    = new MemoryStream();
                await file.OpenReadStream().CopyToAsync(memoryStream);

                if (!Directory.Exists(folderDirectory))
                {
                    Directory.CreateDirectory(folderDirectory);
                }

                await using (var fileStream = new FileStream(path, FileMode.Create, FileAccess.Write))
                {
                    memoryStream.WriteTo(fileStream);
                }

                // url - содержит полный путь до файла.
                var url = $"{_httpContextAccessor.HttpContext.Request.Scheme}://{_httpContextAccessor.HttpContext.Request.Host.Value}/";
                //var url = $"{_configuration.GetValue<string>("ServerUrl")}";
                var fullPath = $"{url}flatimages/{fileName}";

                return(fullPath);
            }
            catch (Exception ex)
            {
                return(ex.Message);
                //or throw ex;
            }
        }