private async Task <string> UploadPhotoAsync(Microsoft.AspNetCore.Http.IFormFile img)
        {
            string urlPhoto = Guid.NewGuid().ToString() + "_" + DateTime.Now.ToString("yyyyMMddHHmmss") + "_" + img.FileName;
            Uri    uri      = await this._documentService.UploadAsync(img.OpenReadStream(), img.ContentType, urlPhoto);

            return(uri.AbsoluteUri);
        }
예제 #2
0
        public IActionResult Edit(Page page, Microsoft.AspNetCore.Http.IFormFile Image)
        {
            if (ModelState.IsValid)
            {
                //получаем все элементы и проверяем есть ли элемент с таким же url
                IQueryable <Page> pages = dataManager.Pages.GetPages();
                foreach (var item in pages)
                {
                    if (item.Id != page.Id && item.Url == page.Url)
                    {
                        ModelState.AddModelError(nameof(Page.Url), "Запись с таким URL уже есть");
                        return(View(page));
                    }
                }
                if (Image.IsImage())
                {
                    //записываем в объект путь к картинке
                    page.Image = Image.FileName;

                    //сохраняем картинку
                    using (var img = System.Drawing.Image.FromStream(Image.OpenReadStream(), true, true))
                    {
                        //создаём измененную картинку
                        var i = new Bitmap(img.ScaleAndCrop(1920, 1280, TargetSpot.BottomMiddle));
                        //сохраняем картинку
                        i.SaveAs(Path.Combine(hostEnvironment.WebRootPath, "images/pages/", Image.FileName));
                    }
                }
                //сохраняем запись
                dataManager.Pages.SavePage(page);
                //выходим на главную
                return(RedirectToAction(nameof(HomeController.Index), nameof(HomeController).CutController()));
            }
            return(View(page));
        }
예제 #3
0
        private static async Task UploadMovieAsync(string MovieTitle, Microsoft.AspNetCore.Http.IFormFile file)
        {
            // get the file and convert it to the byte[]
            byte[] fileBytes = new Byte[file.Length];
            file.OpenReadStream().Read(fileBytes, 0, Int32.Parse(file.Length.ToString()));

            // create unique file name for prevent the mess
            //var fileName = Guid.NewGuid() + file.FileName;

            PutObjectResponse response = null;

            using (var stream = new MemoryStream(fileBytes))
            {
                var request = new PutObjectRequest
                {
                    BucketName  = bucketName,
                    Key         = MovieTitle,
                    InputStream = stream,
                    ContentType = file.ContentType,
                    CannedACL   = S3CannedACL.PublicRead
                };

                response = await s3.PutObjectAsync(request);
            };

            if (response.HttpStatusCode == System.Net.HttpStatusCode.OK)
            {
                Debug.WriteLine("File uploaded");
            }
        }
예제 #4
0
 public ActionResult Create(Calisan calisan, Microsoft.AspNetCore.Http.IFormFile Image)
 {
     calisan.Id = Guid.NewGuid().ToString();
     var maas = _maasManager.GetById(calisan.MaasId);
     ViewBag.Maasies = _maasManager.GetAll();
     calisan.Maas = maas;
     if (!ModelState.IsValid)
     {
         return View("Create");
     }
     if (Image != null)
     {
         MemoryStream memoryStream = new MemoryStream();
         Image.OpenReadStream().CopyTo(memoryStream);
         calisan.Image = Convert.ToBase64String(memoryStream.ToArray());
     }
     else
     {
         calisan.Image = "";
     }
     bool isSaved = _calisanManager.Add(calisan);
     string mgs = "";
     if (isSaved)
     {
         return RedirectToAction("Index");
     }
     else
     {
         mgs = "Save hatasi";
     }
     ViewBag.Mgs = mgs;
     return View();
 }
예제 #5
0
        public async Task <IActionResult> UploadFile(Microsoft.AspNetCore.Http.IFormFile fileToUpload, string container, CancellationToken ct)
        {
            using (var stream = fileToUpload.OpenReadStream())
            {
                var uploadRequestHeaders = fileToUpload.Headers;
                var allContent           = await this.storageProvider.Upload(stream, container, fileToUpload.FileName, fileToUpload.ContentType, ct);

                return(Ok(allContent));
            }
        }
예제 #6
0
 public virtual async Task <IEnumerable <SaveResult <CaseDtoGen> > > CsvUpload(Microsoft.AspNetCore.Http.IFormFile file, bool hasHeader = true)
 {
     if (file != null && file.Length > 0)
     {
         using (var stream = file.OpenReadStream())
         {
             using (var reader = new System.IO.StreamReader(stream)) {
                 var csv = reader.ReadToEnd();
                 return(await CsvSave(csv, hasHeader));
             }
         }
     }
     throw new ArgumentException("No files uploaded");
 }
예제 #7
0
        public static DataFile Create(Microsoft.AspNetCore.Http.IFormFile file)
        {
            var result = new DataFile
            {
                Name = file.FileName,
                Type = file.ContentType
            };

            using (var stream = file.OpenReadStream())
            {
                var reader = new System.IO.BinaryReader(stream);
                reader.BaseStream.Seek(0, System.IO.SeekOrigin.Begin);
                result.Content = reader.ReadBytes((int)reader.BaseStream.Length);
            }
            return(result);
        }
예제 #8
0
        protected async Task <IEnumerable <ItemResult> > CsvUploadImplementation(
            Microsoft.AspNetCore.Http.IFormFile file,
            IDataSource <T> dataSource,
            IBehaviors <T> behaviors,
            bool hasHeader = true)
        {
            if (file == null || file.Length == 0)
            {
                throw new ArgumentException("No files uploaded");
            }

            using (var stream = file.OpenReadStream())
            {
                using (var reader = new System.IO.StreamReader(stream))
                {
                    var csv = await reader.ReadToEndAsync();

                    return(await CsvSaveImplementation(csv, dataSource, behaviors, hasHeader));
                }
            }
        }
예제 #9
0
        /// <summary>
        /// Saves the file to safe dir.
        /// </summary>
        /// <param name="title">Title.</param>
        /// <param name="file">File.</param>
        public static void SaveFileToSafeDir(string title, Microsoft.AspNetCore.Http.IFormFile file)
        {
            var stream = file.OpenReadStream();


            var temp = DateTime.Now.DayOfYear + DateTime.Now.Millisecond.ToString() + file.FileName;

            var filePath = Path.Combine("./UploadedFiles", temp);

            FileStream amin = new FileStream(filePath, System.IO.FileMode.OpenOrCreate);

            stream.CopyTo(amin);

            amin.Close();
            Console.WriteLine(title);
            var places = Database.GetCollection <Location>("Locations");
            var place  = places.FindOne(t => t.Title == title);

            place.ImagesList.Add(temp);
            places.Update(place);
        }
예제 #10
0
        /// <summary>
        /// Saves the user profile image.
        /// </summary>
        /// <param name="username">Username.</param>
        /// <param name="file">File.</param>

        public static void SaveUserProfileImage(string username, Microsoft.AspNetCore.Http.IFormFile file)
        {
            var stream = file.OpenReadStream();


            var temp = DateTime.Now.DayOfYear + DateTime.Now.Millisecond.ToString() + file.FileName;

            var filePath = Path.Combine("./UploadedFiles", temp);

            FileStream amin = new FileStream(filePath, System.IO.FileMode.OpenOrCreate);

            stream.CopyTo(amin);
            Console.WriteLine($"Upload  {username}'s profile pic {file.FileName}");
            amin.Close();
            var users = Database.GetCollection <User>("users");
            var user  = users.FindOne(u => u.UserName.Equals(username));

            user.UserImage = temp;
            users.Update(user);
            Console.WriteLine("Done");
        }
예제 #11
0
파일: MinIO.cs 프로젝트: israelsam/Qantler
        public async Task <UploadResponse> FileUploadv2(Microsoft.AspNetCore.Http.IFormFile file)
        {
            var            bucketName = this.bucket;
            UploadResponse obj        = new UploadResponse();

            try
            {
                var minio = new MinioClient(this.endpoint, accessKey, accessSecret);
                // Make a bucket on the server, if not already present.
                bool found = await minio.BucketExistsAsync(bucketName);

                if (!found)
                {
                    await minio.MakeBucketAsync(bucketName, this.location);
                }

                var stream = file.OpenReadStream();
                await minio.PutObjectAsync(bucketName, file.Name, stream, stream.Length);

                if (file.Length > 0)
                {
                    obj.Message    = "Uploaded Successfully.";
                    obj.HasSucceed = true;
                    obj.FileName   = file.Name;
                    obj.FileUrl    = this.BaseUrl + bucketName + "/" + file.Name;
                }
                else
                {
                    obj.Message = this.BaseUrl + bucketName + "/";
                }
            }
            catch (MinioException e)
            {
                Console.WriteLine("File Upload Error: {0}", e.Message);
                obj.Message    = "Uploaded failed with error " + e.message;
                obj.HasSucceed = false;
                obj.FileUrl    = this.BaseUrl + bucketName + "/";
            }
            return(obj);
        }
        public async Task <IActionResult> Import(Microsoft.AspNetCore.Http.IFormFile schoolFileCsv)
        {
            PageTitle = "Import Schools";
            if (schoolFileCsv == null ||
                !string.Equals(Path.GetExtension(schoolFileCsv.FileName), ".csv",
                               System.StringComparison.OrdinalIgnoreCase))
            {
                AlertDanger = "You must select a .csv file.";
                ModelState.AddModelError("schoolFileCsv", "You must select a .csv file.");
            }

            if (ModelState.ErrorCount == 0)
            {
                using (var streamReader = new StreamReader(schoolFileCsv.OpenReadStream()))
                {
                    (ImportStatus status, string message)
                        = await _schoolImportService.FromCsvAsync(streamReader);

                    switch (status)
                    {
                    case ImportStatus.Success:
                        AlertSuccess = message;
                        break;

                    default:
                        AlertInfo = message;
                        break;

                    case ImportStatus.Warning:
                        AlertWarning = message;
                        break;

                    case ImportStatus.Danger:
                        AlertDanger = message;
                        break;
                    }
                }
            }
            return(RedirectToAction("Import"));
        }
예제 #13
0
        public async Task <IActionResult> Import(Microsoft.AspNetCore.Http.IFormFile eventFileCsv)
        {
            PageTitle = "Import Events";
            if (eventFileCsv == null ||
                Path.GetExtension(eventFileCsv.FileName).ToLower() != ".csv")
            {
                AlertDanger = "You must select a .csv file.";
                ModelState.AddModelError("eventFileCsv", "You must select a .csv file.");
            }

            if (ModelState.ErrorCount == 0)
            {
                using (var streamReader = new StreamReader(eventFileCsv.OpenReadStream()))
                {
                    (ImportStatus status, string message)
                        = await _eventImportService.FromCsvAsync(streamReader);

                    switch (status)
                    {
                    case ImportStatus.Success:
                        AlertSuccess = message;
                        break;

                    case ImportStatus.Info:
                        AlertInfo = message;
                        break;

                    case ImportStatus.Warning:
                        AlertWarning = message;
                        break;

                    case ImportStatus.Danger:
                        AlertDanger = message;
                        break;
                    }
                }
            }
            return(RedirectToAction("Import"));
        }
예제 #14
0
        public string Post(Microsoft.AspNetCore.Http.IFormFile file)
        {
            string ext = "wav";

            if (file.FileName.Length > 3)
            {
                ext = file.FileName.Substring(file.FileName.Length - 3);
            }

            string id = Guid.NewGuid().ToString();

            string path = Base.conf.tempImageFilePath + "\\d-" + id + "." + ext;

            Stream read = file.OpenReadStream();

            using (var fileStream = System.IO.File.Create(path))
            {
                read.CopyTo(fileStream);
            }

            return(id);
        }
예제 #15
0
        public async Task <ActionResult <List <String> > > ImportEsemenyFromExcel()
        {
            Microsoft.AspNetCore.Http.IFormFile file = null;
            try
            {
                file = Request.Form.Files.FirstOrDefault();
            }
            catch
            {
            }
            List <string> log;

            try
            {
                log = await _importerService.ImportEsemenyekFromExcel(file?.OpenReadStream());
            }
            catch (Exception e)
            {
                return(BadRequest(e));
            }

            return(Ok(log));
        }
        public async Task UploadFileToBlobAsync(Microsoft.AspNetCore.Http.IFormFile file)
        {
            // Create the container and return a container client object
            BlobContainerClient containerClient;

            try {
                containerClient = await blobServiceClient.CreateBlobContainerAsync(containerName);
            } catch {
                containerClient = blobServiceClient.GetBlobContainerClient(containerName);
            }

            string fileName = $"hellofile.wav";

            // Get a reference to a blob
            BlobClient blobClient = containerClient.GetBlobClient(fileName);

            Debug.WriteLine("Uploading to Blob storage as blob:\n\t {0}\n", blobClient.Uri);

            // Open the file and upload its data
            using (var stream = file.OpenReadStream()) {
                await blobClient.UploadAsync(stream, true);
            }
        }
예제 #17
0
 /// <summary>
 /// 添加数据。
 /// </summary>
 /// <returns></returns>
 public IActionResult AddTestData()
 {
     if (HttpContext.Request.Method.ToUpper() != "POST")
     {
         return(new JsonResult(new ResultMessage {
             ResultCode = WebAPIStatus.STATE_FAIL, Message = "错误的请求方式。"
         }));
     }
     if (!HttpContext.Request.Form.ContainsKey("GroupId"))
     {
         return(new JsonResult(new ResultMessage {
             ResultCode = WebAPIStatus.STATE_FAIL, Message = "缺少参数。"
         }));
     }
     if (!HttpContext.Request.Form.ContainsKey("TestName"))
     {
         return(new JsonResult(new ResultMessage {
             ResultCode = WebAPIStatus.STATE_FAIL, Message = "缺少参数。"
         }));
     }
     if (!HttpContext.Request.Form.ContainsKey("TestAge"))
     {
         return(new JsonResult(new ResultMessage {
             ResultCode = WebAPIStatus.STATE_FAIL, Message = "缺少参数。"
         }));
     }
     if (!HttpContext.Request.Form.ContainsKey("TestSex"))
     {
         return(new JsonResult(new ResultMessage {
             ResultCode = WebAPIStatus.STATE_FAIL, Message = "缺少参数。"
         }));
     }
     try
     {
         Dictionary <string, object> data = new Dictionary <string, object>();
         data.Add("GroupId", Convert.ToInt32(HttpContext.Request.Form["GroupId"]));
         data.Add("TestName", HttpContext.Request.Form["TestName"].ToString());
         data.Add("TestAge", Convert.ToSingle(HttpContext.Request.Form["TestAge"]));
         data.Add("TestSex", HttpContext.Request.Form["TestSex"].ToString());
         byte[] Bin;
         if (HttpContext.Request.Form.Files.Count < 1)
         {
             data.Add("TestPhoto", DBNull.Value);
         }
         else
         {
             Microsoft.AspNetCore.Http.IFormFile file = HttpContext.Request.Form.Files[0]; // 只接收一个图片文件
             Bin = new byte[file.Length];
             using (System.IO.Stream sm = file.OpenReadStream())
             {
                 int rlen = 0x0, offset = 0x0;
                 do
                 {
                     rlen    = sm.Read(Bin, offset, Bin.Length - offset);
                     offset += rlen;
                 } while (offset < Bin.Length);
             }
             data.Add("TestPhoto", Bin);
         }
         if (AppServices.GetService <DataService>().SaveData(data))
         {
             return(new JsonResult(new ResultMessage {
                 ResultCode = WebAPIStatus.STATE_OK
             }));
         }
         else
         {
             return(new JsonResult(new ResultMessage {
                 ResultCode = WebAPIStatus.STATE_FAIL, Message = "提交数据失败了。"
             }));
         }
     }
     catch (Exception Ex)
     {
         return(new JsonResult(new ResultMessage {
             ResultCode = WebAPIStatus.INTERNAL_SERVER_ERROR, Message = Ex.Message
         }));
     }
 }
예제 #18
0
 public void Upload(Microsoft.AspNetCore.Http.IFormFile file)
 {
     try
     {
         Instance.UploadObject("go-logs-304513.appspot.com", file.FileName, file.ContentType, file.OpenReadStream());
     }
     catch (Exception e)
     {
         System.Diagnostics.Debug.WriteLine(e);
     }
 }
        /// <summary>
        /// 只读取不保存
        /// </summary>
        /// <param name="excelfile"></param>
        /// <param name="IsHaveHead"></param>
        /// <returns></returns>
        public List <Sheetitem> Import(Microsoft.AspNetCore.Http.IFormFile excelfile, bool IsHaveHead = true)
        {
            //最终结果集
            List <Sheetitem> result = new List <Sheetitem>();

            try
            {
                //工厂读取文件流
                IWorkbook readWorkbook = WorkbookFactory.Create(excelfile.OpenReadStream());
                int       CountSheet   = readWorkbook.NumberOfSheets;
                for (var i = 0; i < CountSheet; i++)
                {
                    //获取sheet
                    ISheet    worksheet = readWorkbook.GetSheetAt(i);
                    Sheetitem item      = new Sheetitem();
                    //保存sheet名字
                    item.Name = worksheet.SheetName;
                    //获取行数长度(计算是从0开始的)
                    int rowCount = worksheet.LastRowNum + 1;
                    if (rowCount == 0)
                    {
                        continue;
                    }
                    int startRow = 0;
                    //需要读取的列数
                    List <int> NeedReadCol = new List <int>();
                    //如果有头部处理方式
                    if (IsHaveHead)
                    {
                        int col = -1;
                        foreach (ICell cell in worksheet.GetRow(0).Cells)
                        {
                            string CellValue = "";
                            if (cell.CellType == CellType.Numeric && DateUtil.IsCellDateFormatted(cell))
                            {
                                CellValue = cell.DateCellValue.ToString();
                            }
                            else
                            {
                                CellValue = cell.ToString();
                            }
                            col++;
                            if (!string.IsNullOrEmpty(CellValue))
                            {
                                NeedReadCol.Add(col);
                                //item.Thread[0].Data.Add(new excle_option() { value = CellValue });
                                item.MyTitle.Add(new excle_option()
                                {
                                    value = CellValue
                                });
                            }
                        }
                        startRow++;
                    }
                    //如果不存在头部怎么全部读出来
                    else
                    {
                        for (int NeedCell = 0; NeedCell < int.Parse(worksheet.GetRow(0).LastCellNum.ToString()); NeedCell++)
                        {
                            NeedReadCol.Add(NeedCell);
                        }
                    }

                    //开始遍历所有行(如果有头部怎么去掉头部的行)
                    for (var RowNumber = startRow; RowNumber < rowCount; RowNumber++)
                    {
                        //保存每行是数据
                        RowData Row = new RowData();

                        foreach (int CellNumber in NeedReadCol)
                        {
                            string CellValue = "";
                            ICell  Cell      = worksheet.GetRow(RowNumber).GetCell(CellNumber);
                            if (Cell == null)
                            {
                                CellValue = "";
                            }
                            else if (Cell.CellType == CellType.Numeric && DateUtil.IsCellDateFormatted(Cell))
                            {
                                CellValue = Cell.DateCellValue.ToString();
                            }
                            else
                            {
                                CellValue = Cell.ToString();
                            }
                            //每个但单元格的数据
                            excle_option DataCell = new excle_option();
                            DataCell.value = CellValue;
                            //将单元的数据加到行中
                            Row.Data.Add(DataCell);
                        }
                        if (Row.Data.FindAll(e => !string.IsNullOrEmpty(e.value)).Count > 0)
                        {
                            //遍历完行后,添加到sheet中
                            item.RowData.Add(Row);
                        }
                    }
                    //将sheet添加到结果集中
                    result.Add(item);
                }
            }
            catch (Exception e)
            {
                throw e;
            }
            return(result);
        }
 public static String GetFileName(Microsoft.AspNetCore.Http.IFormFile File)
 {
     return(ComputeHash(File.OpenReadStream()) + FileExtention.GetExtention(File));
 }
예제 #21
0
        public async Task <ActionResult> OnPostAddAsync(Microsoft.AspNetCore.Http.IFormFile file)
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }


            // TODO: Get the username for real.
            string username = Request.Form["usernameTemp"];

            if (String.IsNullOrEmpty(username))
            {
                username = "******";
            }

            Post post = new Post();

            post.Text       = Request.Form["postText"];
            post.Title      = Request.Form["title"];
            post.Tags       = Request.Form["tags"].ToString().Split(',').Select(s => s.Trim().ToLowerInvariant()).ToArray();
            post.CreateDate = DateTime.Now;
            post.Author     = new ObjectModel.User(username);

            if (file != null)
            {
                ImageWithMetadata captionedImage = new ImageWithMetadata();
                captionedImage.Caption    = "testCaption";
                captionedImage.UploadDate = DateTime.Now;
                if (file.FileName.EndsWith(".png"))
                {
                    captionedImage.Filetype = ImageFormat.PNG;
                }
                else if (file.FileName.EndsWith(".gif"))
                {
                    captionedImage.Filetype = ImageFormat.GIF;
                }
                else
                {
                    captionedImage.Filetype = ImageFormat.JPEG;
                }

                var image = System.Drawing.Image.FromStream(file.OpenReadStream());
                using (MemoryStream mStream = new MemoryStream())
                {
                    image.Save(mStream, image.RawFormat);
                    byte[] bytes = mStream.ToArray();

                    var imageInDb = new Stori.ObjectModel.Image(bytes);
                    await imageInDb.SaveChangesAsync();

                    captionedImage.ImageId = imageInDb._id;

                    captionedImage.Width  = image.Width;
                    captionedImage.Height = image.Height;
                }

                await captionedImage.SaveChangesAsync();

                post.CaptionedImages = new ImageWithMetadata[] { captionedImage };  // TODO: Alternatively, just store the identifiers
            }
            SaveChanges(post);

            return(RedirectToPage("./User/View/", new { username = username }));
        }