springMVC多文件上传和下载

转载和参考地址http://www.oschina.net/code/snippet_1590790_48147#69520
**
工程目录
这里写图片描述
jar包
这里写图片描述

web.xml

**

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>SpringMVCFile</display-name>

  <!-- 配置前台分发器 -->
     <servlet>
      <servlet-name>springmvc</servlet-name>
      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
      <!-- 扫描使用springmvc配置文件 -->
      <init-param>
           <param-name>contextConfigLocation</param-name>
           <param-value>classpath:springmvc-context.xml</param-value>
      </init-param>
      <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
      <servlet-name>springmvc</servlet-name>
      <url-pattern>/</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>

springmvc-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">
    <!-- 扫描包裹,我们完全使用注释定义 Bean 并完成 Bean 之间装配: -->
    <context:component-scan base-package="com.fileUpDown" />
    <!-- 解决了@Controller注解的使用前提配置。 -->
    <mvc:annotation-driven />
    <!-- 配置对静态资源的处理 -->
    <!-- mapping是映射路径,location是本地属性就是webcontent下的目录,web-inf可能访问不到 -->
    <mvc:resources mapping="/file/**" location="/fileHome/" />

    <!-- 定义view视图解析器 -->
    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/" />
        <property name="suffix" value=".jsp" />
    </bean>
    <!-- 设置文件上传的一些属性 -->
    <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver"
        p:defaultEncoding="UTF-8" />
</beans>

contoller控制器

package com.fileUpDown;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

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;

import com.utilTools.FileUtils;

@Controller
@RequestMapping(value="fileOperate")
public class FileOperateAction {
    @RequestMapping(value="upload")
    public String upload(HttpServletRequest request){
        init(request);
        try {
            //调用文件的上传方法
            FileUtils.upload(request);
            //设置文件上传成功后返回信息,和文件集合信息
            request.setAttribute("msg", "ok");
            request.setAttribute("map", getMap());
        } catch (Exception e) {
            e.printStackTrace();
        }
        //以重定向的方式跳转到list
        return "redirect:list";
    }
    @RequestMapping(value="list")
    public ModelAndView list(HttpServletRequest request){       
        init(request);
        request.setAttribute("map", getMap());
        return new ModelAndView("downLoad");
    }
    @RequestMapping(value="download")
    public void download(HttpServletRequest request, HttpServletResponse response){
        init(request);
        try {
            //获取前台传递过来的要下载的名称
            String downloadfFileName = request.getParameter("filename");
            //转码
            downloadfFileName = new String(downloadfFileName.getBytes("iso-8859-1"),"utf-8");
            //截取出来真正的文件下载名称
            String fileName = downloadfFileName.substring(downloadfFileName.indexOf("_")+1);
            //识别用户的版本,以便于转码
            String userAgent = request.getHeader("User-Agent");
            byte[] bytes = userAgent.contains("MSIE") ? fileName.getBytes() : fileName.getBytes("UTF-8"); 
            fileName = new String(bytes, "ISO-8859-1");

            response.setHeader("Content-disposition", String.format("attachment; filename=\"%s\"", fileName));
            FileUtils.download(downloadfFileName, response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //定义文件的位置
    private void init(HttpServletRequest request) {
        if(FileUtils.FILEDIR == null){
            //定义出来文件的储存路径
            FileUtils.FILEDIR = request.getSession().getServletContext().getRealPath("/") + "file/";
            System.out.println(FileUtils.FILEDIR);
        }
    }
    //返回指定目录下的文件信息
     private Map<String, String> getMap(){
            Map<String, String> map = new HashMap<String, String>();
            //创建文件数组,把指定目录下的文件放进去
            File[] files = new File(FileUtils.FILEDIR).listFiles();
            if(files != null){
                for (File file : files) {
                    if(file.isDirectory()){
                        File[] files2 = file.listFiles();
                        if(files2 != null){
                            for (File file2 : files2) {
                                String name = file2.getName();
                                map.put(file2.getParentFile().getName() + "/" + name, name.substring(name.lastIndexOf("_")+1));
                            }
                        }
                    }
                }
            }
            return map;
        }   
}

工具类

package com.utilTools;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

public class FileUtils {
    public static String FILEDIR = null;
    /**
     * 上传
     * @param request
     * @throws IOException
     */
    public static void upload(HttpServletRequest request) throws IOException{
        //spring 处理上传文件的类,在springmvc-context.xml中要配置
        MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;

        Map<String, MultipartFile> fileMap = mRequest.getFileMap(); 
        //创建出目标文件路径的File对象
        File file = new File(FILEDIR);
        //判断文件夹是否存在 ,不存在就创建
        if (!file.exists()) {
            file.mkdir();
        }
        //迭代文件map
        Iterator<Map.Entry<String, MultipartFile>> it = fileMap.entrySet().iterator();
        while(it.hasNext()){
            Map.Entry<String, MultipartFile> entry = it.next();
            //获取到map集合中某个集合的具体对象
            MultipartFile mFile = entry.getValue();
            //判断文件对象的大小是否为0,名称是否为空
            if(mFile.getSize() != 0 && !"".equals(mFile.getName())){
                //把文件的输入流,与输出流,传入到具体的文件书写对象
                write(mFile.getInputStream(), new FileOutputStream(initFilePath(mFile.getOriginalFilename())));
            }
        }
    }

    private static int getFileDir(String name) {
        return name.hashCode() & 0xf;
    }
    /**
     * 对文件名称再一次加工,统一格式,防止重复
     * @param request
     * @throws IOException
     */
    private static String initFilePath(String name) {
        String dir = getFileDir(name) + "";
        File file = new File(FILEDIR + dir);
        if (!file.exists()) {
            file.mkdir();
        }
        Long num = new Date().getTime();
        Double d = Math.random()*num;
        return (file.getPath() + "/" + num + d.longValue() + "_" + name).replaceAll(" ", "-");
    }
    public static void download(String downloadfFileName, ServletOutputStream out) {
        try {
            FileInputStream in = new FileInputStream(new File(FILEDIR + "/" + downloadfFileName));
            write(in, out);
        } catch (FileNotFoundException e) {
            try {
                FileInputStream in = new FileInputStream(new File(FILEDIR + "/"
                        + new String(downloadfFileName.getBytes("iso-8859-1"),"utf-8")));
                write(in, out);
            } catch (IOException e1) {              
                e1.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }       
    }
      /**
     * 写入数据
     * @param in
     * @param out
     * @throws IOException
     */
    public static void write(InputStream in, OutputStream out) throws IOException{
        try{
            byte[] buffer = new byte[1024];
            int bytesRead = -1;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
            out.flush();
        } finally {
            try {
                in.close();
            }
            catch (IOException ex) {
            }
            try {
                out.close();
            }
            catch (IOException ex) {
            }
        }
    }  
}

**

jsp文件

**
index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">    
    <title>index</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <style type="text/css">
        a:link {
            text-decoration: none;
        }
        a:visited {
            text-decoration: none;
        }
        a:hover {
            color: #999999;
            text-decoration: underline;
        }
    </style>
  </head>  
  <body>
    <h1>这是springMVC项目的主页</h1> <br>
    <br/><a href="<%=basePath%>upload.jsp">上传文件</a>
  </body>
</html>```

downLoad.jsp

<%@ page language=”java” import=”java.util.*” pageEncoding=”UTF-8” contentType=”text/html; charset=UTF-8” %>
<%@ taglib prefix=”c” uri=”http://java.sun.com/jsp/jstl/core” %>
<%
String basePath = request.getScheme()+”://”+request.getServerName()+”:”+request.getServerPort()+ request.getContextPath()+”/”;
%>



list



a:link {
text-decoration: none;
}
a:visited {
text-decoration: none;
}
a:hover {
color: #999999;
text-decoration: underline;
}






fileOperate/download?filename= v.key"> {v.value}



fileOperate/upload.jsp”>上传文件

upload.jsp

<%@ page language=”java” contentType=”text/html; charset=UTF-8”
pageEncoding=”UTF-8”%>
<%
String basePath = request.getScheme()+”://”+request.getServerName()+”:”+request.getServerPort()+request.getContextPath()+”/”;
%>



upload



.input {
width: 80px;
height: 20px;
line-height: 20px;
background: #0088ff;
text-align: center;
display: inline-block;
overflow: hidden;
position: relative;
text-decoration: none;
top: 5px;
}

.input:hover {
    background: #ff8800;
}

.file {
    opacity: 0;
    filter: alpha(opacity =     0);
    font-size: 50px;
    position: absolute;
    top: 0;
    right: 0;
}

a:link {
    text-decoration: none;
}
a:visited {
    text-decoration: none;
}
a:hover {
    color: #999999;
    text-decoration: underline;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值