首页 > 代码库 > spring mvc文件上传下载

spring mvc文件上传下载

web xml springMvc 注册添加

<multipart-config>            <max-file-size>20848820</max-file-size>            <max-request-size>418018841</max-request-size>            <file-size-threshold>1048576</file-size-threshold></multipart-config>   

 

springMvc配置添加

    <!--文件上传    200*1024*1024即200M resolveLazily属性启用是为了推迟文件解析,以便捕获文件大小异常 -->    <bean id="multipartResolver"        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">        <property name="maxUploadSize" value="209715200" />        <property name="defaultEncoding" value="UTF-8" />        <property name="resolveLazily" value="true" />    </bean>

maven添加

<dependency>    <groupId>commons-io</groupId>    <artifactId>commons-io</artifactId>    <version>2.4</version></dependency>

 

上传页面

<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>  <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %><%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 ‘addfile_Jsp.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="http://www.mamicode.com/styles.css">    -->  </head>    <body>   <form:form commandName="uploadedFile" action="file/save" method="post" enctype="multipart/form-data">      <input type="file" name="files[0]" /> <input type="text" name="alais" /><br />      <input type="file" name="files[1]" /> <input type="text" name="alais" /><br />      <input type="file" name="files[2]" /> <input type="text" name="alais" /><br />      <input type="submit" value="上传" />  </form:form>  </body></html>

下载页面

<%@ page language="java" import="java.util.*"  contentType="text/html; charset=utf-8"%><%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%><%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 ‘allFile_Jsp.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="http://www.mamicode.com/styles.css">    -->  </head>    <body>  00    <c:forEach items="${files}" var="userFile">        <tr>            <td>${userFile.id}</td>            <td>${userFile.name}</td>            <td>${userFile.serverName}</td>            <td><a href="${pageContext.request.contextPath}/file/dow?id=${userFile.id}">dow</a></td>        </tr>        <br/>    </c:forEach>  </body></html>

 

controller

package com.dr.controller;import java.util.List;import javax.annotation.Resource;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.RequestHeader;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RequestParam;import com.dr.domain.UploadedFile;import com.dr.domain.UserFile;import com.dr.service.UserFileService;@Controller@RequestMapping("file")public class FileController {    @Resource(name = "userFilesericeImpl")    private UserFileService userFileService;    @RequestMapping("add")    public String fileAdd(Model model) {        model.addAttribute("uploadedFile",new UploadedFile());        return "addfile_jsp";    }    @RequestMapping("save")    public String fileSave(UploadedFile uploadedFile,            HttpServletRequest request,Model model) {                userFileService.add(uploadedFile, request);                List<UserFile>files=userFileService.getAllFile();                model.addAttribute("files",files);                return "allFile_Jsp";                    }    @RequestMapping("allFile")    public String allFile(Model model){        List<UserFile>files=userFileService.getAllFile();        model.addAttribute("files",files);        return "allFile_Jsp";            }        @RequestMapping(value="dow",method = RequestMethod.GET)    public void getFile(@RequestParam("id")int id, HttpServletRequest request,             HttpServletResponse response,             @RequestHeader String referer){        userFileService.dow(id, request, response, referer);    }}

servers

package com.dr.service.impl;import java.io.BufferedInputStream;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.io.OutputStream;import java.util.ArrayList;import java.util.List;import javax.annotation.Resource;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.springframework.stereotype.Service;import org.springframework.web.multipart.MultipartFile;import com.dr.dao.UserFileDao;import com.dr.domain.UploadedFile;import com.dr.domain.UserFile;import com.dr.service.UserFileService;@Servicepublic class UserFilesericeImpl implements UserFileService {    @Resource(name = "userFileDaoImpl")    private UserFileDao fileDao;    public boolean add(UploadedFile uploadedFile, HttpServletRequest request) {        ArrayList<MultipartFile> files = uploadedFile.getFiles();        // 判断file数组不能为空并且长度大于0        if (files != null && files.size() > 0) {            // 循环获取file数组中得文件            for (int i = 0; i < files.size(); i++) {                MultipartFile file = files.get(i);                // TODO Auto-generated method stub                // 判断文件是否为空                if (!file.isEmpty()) {                    try {                        // 服务器名称防止重名                        String ServiceName = System.currentTimeMillis() + ""                                + (int) (1 + Math.random() * (100 - 1 + 1));                        // 文件保存路径                        String filePath = request.getSession()                                .getServletContext().getRealPath("/")                                + "WEB-INF/file/" + ServiceName;                        // 转存文件                        file.transferTo(new File(filePath));                        // 图片信息存入数据库                        UserFile userFile = new UserFile();                        userFile.setName(file.getOriginalFilename());                        userFile.setServerName(ServiceName);                        fileDao.save(userFile);                    } catch (Exception e) {                        e.printStackTrace();                        return false;                    }                }            }        }        return true;    }    @Override    public List<UserFile> getAllFile() {        // TODO Auto-generated method stub        return fileDao.findAll(UserFile.class);    }    @Override    public void deleteFile(int id) {        // TODO Auto-generated method stub        fileDao.delete(UserFile.class, id);    }    @Override    public void dow(int id, HttpServletRequest request,            HttpServletResponse response, String referer) {        // TODO Auto-generated method stub        if (referer != null) {            String filePath = request.getSession().getServletContext()                    .getRealPath("/")                    + "WEB-INF/file";            UserFile userFile = fileDao.get(UserFile.class, id);            File file = new File(filePath, userFile.getServerName());            if (file.exists()) {                byte[] buffer = new byte[1024];                FileInputStream fis = null;                BufferedInputStream bis = null;                // if you‘re using Java 7, use try-with-resources                try {                    response.setContentType("application/octet-stream");                    // 名字还原                    response.setHeader(                            "Content-disposition",                            "attachment; filename="                                    + new String(userFile.getName().getBytes(                                            "utf-8"), "ISO8859-1"));                    fis = new FileInputStream(file);                    bis = new BufferedInputStream(fis);                    OutputStream os = response.getOutputStream();                    int i = bis.read(buffer);                    while (i != -1) {                        os.write(buffer, 0, i);                        i = bis.read(buffer);                    }                } catch (IOException ex) {                    // do something here                } finally {                    if (bis != null) {                        try {                            bis.close();                        } catch (IOException e) {                        }                    }                    if (fis != null) {                        try {                            fis.close();                        } catch (IOException e) {                        }                    }                }            }        }    }}

上传列表实体

package com.dr.domain;import java.io.Serializable;import java.util.ArrayList;import org.springframework.web.multipart.MultipartFile;public class UploadedFile implements Serializable {    private static final long serialVersionUID = 72348L;    private ArrayList<MultipartFile> files;    public ArrayList<MultipartFile> getFiles() {        return files;    }    public void setFiles(ArrayList<MultipartFile> files) {        this.files = files;    }}

 文件实体类

package com.dr.domain;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;import javax.persistence.Id;import javax.persistence.Table;@Entity@Table(name="user_file")public class UserFile {    @Id     @GeneratedValue(strategy=GenerationType.IDENTITY)    private Integer id;    private String name;    private String serverName;    public Integer getId() {        return id;    }    public void setId(Integer id) {        this.id = id;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public String getServerName() {        return serverName;    }    public void setServerName(String serverName) {        this.serverName = serverName;    }    @Override    public String toString() {        return "UserFile [id=" + id + ", name=" + name + ", serverName="                + serverName + "]";    }    public UserFile(Integer id, String name, String serverName) {        super();        this.id = id;        this.name = name;        this.serverName = serverName;    }    public UserFile() {        super();    }    }

 

spring mvc文件上传下载