2011年6月10日 星期五

Spring 3 + 檔案下載 (file download / export file)

網路上看到的文件都是在講怎麼處理 pdf or excel 的檔案,
但如果是要給使用者下載 jpg or txt 檔該怎麼做呢?

今天試了一下, 其實還滿簡單的. 繼承 AbstractView 即可.
下面是示範的程式碼:

View part:
public class FileView extends AbstractView {

    @Override
    protected void renderMergedOutputModel(Map arg0, HttpServletRequest request, HttpServletResponse response) throws Exception {
        File file = new File(filename);

        // force browser download
        response.setContentType("application/force-download");
        response.setContentLength((int) file.length());
        response.setHeader("content-disposition", "attachment; filename=" + filename);

        // export binary file
        BufferedInputStream br = new BufferedInputStream(new FileInputStream(file));
         OutputStream out = response.getOutputStream();
        int ch;
         while ((ch = br.read()) != -1) {
             out.write(ch);
         }
         out.flush();
         out.close();
    }
}


Controller part:

@Controller
public class MyController {
    @RequestMapping(value={"Download"}, method=RequestMethod.GET)
    public ModelAndView download(String filename) throws Exception {

        ModelAndView mv = null;
        try {
            FileView view = new FileView(filename);
            mv = new ModelAndView(view);
        } catch (Exception e) {
            e.printStackTrace() ;
        }

        return mv;
    }

}



html/jsp part

<a href="Download?filename=xxxx.jpg">download</a>



xml 設定檔的部份並不需要做任何設定.

沒有留言: