본문 바로가기

spring

프로필 사진 수정하기

sql>tbl_product 생성

create table tbl_product(
	pid int auto_increment primary key,
    pname varchar(100) not null,
    price int,
    image varchar(200)
);

spring>productVO 생성

package com.example.domain;

import java.util.Arrays;

public class ProductVO {
	private int pid;
	private String pname;
	private int price;
	private String image;
	private String[] files;
	public int getPid() {
		return pid;
	}
	public void setPid(int pid) {
		this.pid = pid;
	}
	public String getPname() {
		return pname;
	}
	public void setPname(String pname) {
		this.pname = pname;
	}
	public int getPrice() {
		return price;
	}
	public void setPrice(int price) {
		this.price = price;
	}
	public String getImage() {
		return image;
	}
	public void setImage(String image) {
		this.image = image;
	}
	public String[] getFiles() {
		return files;
	}
	public void setFiles(String[] files) {
		this.files = files;
	}
	@Override
	public String toString() {
		return "ProductVO [pid=" + pid + ", pname=" + pname + ", price=" + price + ", image=" + image + ", files="
				+ Arrays.toString(files) + "]";
	}
	
	
}

ProductDAO 생성

package com.example.persistence;

import java.util.List;

import com.example.domain.ProductVO;

public interface ProductDAO {
	public void insert(ProductVO vo);
	public List<ProductVO> list();
	
	public ProductVO read(int pid);
	
	public void update(ProductVO vo);
	
	public void delete(int pid);
}

ProductMapper

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
    PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper  namespace="ProductMapper">
	<insert id="insert">
		insert into tbl_product(pname,price,image)
		values(#{pname},#{price},#{image})
	</insert>
	<select id="list" resultType="com.example.domain.ProductVO">
		select * from tbl_product
		order by pid desc
	</select>
	<select id="read" resultType="com.example.domain.ProductVO">
		select * from tbl_product
		where pid=#{pid}
	</select>
	<update id="update">
		update tbl_product
		set pname=#{pname}, price=#{price},image=#{image}
		where pid=#{pid}
	</update>
	<delete id="delete">
		delete from tbl_product where pid=#{pid}
	</delete>

</mapper>

ProductDAOImpl생성

package com.example.persistence;


import java.util.List;

import javax.inject.Inject;

import org.apache.ibatis.session.SqlSession;
import org.springframework.stereotype.Repository;

import com.example.domain.ProductVO;

@Repository
public class ProductDAOImpl implements ProductDAO{
	
	@Inject
	SqlSession session;
	String namespace="ProductMapper";
	
	
	@Override
	public void insert(ProductVO vo) {
		// TODO Auto-generated method stub
		session.insert(namespace+".insert",vo);
	}


	@Override
	public List<ProductVO> list() {
		// TODO Auto-generated method stub
		return session.selectList(namespace+".list");
	}


	@Override
	public ProductVO read(int pid) {
		// TODO Auto-generated method stub
		return session.selectOne(namespace +".read",pid);
	}


	@Override
	public void update(ProductVO vo) {
		// TODO Auto-generated method stub
		session.update(namespace+".update",vo);
	}


	@Override
	public void delete(int pid) {
		// TODO Auto-generated method stub
		session.delete(namespace+".delete",pid);
	}






}

 

ProductController

package com.example.web;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.UUID;

import javax.annotation.Resource;
import javax.inject.Inject;

import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.example.domain.ProductVO;
import com.example.persistence.ProductDAO;

@RequestMapping("pro")
@Controller
public class ProductController {
	@Resource(name="uploadProduct")
	private String path;
	
	
	@Inject
	ProductDAO dao;
	
	@RequestMapping("insert")
	public String insert(){
		return "pro/insert";
	}
	
	@RequestMapping(value="insert",method=RequestMethod.POST)
	public String insertPost(ProductVO vo,MultipartFile file)throws Exception{
		//System.out.println(vo.toString());
		//System.out.println("파일 사이즈:"+file.getSize());
		
		UUID uid = UUID.randomUUID();
        String savedName = uid.toString() + "_" + file.getOriginalFilename();
        File target = new File(path, savedName);
        FileCopyUtils.copy(file.getBytes(), target);
        
        
        vo.setImage(savedName);
        dao.insert(vo);
		return "redirect:list";
	}
	
	@RequestMapping("list")
	public String list(Model model){
		model.addAttribute("list",dao.list());
		return "pro/list";
	}
	
	  //이미지파일 출력
  @ResponseBody
  @RequestMapping("/display")
   public byte[] display(String fileName)throws Exception{
      InputStream in=new FileInputStream(path + "/" + fileName);
      byte[] image=IOUtils.toByteArray(in);
      in.close();
      return image;
   }
  
  @RequestMapping("read")
  public String read(Model model,int pid){
	  model.addAttribute("vo",dao.read(pid));
	  return "pro/read";
  }
	//파일업로드 메소드
	private String uploadFile(String originalName, byte[] fileData)throws Exception{
      UUID uid = UUID.randomUUID();
      String savedName = uid.toString() + "_" + originalName;
      File target = new File(path, savedName);
      FileCopyUtils.copy(fileData, target);
      return savedName;
  }
  	@ResponseBody
	@RequestMapping(value="upload",method=RequestMethod.POST)
	public String upload(MultipartFile file)throws Exception{
		System.out.println("file:" + file.getOriginalFilename());
		
		String savedName=uploadFile(file.getOriginalFilename(),file.getBytes());
		return savedName;
	}
  	
  	
	@RequestMapping(value="update",method=RequestMethod.POST)
	public String update(ProductVO vo,MultipartFile file) throws Exception{
			if(file.getOriginalFilename()!=""){
				
				String fileName=vo.getImage();
				new File(path +"/"+fileName).delete();//기존 이미지 삭제
				
				//새로운 이미지 업로드
				UUID uid = UUID.randomUUID();
			    String savedName = uid.toString() + "_" + file.getOriginalFilename();
			    File target = new File(path, savedName);
			    FileCopyUtils.copy(file.getBytes(), target);
				
			    //업로드한 파일명 변경
			    vo.setImage(savedName);
			}
			dao.update(vo);
			return "redirect:list";
	}
		
	
	
	@RequestMapping(value="delete",method=RequestMethod.POST)
	public String delete(int pid,ProductVO vo){
		String fileName=vo.getImage();
		new File(path +"/"+fileName).delete();//기존 이미지 삭제
		dao.delete(pid);
		return "redirect:list";
	}
  
}

FileController

package com.example.web;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.UUID;

import javax.annotation.Resource;

import org.apache.commons.io.IOUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class FileController {
	@Resource(name="uploadProduct")//uploadPath로 바꿔야 view 밑에 jsp실행됨
	private String path;

	
	
	//파일업로드 메소드
	private String uploadFile(String originalName, byte[] fileData)throws Exception{
        UUID uid = UUID.randomUUID();
        String savedName = uid.toString() + "_" + originalName;
        File target = new File(path, savedName);
        FileCopyUtils.copy(fileData, target);
        return savedName;
    }
	
	  //이미지파일 출력
	  @ResponseBody
	  @RequestMapping("/display")
	   public byte[] display(String fileName)throws Exception{
	      InputStream in=new FileInputStream(path + "/" + fileName);
	      byte[] image=IOUtils.toByteArray(in);
	      in.close();
	      return image;
	   }
	
	
	@ResponseBody
	@RequestMapping(value="upload",method=RequestMethod.POST)
	public String upload(MultipartFile file)throws Exception{
		System.out.println("file:" + file.getOriginalFilename());
		
		String savedName=uploadFile(file.getOriginalFilename(),file.getBytes());
		return savedName;
	}
	
	//파일삭제
	@ResponseBody
	@RequestMapping(value="deleteFile",method=RequestMethod.POST)
	public void delete(String fileName){
		new File(path +"/" +fileName).delete();
	}
	//파일 다운로드
	@ResponseBody
	  @RequestMapping(value="downloadFile")
	  public ResponseEntity<byte[]> downloadFile(String fileName)throws Exception{
	    System.out.println("파일이름:" + fileName);
	    ResponseEntity<byte[]> entity=null;
	    InputStream in = null;
	    try{
	      HttpHeaders headers = new HttpHeaders();
	      in= new FileInputStream(path+ "/" + fileName);
	      fileName = fileName.substring(fileName.indexOf("_") + 1);
	      headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
	      headers.add("Content-Disposition", "attachment;filename=\"" + 
	                            new String(fileName.getBytes("UTF-8"), "ISO-8859-1") + "\"");
	      entity = new ResponseEntity<byte[]>(IOUtils.toByteArray(in), headers, HttpStatus.CREATED);
	    }catch(Exception e){
	      System.out.println(e.toString());
	      entity= new ResponseEntity<byte[]>(HttpStatus.BAD_REQUEST);
	    }finally{
	      in.close();
	    }
	    return entity;
	  }
	
}

pro > insert.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<title>Product Insert</title>
	<script src="http://code.jquery.com/jquery-3.1.1.min.js"></script>
</head>
<body>
	<h2>Product Insert</h2>
	<form name="frm" action="insert" method="post" encType="multipart/form-data"><!-- form으로 파일 업로드 할때  ENCtype필수 -->
		<table border=1 width=500>
		<tr>
			<td width=100>상품명</td>
			<td><input type="text" name="pname"></td>
		</tr>
		<tr>
			<td width=100>상품가격</td>
			<td><input type="text" name="price"></td>
		</tr>
		<tr>
			<td width=300>상품이미지</td>
			<td>
				<img src="http://placehold.it/300x300" id="image" width=300px; >
				<input type="file" name="file" style="visibility:hidden;" accept="image/*">
			</td>
		</tr>
		</table>
	<input type="submit" value="저장">
	<input type="reset" value="취소">
	</form>
</body> 
<script>
	//회원 정보에 프로필 사진 넣기
	$("#image").on("click",function(){
		$(frm.file).click();
	});
	//이미지 미리보기
   $(frm.file).on("change", function(e){
      var reader = new FileReader();
      reader.onload=function(e){
         $("#image").attr("src", e.target.result);
      }
      reader.readAsDataURL(this.files[0]);
   });
</script>
</html>

pro>list.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<title>Product Insert</title>
	<script src="http://code.jquery.com/jquery-3.1.1.min.js"></script>
</head>
<body>
	<h2>Product Insert</h2>
	<form name="frm" action="insert" method="post" encType="multipart/form-data"><!-- form으로 파일 업로드 할때  ENCtype필수 -->
		<table border=1 width=500>
		<tr>
			<td width=100>상품명</td>
			<td><input type="text" name="pname"></td>
		</tr>
		<tr>
			<td width=100>상품가격</td>
			<td><input type="text" name="price"></td>
		</tr>
		<tr>
			<td width=300>상품이미지</td>
			<td>
				<img src="http://placehold.it/300x300" id="image" width=300px; >
				<input type="file" name="file" style="visibility:hidden;" accept="image/*">
			</td>
		</tr>
		</table>
	<input type="submit" value="저장">
	<input type="reset" value="취소">
	</form>
</body> 
<script>
	//회원 정보에 프로필 사진 넣기
	$("#image").on("click",function(){
		$(frm.file).click();
	});
	//이미지 미리보기
   $(frm.file).on("change", function(e){
      var reader = new FileReader();
      reader.onload=function(e){
         $("#image").attr("src", e.target.result);
      }
      reader.readAsDataURL(this.files[0]);
   });
</script>
</html>

pro>read.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<title>Product Read</title>
	<script src="http://code.jquery.com/jquery-3.1.1.min.js"></script>
	<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/3.0.1/handlebars.js"></script>
</head>
<body>
	<h2>Product Read</h2>
	<form name="frm" action="update" method="post" encType="multipart/form-data"><!-- form으로 파일 업로드 할때  ENCtype필수 -->
		<input type="hidden" name="pid" value="${vo.pid}">
		<input type="hidden" name="image" value="${vo.image}">
		<table border=1 width=500>
		<tr>
			<td width=100>상품명</td>
			<td><input type="text" name="pname" value="${vo.pname}"></td>
		</tr>
		<tr>
			<td width=100>상품가격</td>
			<td><input type="text" name="price" value="${vo.price}"></td>
		</tr>
		<tr>
			<td width=300>상품이미지</td>
			<td>
				<img  id="image" src="display?fileName=${vo.image}" width=300/>
				<input type="file" id="file" name="file" style="visibility:hidden;"/>
			</td>
		</tr>
		</table>
	<input type="submit" value="수정">
	<input type="reset" value="취소">
	<input type="button" value="목록" onClick="location.href='list'">
	<input type="button" value="삭제" onClick="fundel()">
	</form>
</body> 
	<script>
	$(frm).submit(function(){
		if(confirm("수정하시겠습니까?")){
			return true;
		}else{
			return false;
		}
	});
	function fundel(){
		if(confirm("삭제하시겠습니까?")){
			frm.action="delete?pid=" +"${vo.pid}";
			frm.submit();
		}
	}
	$("#image").on("click",function(){
		$("#file").click();
	});
	//이미지 미리보기
   $("#file").on("change", function(e){
      var reader = new FileReader();
      reader.onload=function(e){
         $("#image").attr("src", e.target.result);
      }
      reader.readAsDataURL(this.files[0]);
   });
		
	</script>
</html>

'spring' 카테고리의 다른 글

파일 업로드 라이브러리 임포트  (0) 2019.12.06
Controller Tip  (0) 2019.12.06
파일 업로드  (0) 2019.12.05
파일업로드 클래스  (0) 2019.12.05
파일업로드  (0) 2019.11.29