本文整理汇总了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));
}
示例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);
}
示例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);
}
}
示例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);
}
示例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();
}
示例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;
}
示例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()
});
}
示例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);
}
示例9: Upload
public async Task<IActionResult> Upload(IFormFile file, string userId)
{
var fileId = await _fileHandler.HandleUpload(file);
await _userHandler.AddFileToUserMapping(userId, fileId);
return View();
}
示例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);
}
示例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);
}
示例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.");
}
}
示例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");
}
示例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信息导入成功";
});
}
示例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;
}