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 async Task <IActionResult> Edit(int id, Product product, Microsoft.AspNetCore.Http.IFormFile imageFile) { if (id != product.ID) { return(NotFound()); } string newFile = System.IO.Path.Combine(_env.WebRootPath, "images", imageFile.FileName); System.IO.FileInfo newFileInfo = new System.IO.FileInfo(newFile); using (System.IO.FileStream fs = newFileInfo.Create()) { imageFile.CopyTo(fs); fs.Close(); } product.Image = "/images/" + imageFile.FileName; if (ModelState.IsValid) { try { _context.Update(product); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!ProductExists(product.ID)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } return(View(product)); }
/// <summary> /// 导入表数据Excel文件夹 /// </summary> /// <param name="files"></param> /// <returns></returns> public virtual WebResponseContent Import(List <Microsoft.AspNetCore.Http.IFormFile> files) { if (files == null || files.Count == 0) { return new WebResponseContent { Status = true, Message = "请选择上传的文件" } } ; Microsoft.AspNetCore.Http.IFormFile formFile = files[0]; string dicPath = $"Upload/{DateTime.Now.ToString("yyyMMdd")}/{typeof(T).Name}/".MapPath(); if (!Directory.Exists(dicPath)) { Directory.CreateDirectory(dicPath); } dicPath = $"{dicPath}{Guid.NewGuid().ToString()}_{formFile.FileName}"; using (var stream = new FileStream(dicPath, FileMode.Create)) { formFile.CopyTo(stream); } try { Response = EPPlusHelper.ReadToDataTable <T>(dicPath, GetIgnoreTemplate()); } catch (Exception ex) { Response.Error("未能处理导入的文件,请检查导入的文件是否正确"); Logger.Error($"表{typeof(T).GetEntityTableCnName()}导入失败{ex.Message + ex.InnerException?.Message}"); } if (!Response.Status) { return(Response); } repository.AddRange(Response.Data as List <T>, true); return(new WebResponseContent { Status = true, Message = "文件上传成功" }); }
private string SaveContractFile(Microsoft.AspNetCore.Http.IFormFile contractFile) { string folderName = BusinessConstants.Contract; string webRootPath = _hostingEnvironment.WebRootPath; string newPath = Path.Combine(webRootPath, folderName); if (!Directory.Exists(newPath)) { Directory.CreateDirectory(newPath); } if (contractFile.Length > 0) { string fileName = DateTime.Now.Ticks + "_" + ContentDispositionHeaderValue.Parse(contractFile.ContentDisposition).FileName.Trim('"'); string fullPath = Path.Combine(newPath, fileName); using (FileStream stream = new FileStream(fullPath, FileMode.Create)) { contractFile.CopyTo(stream); } return(fullPath); } return(null); }
public async Task <IActionResult> Create(Product product, Microsoft.AspNetCore.Http.IFormFile imageFile) { if (ModelState.IsValid) { string newFile = System.IO.Path.Combine(_env.WebRootPath, "images", imageFile.FileName); System.IO.FileInfo newFileInfo = new System.IO.FileInfo(newFile); using (System.IO.FileStream fs = newFileInfo.Create()) { imageFile.CopyTo(fs); fs.Close(); } product.Image = "/images/" + imageFile.FileName; _context.Add(product); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } return(View(product)); }
public static string SaveFile(Microsoft.AspNetCore.Http.IFormFile file) { Boolean knownExt = FileExtention.GetExtention(file) != null; String path = null; try { file.CopyTo(new FileStream(FilepathUtils.GetPath(file, !knownExt), FileMode.Create)); if (knownExt) { path = FilepathUtils.GetPath(file, false).Substring(1); } else { ZipFileUtils.ZipIFormFile(FilepathUtils.GetPath(file, false), file); File.Delete(FilepathUtils.GetPath(file, true)); path = (FilepathUtils.GetPath(file, false) + ".zip").Substring(1); } } catch (System.Exception) { if (knownExt) { path = FilepathUtils.GetPath(file, false).Substring(1); } else { path = (FilepathUtils.GetPath(file, false) + ".zip").Substring(1); } } System.Console.WriteLine(path); return(path); }
public async Task <string> Index(Microsoft.AspNetCore.Http.IFormFile file) { long size = file.Length; string response = null; string[] imageExtensions = { ".JPG", ".JPE", ".GIF", ".PNG", ".jpg", ".jpe", ".gif", ".png" }; string extension = Path.GetExtension(file.FileName); byte[] fileBytes; using (var ms = new MemoryStream()) { file.CopyTo(ms); fileBytes = ms.ToArray(); } string externalURL = "http://api.qrserver.com/v1/read-qr-code/"; var destinationUrl = System.Web.HttpUtility.UrlEncode(externalURL); if (size < 1048576 && (Array.IndexOf(imageExtensions, extension) >= 0)) { if (file.Length > 0) { using (var client = new HttpClient()) { client.BaseAddress = new Uri(externalURL); using (var content = new MultipartFormDataContent("Upload" + DateTime.Now.ToString())) { content.Add(new StreamContent(new MemoryStream(fileBytes))); using (var message = await client.PostAsync(destinationUrl, content)) { response = await message.Content.ReadAsStringAsync(); } } } } } return(response); }
private IActionResult UploadFile(Microsoft.AspNetCore.Http.IFormFile imgFile, string fileName, out string url, out string newName) { int index = fileName.LastIndexOf('.'); string extension = fileName.Substring(index, fileName.Length - index); //获取后缀名 string guid = Guid.NewGuid().ToString().Replace("-", ""); //生成guid string newFileName = guid + extension; newName = newFileName; DateTime dateTime = DateTime.Now; //路径日期部分 string datePath = string.Format("{0}/{1}/{2}/", dateTime.Year.ToString(), dateTime.Month.ToString() , dateTime.Day.ToString()); //linux环境目录为/{1}/ string path = string.Format(@"/{0}/TempFile/{1}", "home/www", datePath); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } datePath = datePath + newFileName; try { using (FileStream fs = System.IO.File.Create(path + newFileName)) { imgFile.CopyTo(fs); fs.Flush(); } string savePath = string.Format("{0}/bf/{1}", http, datePath); url = savePath; return(new JsonResult(new { savepath = savePath, datepath = datePath, code = '0', length = imgFile.Length })); } catch (Exception e) { url = ""; return(new JsonResult(new { message = e.Message, code = '1' })); } }
/// <summary> /// Sube el archivo al servidor y retorna la Ruta completa de éste. /// </summary> /// <param name="file"></param> /// <returns>La ruta completa del archivo subido.</returns> public Response <string> Load(Microsoft.AspNetCore.Http.IFormFile file) { Response <string> response = new Response <string> { IsSuccess = false }; string fullPath = string.Empty; try { string folderName = "Uploads"; string webRootPath = "Files"; string newPath = Path.Combine(webRootPath, folderName); if (!Directory.Exists(newPath)) { Directory.CreateDirectory(newPath); } if (file.Length > 0) { string fileName = System.Net.Http.Headers.ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"'); fullPath = Path.Combine(newPath, DateTime.Now.ToString("Hmmss") + fileName); using (var stream = new FileStream(fullPath, FileMode.Create)) { file.CopyTo(stream); response.IsSuccess = true; response.Message.Add(new MessageResult { Message = "Se ha guardado Archivo correctamente." }); response.Result = fullPath; } } } catch (System.Exception ex) { } return(response); }