本文整理汇总了C#中IFormFile.OpenReadStream方法的典型用法代码示例。如果您正苦于以下问题:C# IFormFile.OpenReadStream方法的具体用法?C# IFormFile.OpenReadStream怎么用?C# IFormFile.OpenReadStream使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类IFormFile
的用法示例。
在下文中一共展示了IFormFile.OpenReadStream方法的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: 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);
}
示例4: 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.");
}
}
示例5: 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;
}
示例6: 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");
}
}
示例7: UploadSingle
public FileDetails UploadSingle(IFormFile file)
{
FileDetails fileDetails;
using (var reader = new StreamReader(file.OpenReadStream()))
{
var fileContent = reader.ReadToEnd();
var parsedContentDisposition = ContentDispositionHeaderValue.Parse(file.ContentDisposition);
fileDetails = new FileDetails
{
Filename = parsedContentDisposition.FileName,
Content = fileContent
};
}
return fileDetails;
}
示例8: UploadImage
public async Task<String> UploadImage(IFormFile image, long id)
{
// Create client and use it to upload object to Cloud Storage
var client = await StorageClient
.FromApplicationCredentials(_applicationName);
var imageAcl = ObjectsResource
.InsertMediaUpload.PredefinedAclEnum.PublicRead;
var imageObject = await client.UploadObjectAsync(
bucket: _bucketName,
objectName: id.ToString(),
contentType: image.ContentType,
source: image.OpenReadStream(),
options: new UploadObjectOptions { PredefinedAcl = imageAcl }
);
return imageObject.MediaLink;
}
示例9: SaveImage
//TODO: Need to be able to test this...FrameworkIssues
public Image SaveImage(string fileName, string description, IFormFile file)
{
Image image;
using (var reader = new StreamReader(file.OpenReadStream()))
{
var fileContent = reader.ReadToEnd();
var parsedContentDisposition = ContentDispositionHeaderValue.Parse(file.ContentDisposition);
image = new Image
{
FileName = parsedContentDisposition.FileName,
Content = fileContent,
Description = description,
UploadDate = DateTime.UtcNow,
ImagePath = Path.Combine(_applicationEnvironment.ApplicationBasePath, BlogImageDatabasePath, parsedContentDisposition.FileName)
};
}
return image;
}
示例10: Upload
public IActionResult Upload(string ApiKey, IFormFile ProjectPackage)
{
if (ProjectPackage == null)
{
return HttpBadRequest();
}
if (string.IsNullOrWhiteSpace(ApiKey))
{
// Not accepting empty API key -> Disable API upload to projects by setting the API key empty
return HttpNotFound();
}
var projectEntry = Context.DocumentationProjects.FirstOrDefault(Project => Project.ApiKey == ApiKey);
if (projectEntry == null)
{
return HttpNotFound();
}
// Try to read as zip file
using (var inputStream = ProjectPackage.OpenReadStream())
{
try
{
using (var archive = new ZipArchive(inputStream))
{
var physicalRootDirectory = HostingEnvironment.MapPath("App_Data/");
var result = ProjectWriter.CreateProjectFilesFromZip(archive, physicalRootDirectory, projectEntry.Id, Context);
if (!result)
{
return HttpBadRequest();
}
}
return Ok();
}
catch (InvalidDataException caughtException)
{
return HttpBadRequest(new {Error = "Could not read file as zip."});
}
catch
{
return HttpBadRequest();
}
}
}
示例11: Avatar
public async Task<IActionResult> Avatar(int id, IFormFile avatar)
{
var player = await LoadAndEnsurePlayerExists(id);
if (avatar.Length > 0)
{
var settings = new ResizeSettings
{
MaxWidth = 150,
MaxHeight = 150,
Format = "png"
};
var outputStream = new MemoryStream();
ImageBuilder.Current.Build(avatar.OpenReadStream(), outputStream, settings);
player.Image = outputStream.ToArray();
await _db.SaveChangesAsync();
}
return RedirectToAction("Index", new { id });
}
示例12: 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));
}
示例13: UploadPhotoAsync
/// <summary>
/// Upload a photo to the Azure Blob Storage Service
/// </summary>
/// <param name="photoToUpload"></param>
/// <param name="fileName">Optional. Will use a random GUID if no filename defined</param>
/// <returns></returns>
public async Task<string> UploadPhotoAsync(IFormFile photoToUpload, string fileName = "")
{
if (photoToUpload == null || photoToUpload.Length == 0)
return null;
var parsedContentDisposition = ContentDispositionHeaderValue.Parse(photoToUpload.ContentDisposition);
//check file size and upload
if (!FileSizeIsValid(photoToUpload))
return null;
using (var photoStream = photoToUpload.OpenReadStream())
{
return await UploadPhotoAsync(photoStream, fileName);
}
}
示例14: UploadMomentFile
public void UploadMomentFile(Guid momentId, IFormFile file,int count=1)
{
var fileName = file.ContentDisposition.Split(';')[2].Split('=')[1].Replace("\"", "");
try
{
var moment = MomentExistsResult.Check(this.m_MomentManager, momentId).ThrowIfFailed().Moment;
using (var reader = new StreamReader(file.OpenReadStream()))
{
m_MomentFileManager.CreateMementFile(moment.Id, file.ContentType, reader.BaseStream,fileName);
}
}
catch
{
this.DeleteMoment(momentId);
throw new FineWorkException($"{fileName}上传失败.");
}
}
示例15: UploadProject
public IActionResult UploadProject(Guid ProjectId, IFormFile projectPackage)
{
if (projectPackage == null)
{
ModelState.AddModelError("", "Please select a file to upload.");
return View();
}
var projectEntry = Context.DocumentationProjects.FirstOrDefault(Project => Project.Id == ProjectId);
if (projectEntry == null)
{
return HttpNotFound();
}
// Try to read as zip file
using (var inputStream = projectPackage.OpenReadStream())
{
try
{
using (var archive = new ZipArchive(inputStream))
{
var physicalRootDirectory = HostingEnvironment.MapPath("App_Data/");
var result = ProjectWriter.CreateProjectFilesFromZip(archive, physicalRootDirectory, projectEntry.Id, Context);
if (!result)
{
ModelState.AddModelError(string.Empty, "Failed to update the project files");
return View();
}
}
ViewBag.SuccessMessage = "Uploaded package.";
return View();
}
catch (InvalidDataException caughtException)
{
ModelState.AddModelError("", "Cannot read the file as zip archive.");
return View();
}
catch
{
ModelState.AddModelError("", "Error in request.");
return View();
}
}
}