Ejemplo 1: guardar la imagen IFOrmFile en la ruta en la api web de asp.net 5 C #
usingMicrosoft.AspNetCore.Hosting;publicclassImageController:ControllerprivatereadonlyIWebHostEnvironment _hostEnvironment;publicImageController(...,IWebHostEnvironment hostEnvironment)...this._hostEnvironment = hostEnvironment;...[HttpPost][ValidateAntiForgeryToken]publicasyncTask<IActionResult>Create([Bind("ImageId,Title,ImageFile")]ImageModel imageModel)if(ModelState.IsValid)//Save image to wwwroot/imagestring wwwRootPath = _hostEnvironment.WebRootPath;string fileName = Path.GetFileNameWithoutExtension(imageModel.ImageFile.FileName);string extension = Path.GetExtension(imageModel.ImageFile.FileName);
imageModel.ImageName=fileName = fileName + DateTime.Now.ToString("yymmssfff")+ extension;string path = Path.Combine(wwwRootPath +"/Image/", fileName);using(var fileStream =newFileStream(path,FileMode.Create))await imageModel.ImageFile.CopyToAsync(fileStream);//Insert record
_context.Add(imageModel);await _context.SaveChangesAsync();returnRedirectToAction(nameof(Index));returnView(imageModel);....
Ejemplo 2: guardar la imagen IFOrmFile en la ruta en asp.net 5 C # web api
[Route("api/[controller]")][ApiController]publicclassCarsController:ControllerBaseprivatereadonlyIHostingEnvironment _hostingEnv;privatereadonlyWebAPIDbContext _context;publicCarsController(WebAPIDbContext context,IHostingEnvironment hostingEnv)
_hostingEnv = hostingEnv;
_context = context;[HttpPost]publicasyncTask<ActionResult>Post([FromForm]CarViewModel carVM)if(carVM.Image !=null)var a = _hostingEnv.WebRootPath;var fileName = Path.GetFileName(carVM.Image.FileName);var filePath = Path.Combine(_hostingEnv.WebRootPath,"images\Cars", fileName);using(var fileSteam =newFileStream(filePath, FileMode.Create))await carVM.Image.CopyToAsync(fileSteam);Car car =newCar();
car.CarName = carVM.CarName;
car.ImagePath = filePath;//save the filePath to database ImagePath field.
_context.Add(car);await _context.SaveChangesAsync();returnOk();elsereturnBadRequest();
Recuerda algo, que tienes el privilegio añadir un diagnóstico si te fue de ayuda.
¡Haz clic para puntuar esta entrada!
(Votos: 0 Promedio: 0)