C,C#,JAVA,JSP,SPRING,PYTHON,IOT

Header Ads

2014/06/11

spring file down

0 comments
스프링 설정 파일에 아래를 추가... 보통 <bean>의 하위에 <property>식으로 들어가던데... 아래를 추가했을 떄 오류가 난다면.. beans를 bean으로 바꾸고 beans:property를 property로 바꿔서 해보는게...

<beans:bean class="org.springframework.web.servlet.view.BeanNameViewResolver">
     <beans:property name="order" value="0"/>
 </beans:bean>
위의 설정은 컨트롤러에서 jsp로 보내는 역할을 저기에서 처리 하겠다는 것같다.

다음은 컨트롤러 매핑이다.
 @RequestMapping( "/common/filedown" )
 public ModelAndView brandAdd( HttpServletRequest req, HttpServletResponse res, HttpSession session )throws Exception{
  model = new HashMap<String, Object>(); 
  
  return new ModelAndView( new FileDown(), model );
 }

/common/filedown으로 요청이 들어왔을 때 FileDown 클래스를 실행시켜 파일 다운로드가 된다.

마지막으로 FileDown 파일의 내용이다


package commerce.common.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.servlet.view.AbstractView;
//---* 20140326 chicsoul

public class FileDown extends AbstractView {
 
 public FileDown() {
  setContentType("application/download; charset=utf-8");    
 }
 
 @Override
 protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest req, HttpServletResponse res ) throws Exception { 

  HttpSession session = req.getSession();
  File file = new File( session.getServletContext().getRealPath( Converter.toStr( req.getParameter( "filePath" ) ) ) );   //--- jsp에서 filePath라는 파라미터를 던진다. 값은 파일의 경로와 이름이다. 이를 통해서 실제 file의 path를 구한다.
  res.setContentType(getContentType());
  res.setContentLength((int)file.length());
  String userAgent = req.getHeader("User-Agent");
  boolean ie = userAgent.indexOf("MSIE") > -1;
  String fileName = null;
  if(ie) {
   fileName = URLEncoder.encode(file.getName(), "utf-8");
  }else{
   fileName = new String(file.getName().getBytes("utf-8"), "iso-8859-1");
  }
  
  res.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\";");
  res.setHeader("Content-Transfer-Encoding", "binary");
  OutputStream out = res.getOutputStream();
  FileInputStream fis = null;
  try {
   fis = new FileInputStream(file);
   FileCopyUtils.copy(fis, out);
  } finally {
   if(fis != null) {
    try {
     fis.close();
    } catch(IOException ioe) {}
   }
  }
  out.flush();
 }
 
}

댓글 없음:

댓글 쓰기