当前位置: 首页>>代码示例>>C#>>正文


C# IFormFile类代码示例

本文整理汇总了C#中IFormFile的典型用法代码示例。如果您正苦于以下问题:C# IFormFile类的具体用法?C# IFormFile怎么用?C# IFormFile使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


IFormFile类属于命名空间,在下文中一共展示了IFormFile类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Index

        public async Task<IActionResult> Index(IFormFile photo, string query, string lat, string lng)
        {
            if (photo != null)
            {
                Notez note = new Notez
                {
                    Found = true,
                    Timestamp = DateTimeOffset.Now,
                    UserAgent = Request.Headers["User-Agent"],
                    HostAddress = Context.GetFeature<IHttpConnectionFeature>().RemoteIpAddress.ToString(),
                    LocationRaw = query,
                };

                if (!string.IsNullOrWhiteSpace(query) && (string.IsNullOrWhiteSpace(lat) || string.IsNullOrWhiteSpace(lng)))
                {
                    using (HttpClient http = new HttpClient())
                    {
                        Stream response = await http.GetStreamAsync("http://maps.googleapis.com/maps/api/geocode/xml?address=" + Uri.EscapeDataString(query));
                        XDocument xml = XDocument.Load(response);

                        if (xml.Root.Element("status")?.Value == "OK")
                        {
                            XElement location = xml.Root.Element("result")?.Element("geometry")?.Element("location");

                            lat = location?.Element("lat")?.Value;
                            lng = location?.Element("lng")?.Value;
                        }
                    }
                }

                double value;
                if (double.TryParse(lat, NumberStyles.Float, CultureInfo.InvariantCulture, out value)) note.Latitude = value;
                if (double.TryParse(lng, NumberStyles.Float, CultureInfo.InvariantCulture, out value)) note.Longitude = value;

                _context.Notez.Add(note);
                await _context.SaveChangesAsync();

                string root = Path.Combine(_environment.MapPath("n"));
                await photo.SaveAsAsync(Path.Combine(root, note.ID + ".jpg"));

                try
                {
                    using (Stream s = photo.OpenReadStream())
                        Helper.GenerateThumbnail(s, Path.Combine(root, "t" + note.ID + ".jpg"));
                }
                catch
                {
                    note.FlagStatus = FlagStatus.Invalid;
                    await _context.SaveChangesAsync();
                }

                return RedirectToAction(nameof(Thanks), new { noteID = note.ID });
            }

            return RedirectToAction(nameof(Index));
        }
开发者ID:digitalcivics,项目名称:happynotez,代码行数:56,代码来源:MobileController.cs

示例2: SaveImage

 public async Task<ImageUploadResult> SaveImage(IFormFile file)
 {
     IImage image;
     using (var fileStram = file.OpenReadStream())
     {
         var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Replace("\"", string.Empty);
         string imageName = Guid.NewGuid() + Path.GetExtension(fileName);
         image = _imageFactory.CreateImage(imageName, fileStram);
     }
     await _imageRespository.SaveImageAsync(image);
     string imageUrl = _imageUrlProvider.GetImageUrl(image.Name);
     return new ImageUploadResult(imageUrl, image.Name);
 } 
开发者ID:VysotskiVadim,项目名称:bsuir-misoi-car-number,代码行数:13,代码来源:ImageController.cs

示例3: UploadDocumentAsync

 public async Task UploadDocumentAsync(IFormFile file)
 {
   using (var fileStream = new FileStream(Path.Combine(_documentUploadConfiguration.UploadPath, file.FileName), FileMode.Create))
   {
     await file.CopyToAsync(fileStream);
   }
 }
开发者ID:Research-Institute,项目名称:emr-api,代码行数:7,代码来源:EmrDocumentRepository.cs

示例4: Create

        public async Task<IActionResult> Create([Bind] Participant partner, IFormFile image)
        {
            if (this.ModelState.IsValid)
            {
                var uploads = Path.Combine(this.environment.WebRootPath, "uploads/participants");
                if (!Directory.Exists(uploads))
                {
                    Directory.CreateDirectory(uploads);
                }

                if (image.Length > 0)
                {
                    var fileName = $"{Guid.NewGuid()}.{image.FileName}";
                    using (var fileStream = new FileStream(Path.Combine(uploads, fileName), FileMode.Create))
                    {
                        await image.CopyToAsync(fileStream);
                        partner.ImgPath = $"/uploads/participants/{fileName}";
                    }
                }

                this.context.Add(partner);
                await this.context.SaveChangesAsync();
                return this.RedirectToAction("Index");
            }

            return this.View(partner);
        }
开发者ID:Zashikivarashi,项目名称:Autosation.ru,代码行数:27,代码来源:ParticipantsController.cs

示例5: Create

        public async Task<IActionResult> Create(IFormFile croppedImage1, IFormFile croppedImage2, int distance)
        {

            var uploads = Path.Combine(_environment.WebRootPath, "Uploads");

            if (croppedImage1.Length > 0 && croppedImage2.Length > 0)
            {
                var puzzleImageId = Guid.NewGuid().ToString();
                var fileName = string.Format("{0}.jpg", puzzleImageId);

                await croppedImage1.SaveAsAsync(Path.Combine(uploads, fileName));

                ImageResizer.ImageJob img1 = new ImageResizer.ImageJob(Path.Combine(uploads, fileName), Path.Combine(uploads, "16-9", "400", fileName),
                                new ImageResizer.Instructions("maxheight=400;&scale=both;format=jpg;mode=max"));

                img1.Build();

                ImageResizer.ImageJob img2 = new ImageResizer.ImageJob(Path.Combine(uploads, fileName), Path.Combine(uploads, "16-9", "1065", fileName),
                                                new ImageResizer.Instructions("maxheight=1065;&scale=both;format=jpg;mode=max"));

                img2.Build();


                if (ModelState.IsValid)
                {
                    await _puzzleRepository.AddPuzzleAsync(User, puzzleImageId, distance, _shopRepository.GetUserShop(User).ID);
                }
            }

            return View();

        }
开发者ID:sickpres,项目名称:PuzzleAdv,代码行数:32,代码来源:PuzzleController.cs

示例6: UpdateLogoAsync

 public async Task<string> UpdateLogoAsync(int? clubId, IFormFile file)
 {
     string path = string.Empty;
     if (clubId.HasValue)
     {
         path = await _clubService.GetNameAsync(clubId.Value);
     }
     var relativePath = path;
     if (string.IsNullOrEmpty(path) || !path.Contains(LogoPath))
     {
         var newName = (string.IsNullOrWhiteSpace(path) ? GenerateNewName() : path) + "." + file.FileName.Split('.').Last();
         var newPath = GenerateNewPath(LogoPath);
         relativePath = Path.Combine(newPath, newName);
         path = GetFullPath(relativePath);
     }
     else
     {
         path = GetFullPath(path);
     }
     
     file.CopyTo(new FileStream(path, FileMode.Create));
     relativePath = Regex.Replace(relativePath, "\\\\", "/");
     if (clubId.HasValue)
     {
         await _clubService.UpdateLogoAsync(clubId.Value, relativePath);
     }
     return relativePath;
 }
开发者ID:parys,项目名称:MyLiverpool,代码行数:28,代码来源:UploadService.cs

示例7: Upload

        public IActionResult Upload(IFormFile file)
        {
            if (!User.IsSignedIn())
                return Json(new
                {
                    code = 403,
                    msg = "Forbidden"
                });

            if (file == null)
                return Json(new
                {
                    code = 400,
                    msg = "File not found"
                });

            var _file = new Blob();
            _file.FileName = file.GetFileName();
            _file.Time = DateTime.Now;
            _file.Id = Guid.NewGuid();
            _file.ContentLength = file.Length;
            _file.ContentType = file.ContentType;
            _file.File = file.ReadAllBytes();
            DB.Blobs.Add(_file);
            DB.SaveChanges();
            return Json(new
            {
                code = 200,
                fileId = _file.Id.ToString()
            });
        }
开发者ID:Jeffiy,项目名称:vnextcn.org,代码行数:31,代码来源:FileController.cs

示例8: Create

 public async Task<IActionResult> Create(News news, IFormFile uploadFile)
 {
     if (ModelState.IsValid)
     {
         string fileName = Configurations.DefaultFileName;
         if (uploadFile != null)
         {
             //Image uploading
             string uploads = Path.Combine(_environment.WebRootPath, Configurations.NewsImageStockagePath);
             fileName = Guid.NewGuid().ToString() + "_" + ContentDispositionHeaderValue.Parse(uploadFile.ContentDisposition).FileName.Trim('"');
             await uploadFile.SaveImageAsAsync(Path.Combine(uploads, fileName));
         }
         //Setting value for creation
         news.Id = Guid.NewGuid();
         news.DateOfPublication = DateTime.Now;
         news.ImageLink = Path.Combine(Configurations.NewsImageStockagePath,fileName);
         //TODO Get logged in User and add it to the news
         StolonsUser user = await GetCurrentStolonsUserAsync();
         news.User = user;
         _context.News.Add(news);
         _context.SaveChanges();
         return RedirectToAction("Index");
     }
     return View(news);
 }
开发者ID:ChavFDG,项目名称:Stolons,代码行数:25,代码来源:NewsController.cs

示例9: Upload

        public async Task<IActionResult> Upload(IFormFile file, string userId)
        {
            var fileId = await _fileHandler.HandleUpload(file);

            await _userHandler.AddFileToUserMapping(userId, fileId);     

            return View();
        }
开发者ID:mathiasnohall,项目名称:Servanda,代码行数:8,代码来源:FileController.cs

示例10: StoreFileAsync

 public async Task StoreFileAsync(string fileName, IFormFile formFile, bool overwrite = false)
 {
     var filePath = GetAbsoluteFilePath(fileName);
     if (File.Exists(filePath) && !overwrite)
     {
         throw new Exception("File already exists");
     }
     await formFile.SaveAsAsync(filePath);
 }
开发者ID:QuangDang212,项目名称:StorageApps,代码行数:9,代码来源:FileManager.cs

示例11: Upload

    public async Task Upload(IFormFile file)
    {
      if (file == null || file.Length == 0)
        Exceptions.ServerError("Invalid file.");

      var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');

      using (var stream = file.OpenReadStream())
        await DeployManager.Upload(stream, fileName);
    }
开发者ID:andrewmelnichuk,项目名称:repo2,代码行数:10,代码来源:UploadsController.cs

示例12: UploadAvatar

        public string UploadAvatar(IFormFile file, string key)
        {
            if (file.Length >= 300000)
                throw new Exception("Uploaded image may not exceed 300 kb, please upload a smaller image.");

            try
            {
                using (var readStream = file.OpenReadStream())
                {
                    using (var img = Image.FromStream(readStream))
                    {
                        if (!img.RawFormat.Equals(ImageFormat.Jpeg) && !img.RawFormat.Equals(ImageFormat.Png))
                            throw new Exception("Uploaded file is not recognized as an image.");

                        var tempFile = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());

                        try
                        {
                            ImageBuilder.Current.Build(img, tempFile, new Instructions
                            {
                                Width = 150,
                                Height = 150,
                                Format = "jpg",
                                Mode = FitMode.Max
                            });

                            var avatar = _avatarDirectoryInfo.GetFile(key + ".jpg");
                            if (avatar.Exists)
                                avatar.Delete();
                            avatar.Open(FileMode.Create, stream =>
                            {
                                using (var imageStream = File.OpenRead(tempFile))
                                    imageStream.CopyTo(stream);
                            });
                        }
                        catch (Exception ex)
                        {
                            throw new Exception("Uploaded file is not recognized as a valid image.", ex);
                        }
                        finally
                        {
                            if (File.Exists(tempFile))
                                File.Delete(tempFile);
                        }

                        return key;
                    }
                }
            }
            catch (Exception)
            {
                throw new Exception("Uploaded file is not recognized as an image.");
            }
        }
开发者ID:skimur,项目名称:skimur,代码行数:54,代码来源:AvatarService.cs

示例13: CkeditorUploadImage

        public async Task<ActionResult> CkeditorUploadImage(IFormFile upload, string CKEditorFuncNum, string CKEditor)
        {
            string fileName = ContentDispositionHeaderValue.Parse(upload.ContentDisposition).FileName.Trim('"');
            string format = fileName.Split(".".ToCharArray())[1];
            string newFileName = DateTime.Now.ToString("ddMMyyyyhhmmssffff") + "." + format;
            string path = this._environment.WebRootPath + @"\img\" + newFileName;
            await upload.SaveAsAsync(path);
            string baseUrl = Request.Scheme+"://"+Request.Host.Value;
            return this.Content("<script language='javascript' type = 'text/javascript'> window.parent.CKEDITOR.tools.callFunction(" + CKEditorFuncNum +
                   ", '" + baseUrl + @"/img/" + newFileName + "', '');</script>", "text/html");

        }
开发者ID:benedict1986,项目名称:MyBlogWithASP.NET,代码行数:12,代码来源:BlogController.cs

示例14: Import

 public IActionResult Import(IFormFile file)
 {
     var src = new List<RxLevPoint>();
     var fname = Guid.NewGuid().ToString().Replace("-", "") + System.IO.Path.GetExtension(file.GetFileName());
     var path = System.IO.Path.Combine(System.IO.Path.GetTempPath(), fname);
     file.SaveAs(path);
     string connStr;
     if (System.IO.Path.GetExtension(path) == ".xls")
         connStr = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + path + ";" + ";Extended Properties=\"Excel 8.0;HDR=NO;IMEX=1\"";
     else
         connStr = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + path + ";" + ";Extended Properties=\"Excel 12.0;HDR=NO;IMEX=1\"";
     using (var conn = new OleDbConnection(connStr))
     {
         conn.Open();
         var schemaTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
         var rows = schemaTable.Rows;
         foreach (System.Data.DataRow r in rows)
         {
             if (r["TABLE_NAME"].ToString() == "_xlnm#_FilterDatabase")
                 continue;
             var cmd = new OleDbCommand($"select * from [{r["TABLE_NAME"].ToString()}]", conn);
             var reader = cmd.ExecuteReader();
             var flag = reader.Read();
             var cities = User.Claims.Where(x => x.Type == "有权限访问地市数据").Select(x => x.Value).ToList();
             if (flag)
             {
                 while (reader.Read())
                 {
                     try
                     {
                         src.Add(new RxLevPoint
                         {
                             Lon = Convert.ToDouble(reader[0]),
                             Lat = Convert.ToDouble(reader[1]),
                             Signal = Convert.ToInt32(reader[2])
                         });
                     }
                     catch
                     {
                     }
                 }
             }
         }
     }
     var ret = Algorithms.p2l.Handle(src);
     DB.RxLevLines.AddRange(ret);
     DB.SaveChanges();
     return Prompt(x =>
     {
         x.Title = "导入成功";
         x.Details = "RxLev信息导入成功";
     });
 }
开发者ID:CodeCombLLC,项目名称:ChinaTower,代码行数:53,代码来源:PavementController.cs

示例15: GetImageExtension

 public static string GetImageExtension(IFormFile imageFile)
 {
     switch (imageFile.ContentType)// Accept only png, bmp, jpeg, jpg file
     {
         case "image/png":
             return ".png";
         case "image/bmp":
             return ".bmp";
         case "image/jpeg":
             return ".jpg";
     }
     return null;
 }
开发者ID:Thetyne,项目名称:BodyReport,代码行数:13,代码来源:ImageUtils.cs


注:本文中的IFormFile类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。