1. Tomcat的server.xml配置文件中進行配置(注意填寫路徑跟web.xml)之中的路徑是一樣的
`
<!--The connectors can use a shared executor, you can define one or more named thread pools-->
<!--
<Executor name="tomcatThreadPool" namePrefix="catalina-exec-"
maxThreads="150" minSpareThreads="4"/>
-->
<!-- A "Connector" represents an endpoint by which requests are received
and responses are returned. Documentation at :
Java HTTP Connector: /docs/config/http.html (blocking & non-blocking)
Java AJP Connector: /docs/config/ajp.html
APR (HTTP/AJP) Connector: /docs/apr.html
Define a non-SSL HTTP/1.1 Connector on port 8080
-->
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" URIEncoding="utf-8"/>
<!-- A "Connector" using the shared thread pool-->
<!--
<Connector executor="tomcatThreadPool"
port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />
-->
<!-- Define a SSL HTTP/1.1 Connector on port 8443
This connector uses the JSSE configuration, when using APR, the
connector should be using the OpenSSL style configuration
described in the APR documentation -->
<!--
<Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"
maxThreads="150" scheme="https" secure="true"
clientAuth="false" sslProtocol="TLS" />
-->
<!-- Define an AJP 1.3 Connector on port 8009 -->
<Connector port="8009" protocol="AJP/1.3" redirectPort="8443" />
<!-- An Engine represents the entry point (within Catalina) that processes
every request. The Engine implementation for Tomcat stand alone
analyzes the HTTP headers included with the request, and passes them
on to the appropriate Host (virtual host).
Documentation at /docs/config/engine.html -->
<!-- You should set jvmRoute to support load-balancing via AJP ie :
<Engine name="Catalina" defaultHost="localhost" jvmRoute="jvm1">
-->
<Engine name="Catalina" defaultHost="localhost">
<!--For clustering, please take a look at documentation at:
/docs/cluster-howto.html (simple how to)
/docs/config/cluster.html (reference documentation) -->
<!--
<Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/>
-->
<!-- Use the LockOutRealm to prevent attempts to guess user passwords
via a brute-force attack -->
<Realm className="org.apache.catalina.realm.LockOutRealm">
<!-- This Realm uses the UserDatabase configured in the global JNDI
resources under the key "UserDatabase". Any edits
that are performed against this UserDatabase are immediately
available for use by the Realm. -->
<Realm className="org.apache.catalina.realm.UserDatabaseRealm"
resourceName="UserDatabase"/>
</Realm>
<Host name="localhost" appBase="webapps"
unpackWARs="true" autoDeploy="true">
<!-- SingleSignOn valve, share authentication between web applications
Documentation at: /docs/config/valve.html -->
<!--
<Valve className="org.apache.catalina.authenticator.SingleSignOn" />
-->
<!-- Access log processes all example.
Documentation at: /docs/config/valve.html
Note: The pattern used is equivalent to using pattern="common" -->
<Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
prefix="localhost_access_log." suffix=".txt"
pattern="%h %l %u %t "%r" %s %b" />
<!--<Context path="" docBase="F:\Tomcat 7.0\webapps\zhaowoyou" debug="0"/>-->
<Context docBase="D:/smbms/upload" path="/imgage" reloadable="false"/>
</Host>
</Engine>
2.打開你項目的Tomcat運行項目的配置 ,將紅框處的選項勾選(用來解決可能出現的中文亂碼的問題)如果沒有出現中文亂碼就不需要勾選了。
3.導入文件上傳的三個jar包
鏈接:https://pan.baidu.com/s/1NQkAxWmNQSC_1Zquyr6QHA
提取碼:ch2s
4.在表單中添加文件域
(注意添加類型是File的類型)
5.在表單的抬頭添加enctype屬性!
6.在接口對應的方法中定義MultipartFile對象接收傳入的文件
7.在springmvc中配置文件上傳所需的視圖解析器 注意要加id屬性
` <!--文件上傳-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!--上傳的最大數量-->
<property name="maxUploadSize" value="5000000"></property>
<!--上傳的編碼格式-->
<property name="defaultEncoding" value="UTF-8"></property>
</bean>`
8.在web.xml中配置文件上傳后保存的地址
<!--文件上傳--> <context-param> <param-name>imagepath</param-name> <param-value>D:/smbms/upload</param-value> </context-param>
9.驗證圖片是否傳入
`/**
* 添加用戶
*
* @return
*/
@RequestMapping(value = "/addUser", method = RequestMethod.POST)
public String addUser(HttpServletRequest httpServletRequest, MultipartFile profilePicture) {
List<String> extNames = new ArrayList<String>();
extNames.add(".png");
extNames.add(".jpg");
extNames.add(".gif");
//驗證圖片時都是否傳入
if (profilePicture != null) {
String oldFileName=profilePicture.getOriginalFilename();
//獲取文件后綴名
String hz=oldFileName.substring(oldFileName.lastIndexOf("."));
System.out.println(hz);
if(extNames.contains(hz)){
//驗證文件大小
if(profilePicture.getSize()<=500000000){
//獲取文件需要存在服務器的地址
String newFilepath=httpServletRequest.getServletContext().getInitParameter("imagepath");
//設置新文件的名稱
String newFileName= UUID.randomUUID().toString()+hz;
//根據日期進行保存
String datePath=new SimpleDateFormat("yyyyMMdd").format(new Date());
//根據地址和名稱創建文件對象File
File file=new File(newFilepath+"/"+datePath+"/"+newFileName);
if(!file.exists()){
file.mkdirs();
}
//將文件內容復制到新文件中
try {
profilePicture.transferTo(file);
} catch (IOException e) {
e.printStackTrace();
}
//配置圖片的虛擬路徑,保存到user對象
String realtionPath="/images/"+newFileName;
}else {
System.out.println("文件太大了!");
}
}else {
System.out.println("文件格式不正確!");
}
}
String userName = httpServletRequest.getParameter("userName");
String userPassword = httpServletRequest.getParameter("userPassword");
String userCode = httpServletRequest.getParameter("userCode");
int gender = Integer.parseInt(httpServletRequest.getParameter("gender"));
//轉換日期格式
String briday = httpServletRequest.getParameter("birthday");
boolean flag = true;
Date bir = null;
SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm");
try {
// 設置lenient為false. 否則SimpleDateFormat會比較寬松地驗證日期,比如2007/02/29會被接受,並轉換成2007/03/01
format.setLenient(false);
bir = format.parse(briday);
} catch (ParseException e) {
flag = false;
}
String phone = httpServletRequest.getParameter("phone");
String address = httpServletRequest.getParameter("address");
int userRole = Integer.parseInt(httpServletRequest.getParameter("userRole"));
User u = new User();
u.setUserCode(userCode);
u.setAddress(address);
u.setUserName(userName);
if (!flag) {
u.setBirthday(new Date());
}
u.setGender(gender);
u.setUserRole(userRole);
u.setUserPassword(userPassword);
u.setPhone(phone);
if (userService.addUser(u)) {
return "redirect:/user/toUserList";
} else {
return "useradd";
}
}`
10.多文件上傳
11.單文件上傳的時候可以使用下邊的方式將文件按時間保存在本地
//設置新文件的名稱 String newFileName= UUID.randomUUID().toString()+hz; //根據日期進行保存 String datePath=new SimpleDateFormat("yyyyMMdd").format(new Date()); //根據地址和名稱創建文件對象File File file=new File(newFilepath+"/"+datePath+"/"+newFileName);