• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C# IFormFile类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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


示例16: Create

        public async Task<IActionResult> Create(int campaignId, ActivityDetailModel activity, IFormFile fileUpload)
        {
            if (activity.EndDateTime < activity.StartDateTime)
            {
                ModelState.AddModelError(nameof(activity.EndDateTime), "End date cannot be earlier than the start date");
            }

                CampaignSummaryModel campaign = _bus.Send(new CampaignSummaryQuery { CampaignId = campaignId });
                if (campaign == null ||
                    !User.IsOrganizationAdmin(campaign.OrganizationId))
                {
                    return HttpUnauthorized();
                }

            if (activity.StartDateTime < campaign.StartDate)
            {
                ModelState.AddModelError(nameof(activity.StartDateTime), "Start date cannot be earlier than the campaign start date " + campaign.StartDate.ToString("d"));
            }

            if (activity.EndDateTime > campaign.EndDate)
            {
                ModelState.AddModelError(nameof(activity.EndDateTime), "End date cannot be later than the campaign end date " + campaign.EndDate.ToString("d"));
            }

            if (ModelState.IsValid)
            {
                if (fileUpload != null)
                {
                    if (!fileUpload.IsAcceptableImageContentType())
                    {
                        ModelState.AddModelError("ImageUrl", "You must upload a valid image file for the logo (.jpg, .png, .gif)");
                        return View("Edit", activity);
                    }
                }

                activity.OrganizationId = campaign.OrganizationId;
                var id = _bus.Send(new EditActivityCommand { Activity = activity });

                if (fileUpload != null)
                {
                    // resave now that activty has the ImageUrl
                    activity.Id = id;
                    activity.ImageUrl = await _imageService.UploadActivityImageAsync(campaign.OrganizationId, id, fileUpload);
                    _bus.Send(new EditActivityCommand { Activity = activity });
                }

                return RedirectToAction("Details", "Activity", new { area = "Admin", id = id });
            }
            return View("Edit", activity);
        }
开发者ID:weiplanet,项目名称:allReady,代码行数:50,代码来源:ActivityAdminController.cs


示例17: PerformContentCheck

 public GenericResponseVM PerformContentCheck(string clientUrl, string folderUrl, IFormFile uploadedFile, string fileName)
 {
     GenericResponseVM genericResponse = null;
     ClientContext clientContext = spoAuthorization.GetClientContext(clientUrl);
     using (MemoryStream targetStream = new MemoryStream())
     {
         Stream sourceStream = uploadedFile.OpenReadStream();
         try
         {
             byte[] buffer = new byte[sourceStream.Length + 1];
             int read = 0;
             while ((read = sourceStream.Read(buffer, 0, buffer.Length)) > 0)
             {
                 targetStream.Write(buffer, 0, read);
             }
             string serverFileUrl = folderUrl + ServiceConstants.FORWARD_SLASH + fileName;
             bool isMatched = documentRepository.PerformContentCheck(clientContext, targetStream, serverFileUrl);
             if (isMatched)
             {
                 //listResponse.Add(string.Format(CultureInfo.InvariantCulture, "{0}{1}{1}{1}{2}", ConstantStrings.FoundIdenticalContent, ConstantStrings.Pipe, ConstantStrings.TRUE));
                 genericResponse = new GenericResponseVM()
                 {
                     IsError = true,
                     Code = UploadEnums.IdenticalContent.ToString(),
                     Value = string.Format(CultureInfo.InvariantCulture, errorSettings.FoundIdenticalContent)
                 };
             }
             else
             {
                 genericResponse = new GenericResponseVM()
                 {
                     IsError = true,
                     Code = UploadEnums.NonIdenticalContent.ToString(),
                     Value = string.Format(CultureInfo.InvariantCulture, errorSettings.FoundNonIdenticalContent)
                 };                        
             }
         }
         catch (Exception exception)
         {
             //Logger.LogError(exception, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, UIConstantStrings.LogTableName);
             //response = string.Format(CultureInfo.InvariantCulture, "{0}{1}{1}{1}{2}", ConstantStrings.ContentCheckFailed, ConstantStrings.Pipe, ConstantStrings.TRUE);
         }
         finally
         {
             sourceStream.Dispose();
         }
     }
     return genericResponse;
 }
开发者ID:Microsoft,项目名称:mattercenter,代码行数:49,代码来源:UploadHelperFunctions.cs


示例18: UploadImageAsync

        private async Task<string> UploadImageAsync(string blobPath, IFormFile image)
        {

            //Get filename
            var fileName = (ContentDispositionHeaderValue.Parse(image.ContentDisposition).FileName).Trim('"').ToLower();
            Debug.WriteLine(string.Format("BlobPath={0}, fileName={1}, image length={2}", blobPath, fileName, image.Length.ToString()));

            if (fileName.EndsWith(".jpg") || fileName.EndsWith(".jpeg") || fileName.EndsWith(".png"))
            {
                string storageConnectionString = _config["Data:Storage:AzureStorage"];

                CloudStorageAccount account = CloudStorageAccount.Parse(storageConnectionString);
                CloudBlobContainer container =
                    account.CreateCloudBlobClient().GetContainerReference(CONTAINER_NAME);

                //Create container if it doesn't exist wiht public access
                await container.CreateIfNotExistsAsync(BlobContainerPublicAccessType.Container, new BlobRequestOptions(), new OperationContext());

                string blob = blobPath + "/" + fileName;
                Debug.WriteLine("blob" + blob);

                CloudBlockBlob blockBlob = container.GetBlockBlobReference(blob);

                blockBlob.Properties.ContentType = image.ContentType;

                using (var imageStream = image.OpenReadStream())
                {
                    //Option #1
                    byte[] contents = new byte[image.Length];

                    for (int i = 0; i < image.Length; i++)
                    {
                        contents[i] = (byte)imageStream.ReadByte();
                    }

                    await blockBlob.UploadFromByteArrayAsync(contents, 0, (int)image.Length);

                    //Option #2
                    //await blockBlob.UploadFromStreamAsync(imageStream);
                }

                Debug.WriteLine("Image uploaded to URI: " + blockBlob.Uri.ToString());
                return blockBlob.Uri.ToString();
            }
            else
            {
                throw new Exception("Invalid file extension: " + fileName + "You can only upload images with the extension: jpg, jpeg, or png");
            }
        }
开发者ID:rspaulino,项目名称:allReady,代码行数:49,代码来源:ImageService.cs


示例19: UpdateDocumentAndStatus

 public IActionResult UpdateDocumentAndStatus(IFormFile document)
 {
     try
     {
         if (document == null)
         {
             return HttpBadRequest();
         }
         return Ok();
     }
     catch (Exception ex)
     {
         return HttpBadRequest();
     }
 }
开发者ID:jruckert,项目名称:WindowsAuthOnly,代码行数:15,代码来源:TestController.cs


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



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# IFormatProvider类代码示例发布时间:2022-05-24
下一篇:
C# IFormFactory类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap