1、檢查是否安裝了vsftpd
[root@linux01 ~]# rpm -qa|grep vsftpd
2、安裝vsftpd
[root@linux01 ~]# yum -y install vsftpd
3、啟動vsftpd
[root@linux01 ~]# service vsftpd start
4、設置開機啟動
[root@linux01 ~]# chkconfig vsftpd on
5、管理vsftpd相關命令
啟動vsftpd: service vsftpd start
停止vsftpd: service vsftpd stop
重啟vsftpd: service vsftpd restart
狀態vsftpd: service vsftpd status
6.nginx啟動
[root@linux01 conf]# cd /usr/local/nginx-1.8.1/sbin
[root@linux01 sbin]# ./nginx -s reload
1.ftp_demo Maven Webapp:
UploadController.java:
package com.ftp.demo.controller; import java.util.HashMap; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import com.ftp.demo.model.User; import com.ftp.demo.service.UploadService; @Controller public class UploadController { @Autowired private UploadService fileUploadService; /** * @description 跳轉到頭像上傳頁面 * @return */ @RequestMapping("/") public String turnUploadPage() { return "file_upload"; } /** * @description 跳轉到頭像上傳頁面2 * @return */ @RequestMapping("/ajax") public String turnUploadPageAjax() { return "file_upload_ajax"; } @RequestMapping(value = "/upload", method = RequestMethod.POST) @ResponseBody public Object upload(@RequestParam("headPic") MultipartFile[] files) { String[] picsPath = new String[files.length]; User user = new User(1L, "zhangsan", "123456", null); Map<String, Object> resultMap = new HashMap<String, Object>(); if (files.length <= 0) { return "error"; } for(int i = 0; i < files.length; i++) { // 直接調用service try { resultMap = fileUploadService.upload(files[i]); picsPath[i] = (String)resultMap.get("ftpPicPath"); } catch (Exception e) { e.printStackTrace(); } } String ftpPicPath = (String) resultMap.get("ftpPicPath"); if (ftpPicPath != null) {// 上傳文件成功 // 1.通過登錄進來的用戶(通過存入session的用戶信息獲取到用戶的id) Long userId = user.getId(); // 2.通過用戶的id查詢該用戶信息 if (userId == user.getId()) { // 3.把頭像的路徑更新進查詢出的用戶信息 // setHeadPicPath是什么?-->ftp服務器上的圖片所在路徑-->從service中傳入controller user.setHeadPicPath(ftpPicPath); } // 4.判斷是否更新成功 if (null != user.getHeadPicPath() && !"".equals(user.getHeadPicPath())) { System.out.println(user); // 更新成功 } // model.addAttribute("user", user); return picsPath; } return "error"; } }
User.java:
package com.ftp.demo.model; import java.io.Serializable; public class User implements Serializable { private static final long serialVersionUID = -3925195892141429182L; private Long id; private String username; private String password; private String headPicPath; public User() { } public User(Long id, String username, String password, String headPicPath) { this.id = id; this.username = username; this.password = password; this.headPicPath = headPicPath; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getHeadPicPath() { return headPicPath; } public void setHeadPicPath(String headPicPath) { this.headPicPath = headPicPath; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((headPicPath == null) ? 0 : headPicPath.hashCode()); result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + ((password == null) ? 0 : password.hashCode()); result = prime * result + ((username == null) ? 0 : username.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; User other = (User) obj; if (headPicPath == null) { if (other.headPicPath != null) return false; } else if (!headPicPath.equals(other.headPicPath)) return false; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; if (password == null) { if (other.password != null) return false; } else if (!password.equals(other.password)) return false; if (username == null) { if (other.username != null) return false; } else if (!username.equals(other.username)) return false; return true; } @Override public String toString() { return "User [id=" + id + ", username=" + username + ", password=" + password + ", headPicPath=" + headPicPath + "]"; } }
UploadService.java:
package com.ftp.demo.service; import java.util.HashMap; import java.util.Map; import org.joda.time.DateTime; import org.springframework.web.multipart.MultipartFile; import com.ftp.demo.utils.FtpUtil; import com.ftp.demo.utils.IDUtil; public class UploadService { private String ftpIp; private String ftpPort; private String ftpUsername; private String ftpPassword; private String ftpBasePaht;// /home/ftp/www private String httpBasePath; public String getFtpIp() { return ftpIp; } public void setFtpIp(String ftpIp) { this.ftpIp = ftpIp; } public String getFtpPort() { return ftpPort; } public void setFtpPort(String ftpPort) { this.ftpPort = ftpPort; } public String getFtpUsername() { return ftpUsername; } public void setFtpUsername(String ftpUsername) { this.ftpUsername = ftpUsername; } public String getFtpPassword() { return ftpPassword; } public void setFtpPassword(String ftpPassword) { this.ftpPassword = ftpPassword; } public String getFtpBasePaht() { return ftpBasePaht; } public void setFtpBasePaht(String ftpBasePaht) { this.ftpBasePaht = ftpBasePaht; } public String getHttpBasePath() { return httpBasePath; } public void setHttpBasePath(String httpBasePath) { this.httpBasePath = httpBasePath; } /** * @description 文件上傳 * @param file * @return */ public Map<String, Object> upload(MultipartFile file) { Map<String, Object> resultMap = new HashMap<String, Object>(); if(file == null) { return null; } // 1. 獲取該文件的文件名(從頁面傳遞過來的名字) String oldFileName = file.getOriginalFilename(); // 2.創建新的名字(防止不同用戶上傳的圖片名字一致,導致圖片被覆蓋) String newFileName = IDUtil.genImageName(); // 3.新生成的圖片名字拼接成圖片的類型 // 4636437326167.jpg newFileName = newFileName + oldFileName.substring(oldFileName.lastIndexOf(".")); // 4.2017/09/27生成用戶需要存放的路徑,路徑以當天的日期為文件夾 String filePath = new DateTime().toString("yyyy/MM/dd"); // 5.開始ftp的上傳准備 try { Map<String, Object> map = FtpUtil.uploadFile(ftpIp, Integer.parseInt(ftpPort), ftpUsername, ftpPassword, ftpBasePaht, filePath, newFileName, file.getInputStream()); String picPath = (String)map.get("picPaht"); String ftpPicPath = ""; if(picPath != null && (boolean)map.get("result") == true) { ftpPicPath = httpBasePath+picPath+"/"+newFileName; resultMap.put("ftpPicPath", ftpPicPath); } } catch (Exception e) { e.printStackTrace(); } return resultMap; } }
FtpUtil.java:
package com.ftp.demo.utils; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map; import org.apache.commons.net.ftp.FTP; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPReply; public class FtpUtil { /** * Description: 向FTP服務器上傳文件 * * @author Seven Lee * * @param host * FTP服務器hostname:IP * @param port * FTP服務器端口 * @param username * FTP登錄賬號 * @param password * FTP登錄密碼 * @param basePath * FTP服務器基礎目錄 * @param filePath * FTP服務器文件存放路徑。例如分日期存放:/2015/01/01。文件的路徑為basePath+filePath * /home/ftp/www/2017/04/06/1.txt * @param filename * 上傳到FTP服務器上的文件名 * @param input * 輸入流 * @return 成功返回true,否則返回false * @throws Exception */ public static Map<String, Object> uploadFile(String host, int port, String username, String password, String basePath, String filePath, String filename, InputStream input) throws Exception { String picPath = ""; String tempPath = ""; Map<String, Object> resultMap = new HashMap<String, Object>(); boolean result = false; // 1.創建FTP客戶端對象 FTPClient ftp = new FTPClient(); try { int reply; // 2.通過ip和端口號進行連接ftp服務器 ftp.connect(host, port); // 3.通過賬號和密碼進行登錄 ftp.login(username, password);// 返回boolean類型,成功true,失敗false // getReplyCode:拿到登錄后響應嗎(決定了是否登錄成功,並且根據響應碼可以得到登錄失敗的具體原因) reply = ftp.getReplyCode(); // ftp.getReplyCode()-->230說明登錄成功-->如果返回的是530表示密碼錯誤 // isPositiveCompletion(reply):檢測得到的響應碼是否標識了該用戶登錄的狀態,返回true/false if (!FTPReply.isPositiveCompletion(reply)) { // 標識登錄失敗,退出ftp服務器 ftp.disconnect(); resultMap.put("result", result); resultMap.put("picPaht", null); return resultMap;// false-->說明登錄失敗 } //basePath:/home/ftp/www+/2017/09/27 // changeWorkingDirectory判斷目標上傳的目錄知否存在,返回true/false if (!ftp.changeWorkingDirectory(basePath + filePath)) {// /2017/09/27-->["","2017","09","27"] // 該目錄不存在 // filePath.split("/");-->2017, 09, 27 String[] dirs = filePath.split("/"); // /home/ftp/www tempPath = basePath; // 增強for循環開始循環,是要為下面創建文件夾做准備 for (String dir : dirs) { // 第一次循環:dir:可能是2017也可能為"" // 如果第一次循環,拿到的數據為"",那么第二次循環進來一定拿到2017 if (null == dir || "".equals(dir)) continue;// 跳出該次循環,進入下一次循環 // tempPath:/home/ftp/www/2017 tempPath += "/" + dir; picPath += "/"+dir; // 調用changeWorkingDirectory(tempPath)再次判斷該文件夾是否存在 if (!ftp.changeWorkingDirectory(tempPath)) { // 如果不存在 // 調用makeDirectory(tempPath)-->創建文件夾 mkdir 返回true/fase-->如果創建文件夾失敗,意味着上傳失敗 if (!ftp.makeDirectory(tempPath)) { resultMap.put("result", result); resultMap.put("picPaht", null); return resultMap; } else { // 如果創建文件夾成功,再次驗證該目錄是否存在 ftp.changeWorkingDirectory(tempPath); } } } } // 設置該上傳的文件轉換類型(字節流) ftp.setFileType(FTP.BINARY_FILE_TYPE); // 這里開始真正重點!!!開始上傳 // filename:從uploadService中傳遞來的新生成的文件名,返回true/false if (!ftp.storeFile(filename, input)) { // 如果上傳失敗,返回false resultMap.put("result", result); resultMap.put("picPaht", null); return resultMap; } input.close(); // 退出 ftp.logout(); // 確保了一定是上傳成功的 result = true; } catch (IOException e) { e.printStackTrace(); throw new Exception(e); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ioe) { ioe.printStackTrace(); } } } resultMap.put("result", result); resultMap.put("picPaht", picPath); return resultMap; } }
IDUtil.java:
package com.ftp.demo.utils; import java.util.Random; /** * 各種id生成策略 * * @version 1.0 */ public class IDUtil { /** * 圖片名生成 */ public static String genImageName() { // 獲取到當前時間的毫秒數647238647823647867836287181767867 long millis = System.currentTimeMillis(); Random random = new Random(); // 隨機出1-3位的隨機數 int end3 = random.nextInt(999); // millis:當前時間毫秒數+ // %03d占位符:%占位符,d:數字,03:需要占用3位,如果不夠三位在前面補0 String str = millis + String.format("%03d", end3); // str:當前時間的毫秒數+隨機出的數字 // 為了防止圖片名重復,導致圖片被覆蓋 return str; } }
mybatis-config.xml:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <!-- mybatis默認是沒有開啟延遲加載的 需要手動開啟 --> <settings> <!-- 延遲加載 默認false --> <setting name="lazyLoadingEnabled" value="true" /> <!-- 積極加載 默認true --> <setting name="aggressiveLazyLoading" value="false" /> <!--開啟緩存 --> <setting name="cacheEnabled" value="true" /> </settings> </configuration>
applicationContext-db.xml:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns="http://www.springframework.org/schema/beans" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!--數據源配置 --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="driverClassName" value="${jdbc.driverClassName}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <property name="filters" value="stat" /> <property name="maxActive" value="20" /> <property name="initialSize" value="1" /> <property name="maxWait" value="60000" /> <property name="minIdle" value="1" /> <property name="timeBetweenEvictionRunsMillis" value="60000" /> <property name="minEvictableIdleTimeMillis" value="300000" /> <property name="validationQuery" value="SELECT 'x'" /> <property name="testWhileIdle" value="true" /> <property name="testOnBorrow" value="false" /> <property name="testOnReturn" value="false" /> </bean> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- 自動掃描mapping.xml文件,**表示迭代查找 --> <property name="mapperLocations" value="classpath*:mapper/*Mapper.xml" /> <!--mybatis配置文件位置 --> <property name="configLocation" value="classpath:mybatis/mybatis-config.xml" /> </bean> </beans>
applicationContext-tx.xml:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns="http://www.springframework.org/schema/beans" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 事務管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <!-- 事務詳情 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="select*" read-only="true" /> <tx:method name="find*" read-only="true" /> <tx:method name="get*" read-only="true" /> <tx:method name="query*" read-only="true" /> <tx:method name="*" /> </tx:attributes> </tx:advice> <!--支持基於注解的aspectj --> <aop:aspectj-autoproxy /> <!--aop編程,切入點表達式 確定增強的連接器,從而獲得切入點 --> <aop:config> <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.ftp.demo.service..*.*(..)))" /> </aop:config> </beans>
applicationContext-upload.xml:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns="http://www.springframework.org/schema/beans" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <bean id="fileUploadService" class="com.ftp.demo.service.UploadService"> <property name="ftpIp" value="${ftp.host}"></property> <property name="ftpPort" value="${ftp.port}"></property> <property name="ftpUsername" value="${ftp.username}"></property> <property name="ftpPassword" value="${ftp.password}"></property> <property name="ftpBasePaht" value="${ftp.base.path}"></property> <property name="httpBasePath" value="${http.base.url}"></property> </bean> </beans>
applicationContext-mvc.xml:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" 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" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <!-- 自動掃描且只掃描@Controller 其實@autoWired標識的自動注入service已經注入進來了 只會掃描controller注解,並不會去掃描配置文件中配置的<bean id="fileUploadService"> 到底誰誰該掃描呢?-@autoWired去掃描service的時候,就不知道該誰來操作service 只能掃描到@service,並不能掃描到配置文件-通過配置文件的自動加載把fileUploadService注入進來, 但是開始調用的時候,掃描開始沖突,spring要等待springmvc來處理service,但是springmvc得到通知spring已經掃描了service,就 開始等待spring來處理這個service --> <context:component-scan base-package="com.ftp.demo.controller" /> <!-- 當在web.xml 中 DispatcherServlet使用 <url-pattern>/</url-pattern> 映射時,能映射靜態資源 --> <mvc:default-servlet-handler /> <!-- 可用在springmvc.xml配置文件中使用<mvc:annotation-driven>替代注解處理器和適配器的配置。 --> <mvc:annotation-driven> <mvc:message-converters> <bean class="org.springframework.http.converter.StringHttpMessageConverter"> <constructor-arg index="0" value="UTF-8" /> </bean> <!-- 格式化json --> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="prettyPrint" value="true" /> </bean> </mvc:message-converters> </mvc:annotation-driven> <!-- Jsp視圖解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/pages/" /> <property name="suffix" value=".jsp" /> </bean> <!--文件上傳視圖解析器 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!--允許上傳的文件最大大小 單位是byte 設置上傳文件的最大尺寸為5MB --> <property name="maxUploadSize" value="5242880" /> </bean> <!-- 開啟aop對類代理 --> <aop:config proxy-target-class="true" /> </beans>
application.properties:
#mysql connector
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/shiro
jdbc.username=root
jdbc.password=root
#ftp connector
ftp.host=192.168.1.165
ftp.port=21
ftp.username=ftpuser
ftp.password=123456
ftp.base.path=/home/ftp/www
http.base.url=http\://192.168.1.165
applicationContext.xml:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns="http://www.springframework.org/schema/beans" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!--加載配置文件 --> <context:property-placeholder location="classpath:application.properties" /> <!-- 掃描的包路徑 去掉mvc的注解 不但掃描到了service也一並掃描了其他的注解形式 排除controller的注解,只掃描service --> <context:component-scan base-package="com.ftp.demo.service" /> <!-- 數據源配置 --> <import resource="spring/applicationContext-db.xml" /> <!-- 事務配置 --> <import resource="spring/applicationContext-tx.xml" /> <!-- 文件上傳組件 --> <import resource="spring/applicationContext-upload.xml" /> </beans>
file_upload_ajax.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'file_upload_ajax.jsp' starting page</title> <script type="text/javascript" src="/ftp_demo/js/jquery-3.2.1.min.js"></script> <script type="text/javascript"> /** 使用ajax進行文件的上傳 首先要注意data的參數 data需要把整個form表單一並傳遞給后台,讓后台的java代碼認識enctype="multipart/form-data" */ $(function(){ $("#add_pic").click(function(){ $("#add_pic_implements").prepend("<input type='file' name='headPic'/>"); }); $("#add").click(function(){ $.ajax({ url:"/ftp_demo/upload", type:"post", data: new FormData($('#upload_form')[0]), processData: false, contentType: false,// 是指定瀏覽器向服務器傳遞數據的編碼集-->默認支持application/x-www-form-urlencoded // contentType不指定為false,會造成contentType指定編碼機混亂,但是如果指定了contentType: false的情況下 // 會直接選擇使用form表單的編碼集,自己的編碼集失效 success: function(data){ $("#show_pic").show(); for(var i = 0; i < data.length; i++) { $("#show_pic").append("<img src="+data[i]+" />"); } } }); }); }); </script> </head> <body> <!-- processData為true 會自動把enctype="multipart/form-data"轉換為默認的enctype="application/x-www-form-urlencoded" enctype="application/x-www-form-urlencoded":只支持對象,簡單的類型或者封裝類型,並不支持上傳的類型,也就是multipart/form-data --> <form id="upload_form" enctype="multipart/form-data" method="post"> 請上傳頭像: <div id="add_pic_implements"> <input type="file" name="headPic"/> </div> <input id="add" type="button" value="upload" /> </form> <div> <input id="add_pic" type="button" value="添加圖片" /> </div> <div id="show_pic" style="display:none;"> <h4>上傳成功</h4> </div> </body> </html>
file_upload.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'file_upload.jsp' starting page</title> </head> <body> <form action="/ftp_demo/upload" method="post" enctype="multipart/form-data"> 頭像:<input type="file" name="headPic" /> <input type="submit" value="upload"> </form> </body> </html>
success.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'success.jsp' starting page</title> </head> <body> <h1>圖片的回顯</h1> <h4>上傳的圖片為:</h4> <img alt="圖片無法展示" src="${user.headPicPath }"> </body> </html>
web.xml:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"> <!--Spring入口文件的配置--> <!-- 確定配置文件位置 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <!-- 配置spring 監聽器,加載xml配置文件 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 解決POST請求的中文亂碼--> <filter> <filter-name>CharacterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>utf-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- DispatcherServlet:前端控制器 配置前端控制器servlet --> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!--加載前端控制器配置文件 上下文配置位置--> <init-param> <!--contextConfigLocation:指定springmvc配置的加載位置, 如果不指定則默認加 載WEB-INF/[DispatcherServlet的Servlet名字]-servlet.xml(例如springmvc-servlet.xml)。 --> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc/applicationContext-mvc.xml</param-value> </init-param> <!-- 表示隨WEB服務器啟動 --> <load-on-startup>1</load-on-startup> </servlet> <!-- 可以攔截二種請求 第一種:攔截固定后綴的url,比如設置為 *.do、*.action, 例如:/user/add.action 此方法最簡單,不會導致靜態資源(jpg,js,css)被攔截 第二種:攔截所有 設置為/, 例如:/user/add /user/add.action此方法可以實現REST風格的url 很多互聯網類型的應用使用這種方式.但是此方法會導致靜態文件(jpg,js,css)被攔截后不能正常顯示.需要特殊處理 錯誤設置:攔截所有,設置為/*,此設置方法錯誤,因為請求到Action, 當action轉到jsp時再次被攔截,提示不能根據jsp路徑mapping成功. --> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.upload.demo</groupId> <artifactId>ftp_demo</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>ftp_demo Maven Webapp</name> <url>http://maven.apache.org</url> <properties> <!-- junit --> <junit.version>4.12</junit.version> <!-- spring --> <spring.version>4.3.4.RELEASE</spring.version> <!-- json --> <jackson.version>2.8.1</jackson.version> <fastjson.version>1.2.17</fastjson.version> <!-- servlet, jsp, jstl --> <servlet-api.version>3.0.1</servlet-api.version> <jsp-api.version>2.0</jsp-api.version> <jstl.version>1.2</jstl.version> <!-- mysql --> <mysql.version>5.1.40</mysql.version> <druid.version>1.0.26</druid.version> <!-- mybatis --> <mybatis.version>3.3.0</mybatis.version> <mybatis.spring.version>1.2.3</mybatis.spring.version> <mybatis.mapper.version>3.3.9</mybatis.mapper.version> <!-- slf4j --> <slf4j.version>1.7.7</slf4j.version> <!-- file upload --> <commons-fileupload.version>1.3.1</commons-fileupload.version> <!-- httpClient --> <httpclient.version>4.3.5</httpclient.version> <!-- commons-net(ftp) --> <commons-net.version>3.5</commons-net.version> <!-- joda time --> <joda-time.version>2.9.4</joda-time.version> </properties> <dependencies> <!-- joda time begin --> <dependency> <groupId>joda-time</groupId> <artifactId>joda-time</artifactId> <version>${joda-time.version}</version> </dependency> <!-- joda time end --> <!--spring start --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <!--spring end --> <!--json start --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>${fastjson.version}</version> </dependency> <!--json end --> <!-- servlet --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>${servlet-api.version}</version> <scope>provided</scope> </dependency> <!-- jsp --> <dependency> <groupId>javax.servlet</groupId> <artifactId>jsp-api</artifactId> <version>${jsp-api.version}</version> <scope>provided</scope> </dependency> <!-- jstl --> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>${jstl.version}</version> <scope>runtime</scope> </dependency> <!-- database begin --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> <scope>runtime</scope> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>${druid.version}</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>${mybatis.spring.version}</version> </dependency> <!-- database end --> <!-- slf4j begin --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${slf4j.version}</version> </dependency> <!-- slf4j end --> <!-- mybatis common mapper plugin --> <dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper</artifactId> <version>${mybatis.mapper.version}</version> </dependency> <!-- file upload --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>${commons-fileupload.version}</version> </dependency> <!-- file upload --> <!-- httpclient begin --> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>${httpclient.version}</version> </dependency> <!-- httpclient end --> <!-- ftp begin --> <dependency> <groupId>commons-net</groupId> <artifactId>commons-net</artifactId> <version>${commons-net.version}</version> </dependency> <!-- ftp end --> </dependencies> <build> <finalName>ftp_demo</finalName> </build> </project>