一、今天我們所說的是基於SpringMVC的關於文件的上傳和下載的問題的解決。(這里所說的上傳和下載都是上傳到服務器與從服務器上下載文件)。這里的文件包括我們常用的各種文件。如:文本文件(.txt),word文件(.doc),圖片文件(.png .jpg等),歌曲文件(.mp3等)以及視頻文件(.mp4等)等各種類型的文件。
下面讓我們一步一步的來實現它。
二、首先我們需要導入一些jar包。如圖所示:

即在WEB-INF下的lib文件夾下導入圈起的三個jar包。
三、我們來建立一個簡單名字為upload的jsp頁面,並加入一個表單。如下所示:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/upload" method="post" enctype="multipart/form-data">
文件:<input type="file" name="file"/><br>
名字:<input type="text" name="name"/><br>
<input type="submit" value="上傳"/>
</form>
</body>
</html>
這里有一個需要我們注意的問題,就是form表單的enctype屬性一定要改成multipart/form-data。否則的話,我們無法進行文件的上傳。
四、我們需要在控制層寫一個方法
@RequestMapping(value="/upload",method=RequestMethod.POST)
public String testUpload(HttpServletRequest request,@RequestParam(value="name",required=false) String desc,@RequestParam(value="file") CommonsMultipartFile file) throws Exception{
System.out.println(desc);
ServletContext servletContext = request.getServletContext();
String realPath = servletContext.getRealPath("/upload");
File file1 = new File(realPath);
if(!file1.exists()){
file1.mkdir();
}
OutputStream out;
InputStream in;
String prefix = UUID.randomUUID().toString();
prefix = prefix.replace("-","");
String fileName = prefix+"_"+file.getOriginalFilename();
System.out.println(fileName);
out = new FileOutputStream(new File(realPath+"\\"+fileName));
in = file.getInputStream();
IOUtils.copy(in, out);
out.close();
in.close();
return "/WEB-INF/success.jsp";
}
這里面最 后返回的是WEB-INF下面的一個jsp頁面。
五、在SpringMVC的配置文件里加入以下的配置:
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8"></property>
<property name="maxUploadSize" value="5000000"></property>
</bean>
第一個<property></property>是設置編碼;第二個<property ></property>是設置上傳文件的大小,這里我們指定的大小是5000000個字節。
六、建立一個名字為success的jsp頁面。(隨便寫點東西就行)
七、我們從upload頁面開始運行,然后選擇文件,就會將你的文件上傳到你本機的服務器上。如圖所示:

我們在相應的文件夾下就能夠找到你所上傳的文件。
