-
파일 업로드 원컴퓨터(상품등록)스마트팩토리 개발자 교육(23.05.08 ~ 23.10.27)7/ASP.NET 2023. 7. 9. 22:23
CRUD
Create
- 클라이언트가 상품 등록시 이미지 파일을 전송한다
<form action="product/register" method="post" enctype="multipart/form-data"> <input type="text" name="Name" placeholder="Name"/><br /> <input type="text" name="Price" placeholder="Price"/><br /> <input type="file" name="files" multiple required /> <input type="submit" value="상품 등록" /> </form>-서버에서 파일을 받아 DB에 저장될 URI를 저장하고 해당 경로 wwwroot에 저장이된다
// Controller // 모델, file을 전달 받는다 public async Task<IActionResult> RegisterAsync(ProductModel model, IFormFileCollection files) { // 파일 저장 if (await Upload(model, files) > 0) { return View(model); } // 파일 업로드후 모델 저장 await _context.Set<ProductModel>().AddAsync(model); await _context.SaveChangesAsync(); return Redirect("/"); } // Service private async Task<int> Upload(ProductModel model, IFormFileCollection files) { try { // 여러개의 파일일 경우 하나씩 저장 foreach (var file in files) { if (file.Length > 0) { // 파일이 저장될 경로 string path = "wwwroot/Seller/" + model.Id; // DB에 저장되는 파일의 경로 model.URI = "Seller/" + model.Id + "/" + file.FileName; string fileName = Path.GetFileName(Convert.ToString(file.FileName)); // 경로에 파일이 없으면 생성 if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } // 파일 저장 string filePath = Path.Combine(path, fileName); using (var fileStream = new FileStream(filePath, FileMode.Create)) { file.CopyTo(fileStream); } } } return 0; } catch (Exception ex) { // 파일 업로드 실패 처리 Console.WriteLine(ex.Message); return 1; } } }- 저장시 중복이 되지 않도록 한다
Read
- Html에 해당하는 상품의 ID를 통해 URI를 가져와 img태그 src에 파일 경로를 적어준다
public async Task<IActionResult> Read(int id) { // 상품의 Id로 해당 물건 정보 가져오기 var result = await _context.Set<ProductModel>().FirstOrDefaultAsync(n => n.Id == id); return View(result); }Update
@foreach (var porduct in Model) { <img ser="@porduct.URI"> }- Read를 해서 정보를 가져와고 사용자에게 전달한다
(asp.net get 코드)
- 사용자가 업데이트 요청을 하면 수정을 한다
- 수정과정중 이미지 파일은 기존에 있던 이미지는 삭제하고 새로운 이미지 파일을 생성한다
- 수정된 정보를 DB에 저장한다
[HttpGet("Edit/{id:int}")] public IActionResult Edit(int id) { var UpdateModel = _context .Products .Where(product => product.Id == model.Id) .FirstOrDefault(); UpdateModel.Name = model.Name; UpdateModel.Price = model.Price; _context.SaveChanges(); return Redirect("/"); ; }Delete
- ID 를 통해 상품 정보를 가져온다
- 이미지 파일을 삭제한다
- DB에 정보를 삭제한다
[HttpGet("delete/{id:int}")] public async Task<IActionResult> Delete(int id) { // 상품 삭제시 파일도 삭제 var result = await _context.Set<ProductModel>().FirstOrDefaultAsync(n => n.Id == id); // 파일 삭제 string path = @"wwwroot/" + result.URI; if (System.IO.File.Exists(path)) { try { System.IO.File.Delete(path); } catch (System.IO.IOException e) { await Console.Out.WriteLineAsync(e.Message); } } // 상품 삭제 var entity = await _context.Set<ProductModel>().FirstOrDefaultAsync(n => n.Id == id); await Console.Out.WriteLineAsync((char)entity.Id); EntityEntry entityEntry = _context.Entry<ProductModel>(entity); entityEntry.State = EntityState.Deleted; await _context.SaveChangesAsync(); return Redirect("/"); }'스마트팩토리 개발자 교육(23.05.08 ~ 23.10.27)7 > ASP.NET' 카테고리의 다른 글
원격지 파일 업로드 (0) 2023.07.09 CRUD Base 만들기 (0) 2023.07.09 ASP.NET - ORM (0) 2023.06.19 ASP.NET - Cookies, Session (0) 2023.06.19 ASP.NET - Routeing (0) 2023.06.19