maven项目SSM上传下载

须要jar包html

<!-- 文件上传 -->  
		<dependency>  
			<groupId>commons-fileupload</groupId>  
			<artifactId>commons-fileupload</artifactId>  
			<version>1.3</version>  
		</dependency>

jsp页面java

<%@ 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=ISO-8859-1">  
<title>文件上传下载</title>  
</head>  
<body>  
<form method="post" action="<%=request.getContextPath() %>/doUpload.do" enctype="multipart/form-data">  
<input type="file" name="file"/>  
<button type="submit" >提交</button>  
</form> 
    <hr>  
    <form action="<%=request.getContextPath() %>/down.do" method="get">  
        <input type="submit" value="下载">  
    </form>  
</body>  
</html>

在springmvc文件设置web

<!-- 定义文件解释器 -->  
	<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">    
	    <!-- 设置默认编码 -->  
	    <property name="defaultEncoding" value="utf-8"></property>  
	    <!-- 上传图片最大大小10M-->   
	    <property name="maxUploadSize" value="10484880"></property>    
	</bean>

在Controller层添加方法spring

/** 
     * 上传单个文件操做 
     * @param RequestParam 括号中的参数名file和表单的input节点的name属性值一致 
     * @return 
     */  
    @RequestMapping(value="doUpload", method=RequestMethod.POST)  
    public void doUploadFile(@RequestParam("file") MultipartFile file){  
        if(!file.isEmpty()){  
            try {  
                //这里将上传获得的文件保存目录  
                FileUtils.copyInputStreamToFile(file.getInputStream(), new File("E:\\temp",   
                		System.currentTimeMillis()+ file.getOriginalFilename()));  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }  
  
    }  
      
    /**  
     * 文件下载功能  
     * @param request  
     * @param response  
     * @throws Exception  
     */  
    @RequestMapping("down")  
    public void down(HttpServletRequest request,HttpServletResponse response) throws Exception{  
        //下载路径+文件
        String fileName = "E:\\FileDownLoad.zip";  
        //获取输入流  
        InputStream bis = new BufferedInputStream(new FileInputStream(new File(fileName)));  
        //假如以中文名下载的话   重命名下载后的名字 
        String filename = "下载文件.zip";  
        //转码,省得文件名中文乱码  
        filename = URLEncoder.encode(filename,"UTF-8");  
        //设置文件下载头  
        response.addHeader("Content-Disposition", "attachment;filename=" + filename);    
        //1.设置文件ContentType类型,这样设置,会自动判断下载文件类型    
        response.setContentType("multipart/form-data");   
        BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());  
        int len = 0;  
        while((len = bis.read()) != -1){  
            out.write(len);  
            out.flush();  
        }  
        out.close();  
    }