springMvc上传下载

配置spring-mvc.xml配置文件

上传下载只需要配置一个bean

    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="defaultEncoding" value="UTF-8"/> 
   <!-- 指定所上传文件的总大小不能超过200KB。注意maxUploadSize属性的限制不是针对单个文件,而是所有文件的容量之和 -->  
      <property name="maxUploadSize" value="20000000"/>  
    </bean>  

然后是上传页面

upload.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'upload.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
  
  <body>
<form action="upload.html" method="post" enctype="multipart/form-data">  
<input type="file" name="file" /> <input type="submit" value="Submit" /></form>  
  </body>
</html>

上传的conntroller

UploadController.java

package
net.spring.controller;

 

import java.io.File;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import
org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;

import
org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

 

@Controller

public
class  UploadController {
	@RequestMapping("/upload")
	public String upload(@RequestParam(value = "file", required = false) MultipartFile file,
			HttpServletRequest request,HttpServletResponse response, ModelMap model) throws IOException{  
        System.out.println("开始");  
        String path =request.getSession().getServletContext().getRealPath("upload");
        
        String fileName =file.getOriginalFilename();
//        String type=fileName.substring(fileName.lastIndexOf("."),fileName.length());
//        System.out.println(fileName);
//        String fileNames = new Date().getTime()+type;  
        System.out.println(path);  
        File targetFile = new File(path, fileName);  
        if(!targetFile.exists()){  
            targetFile.mkdirs();  
        }  
  
        //保存  
        try {  
            file.transferTo(targetFile);  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
//     model.addAttribute("fileUrl", request.getContextPath()+"/upload/"+fileName);  
     model.addAttribute("fileUrl", "/upload/"+fileName);  
  
        return "result";  
    }  
}
然后是返回的页面result.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'result.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
  
  <body>文件列表
  <ul>
  <li>${fileUrl}<a href="download.html?fileName=${fileUrl}">下载</a></li>
  </ul>
    
  </body>
</html>

接着就是下载的方法

DownloadController.java


package
net.spring.controller;

 

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

 

@Controller

public
class  DownloadController {
	@RequestMapping("/download")
	public ModelAndView download(String fileName, HttpServletRequest request, HttpServletResponse response)
			throws Exception{  
		  response.setContentType("text/html;charset=utf-8");   
	        request.setCharacterEncoding("UTF-8");   
	        java.io.BufferedInputStream bis = null;   
	        java.io.BufferedOutputStream bos = null;   
	        String ctxPath = request.getSession().getServletContext().getRealPath(   
	                "/")   
	                + "\\";   
	        String downLoadPath = ctxPath + fileName;   
	        System.out.println(downLoadPath);   
	        try {   
	            long fileLength = new File(downLoadPath).length();   
	            response.setContentType("application/x-msdownload;");   
	          String type=fileName.substring(fileName.lastIndexOf("/")+1,fileName.length());
	          System.out.println(type);
	          fileName = type; 
	            response.setHeader("Content-disposition", "attachment; filename="  
	                    + new String(fileName.getBytes("utf-8"), "ISO8859-1"));   
	            response.setHeader("Content-Length", String.valueOf(fileLength));   
	            bis = new BufferedInputStream(new FileInputStream(downLoadPath));   
	            bos = new BufferedOutputStream(response.getOutputStream());   
	            byte[] buff = new byte[2048];   
	            int bytesRead;   
	            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {   
	                bos.write(buff, 0, bytesRead);   
	            }   
	        } catch (Exception e) {   
	            e.printStackTrace();   
	        } finally {   
	            if (bis != null)   
	                bis.close();   
	            if (bos != null)   
	                bos.close();   
	        }   
	        return null;  
	}
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值