Spring mvc实现文件上传下载

5 篇文章 0 订阅
2 篇文章 0 订阅

controller类

package test.controller;

import com.wangyin.commons.util.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by liwenming on 2015/5/26.
 */
@Controller
public class UploadController {

    private static Logger LOGGER = new Logger(UploadController.class);

    @RequestMapping(value = "/upload_enter", method = RequestMethod.GET)
    public String enter(HttpServletRequest request,
                        HttpServletResponse response, ModelMap model) throws IOException {
        // 进入下载界面
        return "upload";
    }

    @RequestMapping(value = "/upload.do", method = RequestMethod.POST)
    public String upload(HttpServletRequest request,
                       HttpServletResponse response, ModelMap model) throws IOException {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        // 得到上传的文件
        MultipartFile mFile = multipartRequest.getFile("file");
        // 得到上传服务器的路径
        String path = request.getSession().getServletContext()
                .getRealPath("/WEB-INF/upload/");

        //打开文件,如果文件不存在就创建
        File file = new File(path);
        if(!file.exists())
            file.mkdir();

        // 得到上传的文件的文件名
        String filename = mFile.getOriginalFilename();
        InputStream inputStream = mFile.getInputStream();
        byte[] b = new byte[1048576];
        int length = inputStream.read(b);
        path += "\\" + filename;
        // 文件流写到服务器端
        FileOutputStream outputStream = new FileOutputStream(path);
        outputStream.write(b, 0, length);
        inputStream.close();
        outputStream.close();

        //查询下载列表
        //得到文件路径
        String basepath = request.getSession().getServletContext().getRealPath("/WEB-INF/upload/");
        //存储要下载的文件名
        Map<String,String> fileNameMap = new HashMap<String,String>();
        listfile(new File(basepath),fileNameMap);//File既可以代表一个文件也可以代表一个目录

        //将Map集合发送到list.jsp页面进行显示
        model.addAttribute("fileNameMap", fileNameMap);
        return "list";
    }

    @RequestMapping(value = "/list")
    public ModelAndView getList(HttpServletRequest request,
                         HttpServletResponse response) throws IOException, ServletException {

        ModelAndView model = new ModelAndView("list");
        //得到文件路径
        String path = request.getSession().getServletContext().getRealPath("/WEB-INF/upload/");

        //存储要下载的文件名
        Map<String,String> fileNameMap = new HashMap<String,String>();

        listfile(new File(path),fileNameMap);//File既可以代表一个文件也可以代表一个目录

        //将Map集合发送到list.jsp页面进行显示
        model.addObject("fileNameMap", fileNameMap);
       return model;
    }

    public void listfile(File file,Map<String,String> map){
        //如果file代表的不是一个文件,而是一个目录
        if(!file.isFile()){
            //列出该目录下的所有文件和目录
            File files[] = file.listFiles();
            //遍历files[]数组
            for(File f : files){
                listfile(f,map);
            }
        }else{
            String realName = file.getName();
            map.put(file.getName(), realName);
        }
    }

    @RequestMapping(value = "/downbyid")
    public void down(HttpServletRequest request,
    HttpServletResponse response, ModelMap model) throws IOException {

        String fileName = request.getParameter("filename");
        fileName = new String(fileName.getBytes("iso8859-1"),"UTF-8");

        //得到文件路径
        String path = request.getSession().getServletContext().getRealPath("/WEB-INF/upload/");

        //得到要下载的文件
        File file = new File(path + "\\" + fileName);

        //如果文件不存在
        if(!file.exists()){
            model.addAttribute("message", "您要下载的资源已被删除!!");
        }

//        LOGGER.info("fileName : " + fileName);
//        LOGGER.info("URLEncoder.encode : " + URLEncoder.encode(fileName, "UTF-8"));
        //设置响应头,控制浏览器下载该文件,告诉浏览器这个文件的名字
        response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        //读取要下载的文件,保存到文件输入流
        FileInputStream in = new FileInputStream(path + "\\" + fileName);
        //创建输出流
        OutputStream out = response.getOutputStream();
        //创建缓冲区
        byte buffer[] = new byte[1048576];
        int len = 0;
        //循环将输入流中的内容读取到缓冲区当中
        while((len=in.read(buffer))>0){
        //输出缓冲区的内容到浏览器,实现文件下载
            out.write(buffer, 0, len);
        }
        //关闭文件输入流
        in.close();
        //关闭输出流
        out.close();

    }
}


list.jsp下载列表页

<%--
  Created by IntelliJ IDEA.
  User: liwenming
  Date: 2015/5/26
  Time: 16:05
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<html>
<head>
    <title></title>
</head>
<body>
<c:forEach var="me" items="${fileNameMap}">
    <c:url value="/downbyid" var="downurl">
        <c:param name="filename" value="${me.key}"></c:param>
    </c:url>
    ${me.value}<a href="${downurl}">下载</a>
    <br/>
</c:forEach>
</body>
</html>

 

upload上传页

<%--
  Created by IntelliJ IDEA.
  User: liwenming
  Date: 2015/5/26
  Time: 14:29
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>文件上传</title>
</head>
<body>
<form method="post" action="upload.do" enctype="multipart/form-data">
    <div>
        <div>
            <label>根证书路径:</label>
        </div>
        <div>
            <input type="file" name="file" placeholder="选择根证书路径" width="300"/>
        </div>
    </div>
    <div>
        <input type="submit" value="保存"/>
    </div>
</form>

</body>
</html>


pom.xml中的依赖关系

<!--实现文件上传-->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.2.2</version>
        </dependency>


视图简析

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize">
            <value>1048576</value>
        </property>
    </bean>


 访问链接

http://localhost:8080/springapp/upload_enter

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值