public async Task <bool> UploadVideoData([FromForm] Microsoft.AspNetCore.Http.IFormFile body) { byte[] fileBytes; using (var memoryStream = new MemoryStream()) { await body.CopyToAsync(memoryStream); fileBytes = memoryStream.ToArray(); if (!Directory.Exists("./Videos")) { Directory.CreateDirectory("Videos"); } } var filename = "./Videos/" + body.FileName; var contentType = body.ContentType; bool fileWrite = ByteArrayToFile(filename, fileBytes); var user = await _userManager.FindByNameAsync("ezaz"); if (user.Videos == null) { user.Videos = new List <Video>(); } Video video = new Video(); video.Path = filename; video.UploadTime = DateTime.Now; video.Description = "in Progress"; user.Videos.Add(video); await _userManager.UpdateAsync(user); return(true); }
public async Task <IActionResult> ImportStatus(int vendorCodeId, Microsoft.AspNetCore.Http.IFormFile excelFile) { if (excelFile == null || Path.GetExtension(excelFile.FileName).ToLower() != ".xls") { AlertDanger = "You must select an .xls file."; ModelState.AddModelError("excelFile", "You must select an .xls file."); } if (ModelState.ErrorCount == 0) { var tempFile = Path.GetTempFileName(); using (var fileStream = new FileStream(tempFile, FileMode.Create)) { await excelFile.CopyToAsync(fileStream); } string file = WebUtility.UrlEncode(Path.GetFileName(tempFile)); return(RedirectToAction("ImportFile", new { id = file })); } else { return(RedirectToAction("ImportStatus")); } }
public static void ZipIFormFile(string path, Microsoft.AspNetCore.Http.IFormFile File) { using (var archive = ZipFile.Open(path + ".zip", ZipArchiveMode.Create)) { archive.CreateEntryFromFile(FilepathUtils.GetPath(File, true), File.FileName); } }
public IActionResult Edit(Page page, Microsoft.AspNetCore.Http.IFormFile Image) { if (ModelState.IsValid) { //получаем все элементы и проверяем есть ли элемент с таким же url IQueryable <Page> pages = dataManager.Pages.GetPages(); foreach (var item in pages) { if (item.Id != page.Id && item.Url == page.Url) { ModelState.AddModelError(nameof(Page.Url), "Запись с таким URL уже есть"); return(View(page)); } } if (Image.IsImage()) { //записываем в объект путь к картинке page.Image = Image.FileName; //сохраняем картинку using (var img = System.Drawing.Image.FromStream(Image.OpenReadStream(), true, true)) { //создаём измененную картинку var i = new Bitmap(img.ScaleAndCrop(1920, 1280, TargetSpot.BottomMiddle)); //сохраняем картинку i.SaveAs(Path.Combine(hostEnvironment.WebRootPath, "images/pages/", Image.FileName)); } } //сохраняем запись dataManager.Pages.SavePage(page); //выходим на главную return(RedirectToAction(nameof(HomeController.Index), nameof(HomeController).CutController())); } return(View(page)); }
private static async Task UploadMovieAsync(string MovieTitle, Microsoft.AspNetCore.Http.IFormFile file) { // get the file and convert it to the byte[] byte[] fileBytes = new Byte[file.Length]; file.OpenReadStream().Read(fileBytes, 0, Int32.Parse(file.Length.ToString())); // create unique file name for prevent the mess //var fileName = Guid.NewGuid() + file.FileName; PutObjectResponse response = null; using (var stream = new MemoryStream(fileBytes)) { var request = new PutObjectRequest { BucketName = bucketName, Key = MovieTitle, InputStream = stream, ContentType = file.ContentType, CannedACL = S3CannedACL.PublicRead }; response = await s3.PutObjectAsync(request); }; if (response.HttpStatusCode == System.Net.HttpStatusCode.OK) { Debug.WriteLine("File uploaded"); } }
public ActionResult Create(Calisan calisan, Microsoft.AspNetCore.Http.IFormFile Image) { calisan.Id = Guid.NewGuid().ToString(); var maas = _maasManager.GetById(calisan.MaasId); ViewBag.Maasies = _maasManager.GetAll(); calisan.Maas = maas; if (!ModelState.IsValid) { return View("Create"); } if (Image != null) { MemoryStream memoryStream = new MemoryStream(); Image.OpenReadStream().CopyTo(memoryStream); calisan.Image = Convert.ToBase64String(memoryStream.ToArray()); } else { calisan.Image = ""; } bool isSaved = _calisanManager.Add(calisan); string mgs = ""; if (isSaved) { return RedirectToAction("Index"); } else { mgs = "Save hatasi"; } ViewBag.Mgs = mgs; return View(); }
public static async Task <Guid> UploadAsObjectAsync(this Microsoft.AspNetCore.Http.IFormFile file) { Guid fileId = Guid.NewGuid(); Models.StorageAccountSettings storageAccountSettings = Common.CurrentStorageAccountSettings; CloudStorageAccount storageAccount = CloudStorageAccount.Parse(storageAccountSettings.ConnectionString); CloudBlobClient client = storageAccount.CreateCloudBlobClient(); CloudBlobContainer container = client.GetContainerReference(storageAccountSettings.UploadsContainerName); CloudBlockBlob blob = null; try { string fileName = $"{fileId}.{file.FileName.Split('.').Last()}"; blob = container.GetBlockBlobReference(fileName); using (var outputStream = await blob.OpenWriteAsync()) { await file.CopyToAsync(outputStream); } } catch (Exception ex) { } return(fileId); }
public async Task UploadPhoto(int userId, PhotoCreateDto model) { //var file = model.File; Microsoft.AspNetCore.Http.IFormFile file = model.File; var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/assets/images/", userId.ToString(), file.FileName); using (var db = base.NewDb()) { using (var stream = System.IO.File.Create(path)) { await file.CopyToAsync(stream); } bool isMain = true; if (await HasMainPhoto(userId)) { isMain = false; } var memberPhoto = new MemberPhoto() { UserId = userId, AddedDate = System.DateTime.Now, Descriptions = model.descriptions ?? file.FileName, IsMain = isMain, PhotoUrl = path }; db.Add(memberPhoto); await db.SaveChangesAsync(); return; } }
private async Task <string> UploadPhotoAsync(Microsoft.AspNetCore.Http.IFormFile img) { string urlPhoto = Guid.NewGuid().ToString() + "_" + DateTime.Now.ToString("yyyyMMddHHmmss") + "_" + img.FileName; Uri uri = await this._documentService.UploadAsync(img.OpenReadStream(), img.ContentType, urlPhoto); return(uri.AbsoluteUri); }
public JsonResult SaveExcel([FromQuery] string filename, Microsoft.AspNetCore.Http.IFormFile excelFile) { ResponseResult result = new ResponseResult(); string targetDirectory = "\\wwwroot\\uploadfiles"; //检查相应目录 if (!Directory.Exists(targetDirectory)) { Directory.CreateDirectory(targetDirectory); } int bufferThreshold = 5120000; //500k bufferThreshold 设置的是 Request.Body 最大缓存字节数(默认是30K) 超出这个阈值的字节会被写入磁盘 int bufferLimit = 10240000; //1m 设置的是 Request.Body 允许的最大字节数(默认值是null),超出这个限制,就会抛出异常 System.IO.IOException HttpContext.Request.Body.Position = 0; if (this.Request.ContentLength > 0 && this.Request.Body != null && this.Request.Body.CanRead) { Encoding encoding = System.Text.UTF8Encoding.Default; using (var buffer = new MemoryStream()) { HttpContext.Request.Body.CopyTo(buffer); buffer.Flush(); buffer.Position = 0; buffer.ToFile(Path.Combine(targetDirectory, "a.jpg")); } } return(Json(result)); }
private string ConverterToBase64(Microsoft.AspNetCore.Http.IFormFile file) { using (var ms = new System.IO.MemoryStream()) { file.CopyTo(ms); return(Convert.ToBase64String(ms.ToArray())); } }
public IActionResult Quote(Microsoft.AspNetCore.Http.IFormFile file) { var jsonToReturn = new { gasPrice = "1,00" }; return(Json(jsonToReturn)); }
public IActionResult UploadFile(Microsoft.AspNetCore.Http.IFormFile file) { String rootpath = System.IO.Directory.GetCurrentDirectory() + @"\wwwroot\upload\" + file.FileName; System.IO.FileStream flstream = new System.IO.FileStream(rootpath, FileMode.Create); file.CopyTo(flstream); ViewBag.ImageName = file.FileName; return(View("Index")); }
public async Task <IActionResult> EmailAwardStatus(int vendorCodeTypeId, Microsoft.AspNetCore.Http.IFormFile excelFile) { if (excelFile == null || !string.Equals(Path.GetExtension(excelFile.FileName), ".xls", StringComparison.OrdinalIgnoreCase)) { AlertDanger = "You must select an .xls file."; ModelState.AddModelError("excelFile", "You must select an .xls file."); return(RedirectToAction(nameof(EmailAward))); } if (ModelState.ErrorCount == 0) { var tempFile = _pathResolver.ResolvePrivateTempFilePath(); _logger.LogInformation("Accepted vendor code type {vendorCodeTypeId} email award file {UploadFile} as {TempFile}", vendorCodeTypeId, excelFile.FileName, tempFile); using (var fileStream = new FileStream(tempFile, FileMode.Create)) { await excelFile.CopyToAsync(fileStream); } string file = WebUtility.UrlEncode(Path.GetFileName(tempFile)); var site = await GetCurrentSiteAsync(); var jobToken = await _jobService.CreateJobAsync(new Job { JobType = JobType.UpdateEmailAwardStatus, SerializedParameters = JsonConvert .SerializeObject(new JobDetailsVendorCodeStatus { VendorCodeTypeId = vendorCodeTypeId, Filename = file, SiteName = site.Name }) }); return(View("Job", new ViewModel.MissionControl.Shared.JobViewModel { CancelUrl = Url.Action(nameof(EmailAward)), JobToken = jobToken.ToString(), PingSeconds = 5, SuccessRedirectUrl = "", SuccessUrl = Url.Action(nameof(EmailAward)), Title = "Loading email award status..." })); } else { return(RedirectToAction(nameof(EmailAward))); } }
public async Task <IActionResult> UploadFile(Microsoft.AspNetCore.Http.IFormFile fileToUpload, string container, CancellationToken ct) { using (var stream = fileToUpload.OpenReadStream()) { var uploadRequestHeaders = fileToUpload.Headers; var allContent = await this.storageProvider.Upload(stream, container, fileToUpload.FileName, fileToUpload.ContentType, ct); return(Ok(allContent)); } }
public void Upload(Microsoft.AspNetCore.Http.IFormFile file) { try { Instance.UploadObject("go-logs-304513.appspot.com", file.FileName, file.ContentType, file.OpenReadStream()); } catch (Exception e) { System.Diagnostics.Debug.WriteLine(e); } }
public void SaveFile(string id, string folderName, Microsoft.AspNetCore.Http.IFormFile file) { try { var fileName = id.ToString() + Path.GetExtension(file.FileName); var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", folderName, fileName); using (var stream = new FileStream(path, FileMode.Create)) { file.CopyTo(stream); } } catch (Exception ex) { } }
public ResultView SetHeadImg(string employeeId, Microsoft.AspNetCore.Http.IFormFile imageFile) { string webFile = $"~/wwwroot/UploadFiles/Employee/Head/{employeeId}/{Guid.NewGuid().ToString()}"; UploadFileInfo file = UploadFileHandle.UploadImage(webFile, imageFile); var info = _Service._SearchById(employeeId); UploadFileHandle.Delete(info.HeadImg); info.HeadImg = file.WebFileName; _Service.Update(info, LogonInfo); return(ResultView.Success("头像修改成功")); }
public void SetImage(Microsoft.AspNetCore.Http.IFormFile file) { if (file == null) { return; } ImageContentType = file.ContentType; using var stream = new System.IO.MemoryStream(); file.CopyTo(stream); Image = stream.ToArray(); }
public string Upload(Microsoft.AspNetCore.Http.IFormFile file, string path = "wwwroot/uploads") { var fileName = DateTime.Now.ToString("yyyyMMddHHmmssff") + Path.GetExtension(file.FileName); var uploadPath = Path.Combine(Directory.GetCurrentDirectory(), path, fileName); using (var stream = new FileStream(uploadPath, FileMode.Create)) { file.CopyTo(stream); } return(fileName); }
public virtual async Task <IEnumerable <SaveResult <CaseDto> > > CsvUpload(Microsoft.AspNetCore.Http.IFormFile file, bool hasHeader = true) { if (file != null && file.Length > 0) { using (var stream = file.OpenReadStream()) { using (var reader = new System.IO.StreamReader(stream)) { var csv = reader.ReadToEnd(); return(await CsvSave(csv, hasHeader)); } } } throw new ArgumentException("No files uploaded"); }
public IActionResult Add([FromForm] Vlag vlag, [FromForm] IFormFile image) { Vlag toAddVlag = vlag; if (image != null) { image.CopyTo(new FileStream("wwwroot/images/vlag/" + image.FileName, FileMode.Create)); toAddVlag.Afbeelding = "/images/vlag/" + image.FileName; } mgr.AddVlag(toAddVlag); return(RedirectToAction("Index")); }
public void SetImage(Microsoft.AspNetCore.Http.IFormFile file) { if (file == null) { return; } FileName = file.ContentType; using (var stream = new System.IO.MemoryStream()) { file.CopyTo(stream); Attachment = stream.ToArray(); } }
public ActionResult Upload() { try { Microsoft.AspNetCore.Http.IFormFile file = Request.Form.Files[0]; return(Content(SaveFileUtils.SaveFile(file))); } catch (System.Exception e) { Console.WriteLine(e); return(StatusCode(500)); } }
private async Task <UploadStatus> uploadFile(Microsoft.AspNetCore.Http.IFormFile media, string newFileName) { string message = string.Empty; bool status = false; if (media != null) { // Create full path and save the original media file newFileName = string.IsNullOrWhiteSpace(newFileName) ? media.FileName:newFileName; var saveDir = Path.Combine("aspnetcore_files", newFileName); if (System.IO.File.Exists("aspnetcore_files/" + newFileName)) { newFileName = Guid.NewGuid().ToString() + ".png"; saveDir = Path.Combine("aspnetcore_files", newFileName); } using (var stream = new FileStream(saveDir, FileMode.Create)) { var ext = Path.GetExtension(media.FileName); var fAllows = _config.AllowFileType.Contains(ext.ToLower()); if (fAllows == false) { message = "File hanya diperbolehkan " + _config.AllowFileType; return(new UploadStatus { FileName = message, Status = status }); } if (media.Length < _config.MaxSizeUploadFile && fAllows) { await media.CopyToAsync(stream); message = newFileName; status = true; } else { message = "File maksimal berukuran " + (_config.MaxSizeUploadFile / 1048576) + "Mb"; } } } return(new UploadStatus { FileName = message, Status = status }); }
public static DataFile Create(Microsoft.AspNetCore.Http.IFormFile file) { var result = new DataFile { Name = file.FileName, Type = file.ContentType }; using (var stream = file.OpenReadStream()) { var reader = new System.IO.BinaryReader(stream); reader.BaseStream.Seek(0, System.IO.SeekOrigin.Begin); result.Content = reader.ReadBytes((int)reader.BaseStream.Length); } return(result); }
public static String GetExtention(Microsoft.AspNetCore.Http.IFormFile file) { String mediaType = file.ContentType; String returnString = null; for (byte i = 0; i < mediaTypes.GetLength(0); i++) { if (mediaType == mediaTypes[i, 0]) { returnString = mediaTypes[i, 1]; break; } } return(returnString); }
public static String GetPath(Microsoft.AspNetCore.Http.IFormFile File, Boolean tmp) { String folder; if (tmp) { folder = "tmp"; } else { folder = "image"; } String filePath = @"./" + folder + "/" + GetFileName(File); return(filePath); }
public async Task <string> UploadFileAsync(Microsoft.AspNetCore.Http.IFormFile file) { string ext = Path.GetExtension(file.FileName); string filepath = $"files/{Path.GetRandomFileName()}{ext}"; int tries = 1; while (File.Exists(filepath)) { filepath = $"files/{Path.GetRandomFileName()}_{tries}{ext}"; } using var fileStream = new FileStream(filepath, FileMode.Create); _Logger.LogInformation($"Uploading file to \"{filepath}\""); await file.CopyToAsync(fileStream); fileStream.Close(); return(filepath); }
public static string PostApi(string ApiUrl, Microsoft.AspNetCore.Http.IFormFile formFiles) { var request = (HttpWebRequest)WebRequest.Create(ApiUrl); string postData = "{FileName:abc}"; var data = Encoding.ASCII.GetBytes(postData); request.Method = "POST"; request.ContentType = "application/form-data"; request.ContentLength = data.Length; using (var stream = request.GetRequestStream()) { stream.Write(data, 0, data.Length); } var response = (HttpWebResponse)request.GetResponse(); var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd(); return(responseString); }