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


C# IFormFile.SaveAsAsync方法代码示例

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


在下文中一共展示了IFormFile.SaveAsAsync方法的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: 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

示例3: 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.SaveAsAsync(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
         var appUser = await GetCurrentUserAsync();
         User user;
         user = _context.Consumers.FirstOrDefault(x => x.Email == appUser.Email);
         if(user == null)
         {
             user = _context.Producers.FirstOrDefault(x => x.Email == appUser.Email);
         }
         news.User = user;
         _context.News.Add(news);
         _context.SaveChanges();
         return RedirectToAction("Index");
     }
     return View(news);
 }
开发者ID:ChavFDG,项目名称:Old-Stolons,代码行数:31,代码来源:NewsController.cs

示例4: 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

示例5: Post

 public async Task Post(string name, IFormFile file)
 {
     var beer = new Beer { Name = name };
     if (file != null)
     {
         var filename = ContentDispositionHeaderValue
             .Parse(file.ContentDisposition)
             .FileName
             .Trim('"');
         
         beer.Picture = "http://localhost:5000/Images/" + filename;
         await file.SaveAsAsync("C:\\Code\\personal\\app-to-app-uwp\\Inventory.API\\wwwroot\\Images\\" + filename);
     }
     beers.Add(beer);
 }
开发者ID:acasquete,项目名称:app-to-app-uwp,代码行数:15,代码来源:BeersController.cs

示例6: Create

 public async Task<IActionResult> Create(IFormFile file)
 {
     try
     {
         var uploads = Path.Combine(_environment.WebRootPath,"uploads");
         var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
         FileUpload01.Models.File newFile = new FileUpload01.Models.File();
         newFile.ImagePath = fileName;
         _db.Uploads.Add(newFile);
         _db.SaveChanges();
         await file.SaveAsAsync(Path.Combine(uploads, fileName));
         return RedirectToAction("Index");
     }
     catch (Exception ex)
     {
         System.Diagnostics.Debug.Write(ex);
         return View();
     }
 }
开发者ID:jmk22,项目名称:FileUpload01,代码行数:19,代码来源:HomeController.cs

示例7: Create

        public async Task<IActionResult> Create(UserStolonViewModel vmConsumer, IFormFile uploadFile)
        {
            if (ModelState.IsValid)
            {
                #region Creating Consumer
                string fileName = Configurations.DefaultFileName;
                if (uploadFile != null)
                {
                    //Image uploading
                    string uploads = Path.Combine(_environment.WebRootPath, Configurations.UserAvatarStockagePath);
                    fileName = Guid.NewGuid().ToString() + "_" + ContentDispositionHeaderValue.Parse(uploadFile.ContentDisposition).FileName.Trim('"');
                    await uploadFile.SaveAsAsync(Path.Combine(uploads, fileName));
                }
                //Setting value for creation
                vmConsumer.Consumer.Avatar = Path.Combine(Configurations.UserAvatarStockagePath, fileName);
                vmConsumer.Consumer.RegistrationDate = DateTime.Now;
                vmConsumer.Consumer.Name = vmConsumer.Consumer.Name.ToUpper();
                _context.Consumers.Add(vmConsumer.Consumer);
                #endregion Creating Consumer

                #region Creating linked application data
                var appUser = new ApplicationUser { UserName = vmConsumer.Consumer.Email, Email = vmConsumer.Consumer.Email };
                appUser.User = vmConsumer.Consumer;
                
                var result = await _userManager.CreateAsync(appUser, vmConsumer.Consumer.Email);
                if (result.Succeeded)
                {
                    //Add user role
                    result = await _userManager.AddToRoleAsync(appUser, vmConsumer.UserRole.ToString());
                    //Add user type
                    result = await _userManager.AddToRoleAsync(appUser, Configurations.UserType.Consumer.ToString());
                }
                #endregion Creating linked application data

                _context.SaveChanges();
                //Send confirmation mail
                Services.AuthMessageSender.SendEmail(vmConsumer.Consumer.Email, vmConsumer.Consumer.Name, "Creation de votre compte", base.RenderPartialViewToString("UserCreatedConfirmationMail", vmConsumer));

                return RedirectToAction("Index");
            }
            return View(vmConsumer);
        }
开发者ID:ChavFDG,项目名称:Old-Stolons,代码行数:42,代码来源:UsersController.cs

示例8: SaveProfileImage

        public async System.Threading.Tasks.Task<CommonResult<UploadImageResult>> SaveProfileImage(IFormFile file)
        {
            var fileName = Guid.NewGuid().ToString() + ".jpg";

            var filePath = _configurationProvider.GetProfileOriginalImagesFolderPath() + fileName;

            await file.SaveAsAsync(filePath);

            UpdateUserProfileImage(StaticManager.UserName, fileName);

            var image = Image.FromFile(filePath);

            return CommonResult<UploadImageResult>.Success(new UploadImageResult
            {
                Status = "success",
                Width = image.Width,
                Height = image.Height,
                Url = _configurationProvider.GetProfileOriginalImagesFolderInternalPath() + fileName
            });
        }
开发者ID:psmyrdek,项目名称:it-learning,代码行数:20,代码来源:UserService.cs

示例9: Create

        public async Task<IActionResult> Create(Barber barber, IFormFile image)
        {
            if (ModelState.IsValid)
            {
                var uploads = Path.Combine(_environment.WebRootPath, "ProfilePicPath");
                if (image != null)
                {
                    var fileName = ContentDispositionHeaderValue.Parse(image.ContentDisposition).FileName.Trim('"');
                    await image.SaveAsAsync(Path.Combine(uploads, fileName));
                    barber.ProfilePicPath = fileName;
                }
                
                _context.Barbers.Add(barber);
                _context.SaveChanges();
                

                return RedirectToAction("Index");
            }
            return View(barber);
        }
开发者ID:scottapow,项目名称:WaitlistManager,代码行数:20,代码来源:BarbersController.cs

示例10: Index

        public async Task<IActionResult> Index(IFormFile photo, string query, string latitude, string longitude, string elevation, string zoom, bool found)
        {
            if (photo != null)
            {
                Notez note = new Notez
                {
                    Found = found,
                    Timestamp = DateTimeOffset.Now,
                    UserAgent = Request.Headers["User-Agent"],
                    HostAddress = Context.GetFeature<IHttpConnectionFeature>().RemoteIpAddress.ToString(),
                    LocationRaw = query,
                    Latitude = double.Parse(latitude, CultureInfo.InvariantCulture),
                    Longitude = double.Parse(longitude, CultureInfo.InvariantCulture),
                    Zoom = float.Parse(zoom, CultureInfo.InvariantCulture),
                    Elevation = float.Parse(elevation, CultureInfo.InvariantCulture),
                };

                _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(Index), new { noteID = note.ID });
            }

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

示例11: Edit

 public async Task<IActionResult> Edit(ProducerViewModel vmProducer, IFormFile uploadFile, Configurations.Role UserRole)
 {
     if (ModelState.IsValid)
     {
         if (uploadFile != null)
         {
             string uploads = Path.Combine(_environment.WebRootPath, Configurations.UserAvatarStockagePath);
             //Deleting old image
             string oldImage = Path.Combine(uploads, vmProducer.Producer.Avatar);
             if (System.IO.File.Exists(oldImage) && vmProducer.Producer.Avatar != Path.Combine(Configurations.UserAvatarStockagePath, Configurations.DefaultFileName))
                 System.IO.File.Delete(Path.Combine(uploads, vmProducer.Producer.Avatar));
             //Image uploading
             string fileName = Guid.NewGuid().ToString() + "_" + ContentDispositionHeaderValue.Parse(uploadFile.ContentDisposition).FileName.Trim('"');
             await uploadFile.SaveAsAsync(Path.Combine(uploads, fileName));
             //Setting new value, saving
             vmProducer.Producer.Avatar = Path.Combine(Configurations.UserAvatarStockagePath, fileName);
         }
         ApplicationUser producerAppUser = _context.Users.First(x => x.Email == vmProducer.OriginalEmail);
         producerAppUser.Email = vmProducer.Producer.Email;
         _context.Update(producerAppUser);
         //Getting actual roles
         IList<string> roles = await _userManager.GetRolesAsync(producerAppUser);
         if (!roles.Contains(UserRole.ToString()))
         {
             string roleToRemove = roles.FirstOrDefault(x => Configurations.GetRoles().Contains(x));
             await _userManager.RemoveFromRoleAsync(producerAppUser, roleToRemove);
             //Add user role
             await _userManager.AddToRoleAsync(producerAppUser, UserRole.ToString());
         }
         _context.Update(vmProducer.Producer);
         _context.SaveChanges();
         return RedirectToAction("Index");
     }
     return View(vmProducer);
 }
开发者ID:ChavFDG,项目名称:Old-Stolons,代码行数:35,代码来源:ProducersController.cs

示例12: Upload

        public async Task<IActionResult> Upload(IFormFile file)
        {
            var id = Request.Form["id"];

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

            if (fileName.IsImage())
            {
                Directory.CreateDirectory(filePath);

                var savePath = Path.Combine(filePath, fileName);
                await file.SaveAsAsync(savePath);
            }
            return Json(new { FileName = fileName, FilePath = filePath, Success = true });
        }
开发者ID:gwartnes,项目名称:Blogness,代码行数:16,代码来源:AdminController.cs

示例13: UploadAndResizeImageFile

        public static async Task<string> UploadAndResizeImageFile(IHostingEnvironment environment, IFormFile uploadFile, string path)
        {
            string uploads = Path.Combine(environment.WebRootPath, path);
            string fileName = Guid.NewGuid().ToString() + "_" + ContentDispositionHeaderValue.Parse(uploadFile.ContentDisposition).FileName.Trim('"');
	    
            await uploadFile.SaveAsAsync(Path.Combine(uploads, fileName));
            return Path.Combine(path,fileName);
        }
开发者ID:ChavFDG,项目名称:Old-Stolons,代码行数:8,代码来源:Configurations.cs

示例14: UploadFile

        public async Task<JsonResult> UploadFile(IFormFile file)
        {
            string fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
            string path = this._environment.WebRootPath + @"\file\" + fileName;
            await file.SaveAsAsync(path);
            string url = Request.Scheme + "://" + Request.Host.Value + "/file/" + fileName;
            return this.Json(new {name=fileName, path= url });

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

示例15: 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


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