首页 > 代码库 > SpringMVC文件上传和下载

SpringMVC文件上传和下载

上传与下载

1文件上传

1.1加入jar包

技术分享

技术分享

文件上传需要依赖的jar包

1.2配置部件解析器

解析二进制流数据。

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!-- 到入xml文件的约束 -->
 3 
 4 <beans xmlns="http://www.springframework.org/schema/beans"
 5     xmlns:context="http://www.springframework.org/schema/context"
 6     xmlns:mvc="http://www.springframework.org/schema/mvc"
 7     xmlns:p="http://www.springframework.org/schema/p"
 8     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 9     xsi:schemaLocation="http://www.springframework.org/schema/beans
10      http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
11      http://www.springframework.org/schema/context
12      http://www.springframework.org/schema/context/spring-context-4.1.xsd
13       http://www.springframework.org/schema/mvc
14      http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
15      ">
16       
17       <!-- 开启注解扫描(将对象纳入spring容器) -->
18       <context:component-scan base-package="org.guangsoft.controller">
19       </context:component-scan> 
20       
21      <!-- 开始springmvc的映射注解和适配注解 -->
22      <mvc:annotation-driven></mvc:annotation-driven>
23      
24      
25      <!-- 实例化文件上传的解析器(MIME) -->
26      <bean id="multipartResolver" 
27          class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
28          <property name="defaultEncoding" value="utf-8"></property><!-- 客户端发送数据的编码 -->
29          <property name="maxUploadSize" value="5242880"></property><!-- 上传文件的大小 -->
30          <property name="uploadTempDir" value="/upload"></property>
31      </bean>
32      
33 </beans> 

1.3建立FileController

 1 package org.guangsoft.controller;
 2 import java.io.File;
 3 import java.io.IOException;
 4 import java.util.UUID;
 5 import javax.servlet.http.HttpSession;
 6 import org.apache.commons.io.FileUtils;
 7 import org.springframework.http.HttpHeaders;
 8 import org.springframework.http.HttpStatus;
 9 import org.springframework.http.MediaType;
10 import org.springframework.http.ResponseEntity;
11 import org.springframework.stereotype.Controller;
12 import org.springframework.web.bind.annotation.RequestMapping;
13 import org.springframework.web.bind.annotation.RequestParam;
14 import org.springframework.web.multipart.commons.CommonsMultipartFile;
15 @Controller
16 public class FileController
17 {
18     /***
19      * 实现文件的上传
20      * 
21      * @RequestParam:指定客户端发送数据的名字
22      * **/
23     @RequestMapping("/uploadFile")
24     public String uploadFile(@RequestParam("cmf") CommonsMultipartFile cmf,
25             HttpSession session)
26     {
27         // 1获得上传的文件内容
28         byte[] bytes = cmf.getBytes();
29         // 2获得upload的绝对路径
30         String path = session.getServletContext().getRealPath("/upload");
31         // 3在服务器的upload目录下创建File对象
32         String oname = cmf.getOriginalFilename(); // 上传文件的原始名字
33         String uuid = UUID.randomUUID().toString();
34         File file = new File(path, uuid
35                 + oname.substring(oname.lastIndexOf(".")));
36         // 4将上传的文件拷贝到指定的目录
37         try
38         {
39             FileUtils.writeByteArrayToFile(file, bytes);
40         }
41         catch (IOException e)
42         {
43             e.printStackTrace();
44         }
45         return "index.jsp";
46     }
47     /***
48      * 实现文件下载
49      * ***/
50     @RequestMapping("/download")
51     public ResponseEntity download(HttpSession session)
52     {
53         // 用来封装响应头信息
54         HttpHeaders responseHeaders = new HttpHeaders();
55         // 下载的附件的类型
56         responseHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
57         // 下载的附件的名称
58         responseHeaders.setContentDispositionFormData("attachment", "1.png");
59         String path = session.getServletContext().getRealPath("/upload");
60         String fname = "b8abd107-ecdd-49ae-9175-b39f1d18a288.png"; // 数据库查询获得
61         // 将下载的文件封装流对象
62         File file = new File(path, fname);
63         try
64         {
65             /**
66              * arg1:需要响应到客户端的数据 arg2:设置本次请求的响应头 arg3:响应到客户端的状态码
67              * ***/
68             return new ResponseEntity(FileUtils.readFileToByteArray(file),
69                     responseHeaders, HttpStatus.CREATED);
70         }
71         catch (IOException e)
72         {
73             e.printStackTrace();
74         }
75         return null;
76     }
77

1.4建立视图页面

 1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
 2 <%
 3 String path = request.getContextPath();
 4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
 5 %>
 6 
 7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 8 <html>
 9   <head>
10     <base href="<%=basePath%>">
11     <title>upload</title>
12     <meta http-equiv="pragma" content="no-cache">
13     <meta http-equiv="cache-control" content="no-cache">
14     <meta http-equiv="expires" content="0">    
15     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
16     <meta http-equiv="description" content="This is my page">
17   </head>
18   
19   <body>
20     <form action="uploadFile.action" method="post" 
21         enctype="multipart/form-data">
22         <div>file<input name="cmf" type="file"/></div>
23         <div> <input type="submit" value="提交"/></div>
24     </form>
25     <hr/>
26     <a href="download.action">下载</a>
27   </body>
28 </html> 

2 文件下载

2.1建立下的handler方法

见上 

 

SpringMVC文件上传和下载