添加上傳的Maven依賴
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
在mvc配置文件中添加上傳文件的Bean
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"><!--配置上傳文件-->
<property name="defaultEncoding" value="utf-8"/><!--默認(rèn)字符編碼-->
<property name="maxUploadSize" value="10485760000"/><!--上傳文件大小-->
<property name="maxInMemorySize" value="4096"/><!--內(nèi)存中的緩存大小-->
</bean>
創(chuàng)建單上傳的前端頁(yè)面
oneUpload.jsp
<%--
Created by IntelliJ IDEA.
User: elijahliu
Date: 2017/2/24
Time: 13:32
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>單文件上傳</title>
</head>
<body>
<div style="margin: 100px auto 0;">
<form action="/oneUpload" method="post" enctype="multipart/form-data"><%--定義enctype來(lái)用于文件上傳--%>
<p>
<span>文件</span>
<input type="file" name="imageFile">
<input type="submit">
</p>
</form>
</div>
</body>
</html>
創(chuàng)建多上傳頁(yè)面
moreUpload.jsp
<%--
Created by IntelliJ IDEA.
User: elijahliu
Date: 2017/2/24
Time: 13:51
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>多文件上傳</title>
</head>
<body>
<div style="margin: 100px auto 0;">
<form action="/moreUpload" method="post" enctype="multipart/form-data"><%--定義enctype來(lái)用于文件上傳--%>
<p>
<span>文件1</span>
<input type="file" name="imageFile1">
</p>
<p>
<span>文件2</span>
<input type="file" name="imageFile2">
</p>
<p>
<input type="submit">
</p>
</form>
</div>
</body>
</html>
編寫(xiě)Controller層的代碼
UploadController.java
package com.springmvc.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* Created by elijahliu on 2017/2/24.
*/
@Controller
public class UploadController {
@RequestMapping("/oneUpload")
public String onUpload(@RequestParam("imageFile")MultipartFile imageFile, HttpServletRequest request) {//獲取文件參數(shù)
String uploadUrl = request.getSession().getServletContext().getRealPath("/")+"upload/";//獲取路徑
String filename = imageFile.getOriginalFilename();//獲取上傳文件的源文件名
File dir = new File(uploadUrl);
if (!dir.exists()) {
dir.mkdirs();
}
System.out.println("文件上傳到" + uploadUrl + filename);
File targetFile = new File(uploadUrl + filename);
if (!targetFile.exists()) {
try {
targetFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
imageFile.transferTo(targetFile); //這一句就是將上傳的文件轉(zhuǎn)化到剛才新建的文件中去了
} catch (IOException e) {
e.printStackTrace();
}
return "redirect:http://localhost:8080/upload/"+filename;
}
@RequestMapping("/moreUpload")
public String moreUpload(HttpServletRequest request) {
MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
Map<String,MultipartFile> files = multipartHttpServletRequest.getFileMap();//獲取圖片的集合
String uploadUrl = request.getSession().getServletContext().getRealPath("/") + "upload/";
File dir = new File(uploadUrl);
if (!dir.exists()) {
dir.mkdirs();
}
List<String> fileList = new ArrayList<String>();
for (MultipartFile file:files.values()) {//使用循環(huán)??map集合上傳文件
File targetFile = new File(uploadUrl + file.getOriginalFilename());
if (!targetFile.exists()) {
try {
targetFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
try {
file.transferTo(targetFile);
fileList.add("http://localhost:8080/upload/"+file.getOriginalFilename());//將文件路徑添加到文件列表中去
} catch (IOException e) {
e.printStackTrace();
}
}
}
request.setAttribute("files",fileList);
return "moreUploadResult";
}
}
編寫(xiě)多上傳的結(jié)果頁(yè)面
<%@ page import="java.util.List" %><%--
Created by IntelliJ IDEA.
User: elijahliu
Date: 2017/2/24
Time: 13:54
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>多文件上傳結(jié)果</title>
</head>
<body>
<div style="margin: 0 auto 100px">
<%
List<String> fileList = (List<String>) request.getAttribute("files");
for (String url:fileList) {
%>
<a href="<%=url%>">
<img alt="" src="<%=url%>"/>
</a>
<%
}
%>
</div>
</body>
</html>
創(chuàng)建下載Controller
package com.springmvc.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
/**
* Created by elijahliu on 2017/2/24.
*/
@Controller
public class DownloadController {
@RequestMapping("/download")
public String download(HttpServletRequest request, HttpServletResponse response){
String fileName = "1.JPG";
System.out.println(fileName);
response.setContentType("text/html;charset=utf-8"); /*設(shè)定相應(yīng)類型 編碼*/
try {
request.setCharacterEncoding("UTF-8");//設(shè)定請(qǐng)求字符編碼
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
java.io.BufferedInputStream bis = null;//創(chuàng)建輸入輸出流
java.io.BufferedOutputStream bos = null;
String ctxPath = request.getSession().getServletContext().getRealPath("/") + "upload/";//獲取文件真實(shí)路徑
System.out.println(ctxPath);
String downLoadPath = ctxPath + fileName;
System.out.println(downLoadPath);
try {
long fileLength = new File(downLoadPath).length();//獲取文件長(zhǎng)度
response.setContentType("application/x-msdownload;");//下面這三行是固定形式
response.setHeader("Content-disposition", "attachment; filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1"));
response.setHeader("Content-Length", String.valueOf(fileLength));
bis = new BufferedInputStream(new FileInputStream(downLoadPath));//創(chuàng)建輸入輸出流實(shí)例
bos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[2048];//創(chuàng)建字節(jié)緩沖大小
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null)
try {
bis.close();//關(guān)閉輸入流
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (bos != null)
try {
bos.close();//關(guān)閉輸出流
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
}
創(chuàng)建導(dǎo)航頁(yè)面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>導(dǎo)航</title>
</head>
<body>
<div style="margin: 0 auto 100px;">
<a href="topage.html?pagename=oneUpload">單文件上傳</a>
<a href="topage.html?pagename=moreUpload">多文件上傳</a>
<a href="http://localhost:8080/download">文件下載</a>
<a href="topage.html?pagename=login">驗(yàn)證碼</a>
</div>
</body>
</html>
GitHub地址: