一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務(wù)器之家:專注于服務(wù)器技術(shù)及軟件下載分享
分類導航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術(shù)|正則表達式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務(wù)器之家 - 編程語言 - Java教程 - Spring MVC 文件上傳下載的實例

Spring MVC 文件上傳下載的實例

2020-07-24 13:39geloin Java教程

本篇文章主要介紹了Spring MVC 文件上傳下載的實例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

Spring MVC 文件上傳下載,具體如下:

(1) 導入jar包:ant.jar、commons-fileupload.jar、connom-io.jar。

(2) 在src/context/dispatcher.xml中添加

?
1
2
3
<bean id="multipartResolver"
 class="org.springframework.web.multipart.commons.CommonsMultipartResolver"
 p:defaultEncoding="UTF-8" />

注意,需要在頭部添加內(nèi)容,添加后如下所示:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
<beans default-lazy-init="true"
 xmlns="http://www.springframework.org/schema/beans"
 xmlns:p="http://www.springframework.org/schema/p"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:mvc="http://www.springframework.org/schema/mvc"
 xsi:schemaLocation="
  http://www.springframework.org/schema/beans 
  http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  http://www.springframework.org/schema/mvc 
  http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd 
  http://www.springframework.org/schema/context
  http://www.springframework.org/schema/context/spring-context-3.0.xsd">

(3) 添加工具類FileOperateUtil.java

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
/**
 *
 * @author geloin
 */
package com.geloin.spring.util;
 
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
 
public class FileOperateUtil {
 private static final String REALNAME = "realName";
 private static final String STORENAME = "storeName";
 private static final String SIZE = "size";
 private static final String SUFFIX = "suffix";
 private static final String CONTENTTYPE = "contentType";
 private static final String CREATETIME = "createTime";
 private static final String UPLOADDIR = "uploadDir/";
 
 /**
  * 將上傳的文件進行重命名
  *
  * @param name
  * @return
  */
 private static String rename(String name) {
 
  Long now = Long.parseLong(new SimpleDateFormat("yyyyMMddHHmmss")
    .format(new Date()));
  Long random = (long) (Math.random() * now);
  String fileName = now + "" + random;
 
  if (name.indexOf(".") != -1) {
   fileName += name.substring(name.lastIndexOf("."));
  }
 
  return fileName;
 }
 
 /**
  * 壓縮后的文件名
  *
  * @param name
  * @return
  */
 private static String zipName(String name) {
  String prefix = "";
  if (name.indexOf(".") != -1) {
   prefix = name.substring(0, name.lastIndexOf("."));
  } else {
   prefix = name;
  }
  return prefix + ".zip";
 }
 
 /**
  * 上傳文件
  *
  * @param request
  * @param params
  * @param values
  * @return
  * @throws Exception
  */
 public static List<Map<String, Object>> upload(HttpServletRequest request,
   String[] params, Map<String, Object[]> values) throws Exception {
 
  List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
 
  MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;
  Map<String, MultipartFile> fileMap = mRequest.getFileMap();
 
  String uploadDir = request.getSession().getServletContext()
    .getRealPath("/")
    + FileOperateUtil.UPLOADDIR;
  File file = new File(uploadDir);
 
  if (!file.exists()) {
   file.mkdir();
  }
 
  String fileName = null;
  int i = 0;
  for (Iterator<Map.Entry<String, MultipartFile>> it = fileMap.entrySet()
    .iterator(); it.hasNext(); i++) {
 
   Map.Entry<String, MultipartFile> entry = it.next();
   MultipartFile mFile = entry.getValue();
 
   fileName = mFile.getOriginalFilename();
 
   String storeName = rename(fileName);
 
   String noZipName = uploadDir + storeName;
   String zipName = zipName(noZipName);
 
   // 上傳成為壓縮文件
   ZipOutputStream outputStream = new ZipOutputStream(
     new BufferedOutputStream(new FileOutputStream(zipName)));
   outputStream.putNextEntry(new ZipEntry(fileName));
   outputStream.setEncoding("GBK");
 
   FileCopyUtils.copy(mFile.getInputStream(), outputStream);
 
   Map<String, Object> map = new HashMap<String, Object>();
   // 固定參數(shù)值對
   map.put(FileOperateUtil.REALNAME, zipName(fileName));
   map.put(FileOperateUtil.STORENAME, zipName(storeName));
   map.put(FileOperateUtil.SIZE, new File(zipName).length());
   map.put(FileOperateUtil.SUFFIX, "zip");
   map.put(FileOperateUtil.CONTENTTYPE, "application/octet-stream");
   map.put(FileOperateUtil.CREATETIME, new Date());
 
   // 自定義參數(shù)值對
   for (String param : params) {
    map.put(param, values.get(param)[i]);
   }
 
   result.add(map);
  }
  return result;
 }
 
 /**
  * 下載
  * @param request
  * @param response
  * @param storeName
  * @param contentType
  * @param realName
  * @throws Exception
  */
 public static void download(HttpServletRequest request,
   HttpServletResponse response, String storeName, String contentType,
   String realName) throws Exception {
  response.setContentType("text/html;charset=UTF-8");
  request.setCharacterEncoding("UTF-8");
  BufferedInputStream bis = null;
  BufferedOutputStream bos = null;
 
  String ctxPath = request.getSession().getServletContext()
    .getRealPath("/")
    + FileOperateUtil.UPLOADDIR;
  String downLoadPath = ctxPath + storeName;
 
  long fileLength = new File(downLoadPath).length();
 
  response.setContentType(contentType);
  response.setHeader("Content-disposition", "attachment; filename="
    + new String(realName.getBytes("utf-8"), "ISO8859-1"));
  response.setHeader("Content-Length", String.valueOf(fileLength));
 
  bis = new BufferedInputStream(new FileInputStream(downLoadPath));
  bos = new BufferedOutputStream(response.getOutputStream());
  byte[] buff = new byte[2048];
  int bytesRead;
  while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
   bos.write(buff, 0, bytesRead);
  }
  bis.close();
  bos.close();
 }
}

可完全使用而不必改變該類,需要注意的是,該類中設(shè)定將上傳后的文件放置在WebContent/uploadDir下。

(4) 添加FileOperateController.Java

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
/**
 *
 * @author geloin
 */
package com.geloin.spring.controller;
 
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
 
import com.geloin.spring.util.FileOperateUtil;
 
@Controller
@RequestMapping(value = "background/fileOperate")
public class FileOperateController {
 /**
  * 到上傳文件的位置
  * @return
  */
 @RequestMapping(value = "to_upload")
 public ModelAndView toUpload() {
  return new ModelAndView("background/fileOperate/upload");
 }
 
 /**
  * 上傳文件
  *
  * @param request
  * @return
  * @throws Exception
  */
 @RequestMapping(value = "upload")
 public ModelAndView upload(HttpServletRequest request) throws Exception {
 
  Map<String, Object> map = new HashMap<String, Object>();
 
  // 別名
  String[] alaises = ServletRequestUtils.getStringParameters(request,
    "alais");
 
  String[] params = new String[] { "alais" };
  Map<String, Object[]> values = new HashMap<String, Object[]>();
  values.put("alais", alaises);
 
  List<Map<String, Object>> result = FileOperateUtil.upload(request,
    params, values);
 
  map.put("result", result);
 
  return new ModelAndView("background/fileOperate/list", map);
 }
 
 /**
  * 下載
  *
  * @param attachment
  * @param request
  * @param response
  * @return
  * @throws Exception
  */
 @RequestMapping(value = "download")
 public ModelAndView download(HttpServletRequest request,
   HttpServletResponse response) throws Exception {
 
  String storeName = "201205051340364510870879724.zip";
  String realName = "Java設(shè)計模式.zip";
  String contentType = "application/octet-stream";
 
  FileOperateUtil.download(request, response, storeName, contentType,
    realName);
 
  return null;
 }
}

下載方法請自行變更,若使用數(shù)據(jù)庫保存上傳文件的信息時,請參考Spring MVC 整合Mybatis實例。

(5) 添加fileOperate/upload.jsp

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<%@ page language="java" contentType="text/html; charset=UTF-8"
 pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Insert title here</title>
</head>
<body>
</body>
<form enctype="multipart/form-data"
 action="<c:url value="/background/fileOperate/upload.html" />" method="post">
 <input type="file" name="file1" /> <input type="text" name="alais" /><br />
 <input type="file" name="file2" /> <input type="text" name="alais" /><br />
 <input type="file" name="file3" /> <input type="text" name="alais" /><br />
 <input type="submit" value="上傳" />
</form>
</html>

 確保enctype的值為multipart/form-data;method的值為post。

(6) 添加fileOperate/list.jsp

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<%@ page language="java" contentType="text/html; charset=UTF-8"
 pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Insert title here</title>
</head>
<body>
 <c:forEach items="${result }" var="item">
  <c:forEach items="${item }" var="m">
   <c:if test="${m.key eq 'realName' }">
    ${m.value }
   </c:if>
   <br />
  </c:forEach>
 </c:forEach>
</body>
</html>

(7) 通過http://localhost:8080/spring_test/background/fileOperate/to_upload.html訪問上傳頁面,通過http://localhost:8080/spring_test/background/fileOperate/download.html下載文件

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持服務(wù)器之家。

原文鏈接:http://blog.csdn.net/geloin/article/details/7537425/

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 国产精品99久久 | 吃大胸寡妇的奶 | yjsp妖精视频在线观看免费 | 日本68xxxxxxxxx24 日本 片 成人 在线 | 黄绝一级 | 青草草视频在线观看 | 91免费精品国自产拍在线可以看 | 午夜福到在线4国产 | 亚洲国产成人综合 | 亚洲v日韩v欧美在线观看 | 欧美一级视 | 国产成人福利色视频 | 午夜国产理论 | 高h全肉动漫在线观看免费 高h辣h双处全是肉军婚 | 精品国产品香蕉在线观看75 | 天堂va亚洲va欧美va国产 | 日韩久久网| 深夜精品高中女学生 | 亚洲国产一区二区a毛片 | 男女污网站 | 91在线免费播放 | 欧美精品v日韩精品v国产精品 | 天天gan| 91porn最新地址 | 青青成人在线 | 9420高清完整版在线观看国语 | 成年视频在线观看 | 欧洲老妇人70 | 婚前试爱免费看 | 亚洲免费在线观看 | 狠狠做五月深爱婷婷天天综合 | 亚洲精品国产成人 | 成人国产网站v片免费观看 成人国产精品视频 | 无限时间看片在线观看 | 我年轻漂亮的继坶2中字在线播放 | 女人又色又爽又黄 | 亚洲国产成人精品无码区5566 | 2019自拍偷拍视频 | 美女逼逼喷水 | 日韩欧美视频二区 | 欧美亚洲一区二区三区 |