zoukankan      html  css  js  c++  java
  • SpringMVC下文件的上传与下载以及文件列表的显示

    1、配置好SpringMVC环境-----SpringMVC的HelloWorld快速入门!

    导入jar包:commons-fileupload-1.3.1.jar和commons-io-2.4.jar

    文件上传和下载的jar包(百度云) ---> 资源目录--->jar包资源--->文件上传和下载的jar包

    2、在SpringMVC配置文件springmvc.xml中配置CommonsMultipartResovler

    1 <!-- 配置CommonsMultipartResolver -->
    2 <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    3     <property name="defaultEncoding" value="utf-8"></property>
    4     <!-- 以字节为单位 -->
    5     <property name="maxUploadSize" value="10485760"></property><!-- 1M=1024x1024 -->
    6 </bean>

    3、controller方法

     1 @Controller
     2 @RequestMapping("File")
     3 public class FileController {
     4     //文件上传:表单:POST请求,file类型,enctype="multipart/form-data"
     5     @RequestMapping(value = "fileUpload", method = RequestMethod.POST)
     6     public String testUpload(HttpServletRequest request, @RequestParam(value = "desc", required = false) String desc,
     7             @RequestParam("photo") CommonsMultipartFile fileList[]) throws Exception {
     8         ServletContext servletContext = request.getServletContext();
     9         //获取服务器下的upload目录
    10         String realPath = servletContext.getRealPath("/upload");
    11         File filePath = new File(realPath);
    12         //如果目录不存在,则创建该目录
    13         if (!filePath.exists()) {
    14             filePath.mkdir();
    15         }
    16         OutputStream out;
    17         InputStream in;
    18         for (CommonsMultipartFile file : fileList) {
    19             if (file.getSize() == 0) {
    20                 continue;
    21             }
    22             // 防止重命名uuid_name.jpg
    23             String prefix = UUID.randomUUID().toString();
    24             prefix = prefix.replace("-", "");
    25             String fileName = prefix + "_" + file.getOriginalFilename();
    26             out = new FileOutputStream(new File(realPath + "\" + fileName));
    27             in = file.getInputStream();
    28             byte[] b = new byte[1024];
    29             int c = 0;
    30             while ((c = in.read(b)) != -1) {
    31                 out.write(b, 0, c);
    32                 out.flush();
    33             }
    34             out.close();
    35             in.close();
    36         }
    37         return "redirect:/File/showFile";
    38     }
    39     //用ResponseEntity<byte[]> 返回值完成文件下载
    40     @RequestMapping(value = "fileDownload")
    41     public ResponseEntity<byte[]> fileDownload(HttpServletRequest request, @RequestParam(value = "path") String path)
    42             throws Exception {
    43         byte[] body = null;
    44         // ServletContext servletContext = request.getServletContext();
    45         String fileName = path.substring(path.lastIndexOf("_") + 1); //从uuid_name.jpg中截取文件名
    46         // String path = servletContext.getRealPath("/WEB-INF/res/" + fileName);
    47         File file = new File(path);
    48         InputStream in = new FileInputStream(file);
    49         body = new byte[in.available()];
    50         in.read(body);
    51         HttpHeaders headers = new HttpHeaders();
    52         fileName = new String(fileName.getBytes("gbk"), "iso8859-1");
    53         headers.add("Content-Disposition", "attachment;filename=" + fileName);
    54         HttpStatus statusCode = HttpStatus.OK;
    55         ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(body, headers, statusCode);
    56         in.close();
    57         return response;
    58     }
    59     //文件列表的显示
    60     @RequestMapping(value = "/showFile")
    61     public String showFile(HttpServletRequest request,Model m){
    62         ServletContext servletContext = request.getServletContext();
    63         String path=servletContext.getRealPath("/upload");
    64         File[] fileList = new File(path).listFiles();
    65         m.addAttribute("fileList", fileList);
    66         return "showFile";
    67     }
    68 }

    文件列表的显示没有对其进行处理,应该按时间排序:获取一个目录下的所有文件(按时间排序)

    4、前台页面fileUpload.jsp和showFile.jsp

    fileUpload.jsp

    1 <form action="${pageContext.request.contextPath}/File/fileUpload"method="post" enctype="multipart/form-data">
    2     <input type="file" name="photo"><br>
    3     <input type="file" name="photo"><br>
    4     <input type="file" name="photo"><br>
    5     描述:<input type="text" name="desc"><br>
    6     <input type="submit" value="上传">
    7 </form>

    showFile.jsp

     1 <c:choose>
     2     <c:when test="${not empty fileList }">
     3         <!--索引-->
     4         <c:set var="index" value='1'></c:set>
     5         <c:forEach items="${fileList }" var="file">
     6             <!-- filename:文件的名字,不带UUID -->
     7             <c:set var="filename" value='${fn:substring(file.name,fn:indexOf(file.name,"_")+1,fn:length(file.name)) }'/>
     8             <!-- filefullname:文件的名字,带UUID -->
     9             <c:set var="filefullname" value='${fn:split(file.path,"\\")[fn:length(fn:split(file.path,"\\"))-1] }'></c:set>
    10             <!-- rootdir:文件的目录 -->
    11             <c:set var="rootdir" value='${pageContext.request.contextPath}/upload/'></c:set>
    12             <div>
    13             <img alt='${fileanme }' src='${rootdir.concat(filefullname) }'><!-- 文件的全路径 -->
    14                 <a href="${pageContext.request.contextPath}/File/fileDownload?path=${file.path}">下载</a>
    15             </div>
    16             <!-- 每行显示5张图片 -->
    17             <c:if test="${index%5==0 }">
    18                 <br>
    19             </c:if>
    20             <!--索引+1-->
    21             <c:set var="index" value='${index+1 }'></c:set>
    22         </c:forEach>
    23     </c:when>
    24     <c:otherwise>
    25         暂无数据
    26     </c:otherwise>
    27 </c:choose>

    <c:set>中使用“\”会报错,要使用“\\”,其他地方使用“\”即可

  • 相关阅读:
    记一次给自己的本子更换一个SSD盘
    喜欢的电影
    一个人没有出息的9大根源
    经典思维模式
    Linux基础入门教程
    XML
    UML
    Linux最常用的基础命令
    IP地址
    http协议
  • 原文地址:https://www.cnblogs.com/lixiang1993/p/7443246.html
Copyright © 2011-2022 走看看