spring和mybatis框架中实现文件下载功能

    //文件下载
    @RequestMapping(value = "/downFile")
    public void downFile(FileBean fileBean, HttpServletRequest request, HttpServletResponse response) {
		BufferedInputStream in = null;  
		BufferedOutputStream out = null;  
		try {  
	    	//根据id单条查询出文件实体对象
			fileBean = fileService.queryFileById(id);
			
			response.setContentType("text/html;charset=UTF-8");   
			String rootpath = request.getSession().getServletContext().getRealPath("/"); 
			
			//fileBean.getfilepath()表示获取文件实体对象中的路径
			File f = new File(rootpath + File.separator + fileBean.getfilepath());  
			
			response.reset();
			response.setContentType("application/x-excel");  
			response.setCharacterEncoding("UTF-8");  
			
			//fileBean.getname()表示获取文件实体对象中的名称
			response.setHeader("Content-Disposition", "attachment; filename=" + new String(fileBean.getname().getBytes("gbk"),"iso-8859-1"));  
		
			response.setHeader("Content-Length",String.valueOf(f.length()));  
			in = new BufferedInputStream(new FileInputStream(f));  
			out = new BufferedOutputStream(response.getOutputStream());  
			byte[] data = new byte[1024];  
			int len = 0;  
			while (-1 != (len=in.read(data, 0, data.length))) {  
				out.write(data, 0, len);  
			}  
		} catch (Exception e) {  
			e.printStackTrace();  
		} finally {  
			if (in != null) {  
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}  
			}  
			if (out != null) {  
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}  
			}  
		}  
    }

你可能感兴趣的:(spring)