需要準(zhǔn)備:
1.安裝虛擬機(jī),系統(tǒng)Linux CentOS6.4
2.Nginx
3.Vsftpd
1.安裝虛擬機(jī)
VMware Workstation 瑰排,系統(tǒng)Linux CentOS6.4用64位
2.安裝nginx
1.使用yum形式安裝捉貌,搜索CentOS6 yum nginx
rpm -ivh http://nginx.org/packages/centos/6/noarch/RPMS/nginx-release-centos-6-0.el6.ngx.noarch.rpm
yum -y install nginx
2.由于Nginx需要依賴其他地方庫支鸡,在命令行輸入:
yum install gcc gcc-c++ automake pcre pcre-devel zlib zlib-devel openssl openssl-devel –y
3.查看nginx安裝版本
nginx -v
4.查看nginx安裝的信息,如下圖所示:
nginx -V
5.修改nginx的配置文件:
vim /etc/nginx/nginx.conf
打開子配置信息,配置ftpuser服務(wù)路徑:
6.啟動(dòng)趁窃、關(guān)閉牧挣、重啟服務(wù):
service nginx start
測(cè)試:打開火狐:localhost
service nginx stop
service nginx restart
3安裝ftp服務(wù)(客戶端安裝FileZilla Client)
1.安裝服務(wù)yum -y install vsftpd
2.添加一個(gè)ftp用戶,此用戶就是用來登錄ftp服務(wù)器用的。
useradd ftpuser
登錄后默認(rèn)的路徑為 /home/ftpuser.
3.給ftp用戶添加密碼
passwd ftpuser
輸入兩次密碼后修改密碼醒陆。
4.防火墻開啟21端口瀑构,因?yàn)閒tp默認(rèn)的端口為21,而centos默認(rèn)是沒有開啟的刨摩,所以要修改iptables文件
vim /etc/sysconfig/iptables
在行上面有22 -j ACCEPT 下面另起一行輸入跟那行差不多的寺晌,只是把22換成21世吨,然后:wq保存。
還要運(yùn)行下,重啟iptables呻征。service iptables restart
5.修改selinux(外網(wǎng)是可以訪問上去了耘婚,可是發(fā)現(xiàn)沒法返回目錄(使用ftp的主動(dòng)模式,被動(dòng)模式還是無法訪問)陆赋,也上傳不了沐祷,因?yàn)閟elinux作怪了。)
修改selinux:
執(zhí)行以下命令查看狀態(tài):
[root@bogon ~]# getsebool -a | grep ftp
allow_ftpd_anon_write --> off
allow_ftpd_full_access --> off
allow_ftpd_use_cifs --> off
allow_ftpd_use_nfs --> off
ftp_home_dir --> off
ftpd_connect_db --> off
ftpd_use_passive_mode --> off
httpd_enable_ftp_server --> off
tftp_anon_write --> off
[root@bogon ~]#
執(zhí)行上面命令攒岛,再返回的結(jié)果看到兩行都是off赖临,代表,沒有開啟外網(wǎng)的訪問
[root@bogon ~]# setsebool -P allow_ftpd_full_access on
[root@bogon ~]# setsebool -P ftp_home_dir on
這樣應(yīng)該沒問題了(如果灾锯,還是不行思杯,看看是不是用了ftp客戶端工具用了passive模式訪問了,如提示Entering Passive mode挠进,就代表是passive模式,默認(rèn)是不行的誊册,因?yàn)閒tp passive模式被iptables擋住了领突,下面會(huì)講怎么開啟,如果懶得開的話案怯,就看看你客戶端ftp是否有port模式的選項(xiàng)君旦,或者把passive模式的選項(xiàng)去掉。如果客戶端還是不行嘲碱,看看客戶端上的主機(jī)的電腦是否開了防火墻金砍,關(guān)吧)
FileZilla的主動(dòng)、被動(dòng)模式修改:
菜單:編輯→設(shè)置
6.啟動(dòng)服務(wù):service vsftpd restart
代碼實(shí)現(xiàn)
package com.taotao.service;
import java.util.Map;
import org.springframework.web.multipart.MultipartFile;
public interface PictureService {
Map uploadPicture(MultipartFile uploadFile);
}
package com.taotao.service.impl;
import java.util.HashMap;
import java.util.Map;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.taotao.common.utils.FtpUtil;
import com.taotao.common.utils.IDUtils;
import com.taotao.service.PictureService;
/**
* 圖片上傳服務(wù)
*
* @author gyq
*
*/
@Service
public class PictureServiceImpl implements PictureService {
@Value("${FTP_ADDRESS}")
private String FTP_ADDRESS;
@Value("${FTP_PORT}")
private Integer FTP_PORT;
@Value("${FTP_USERNAME}")
private String FTP_USERNAME;
@Value("${FTP_PASSWORD}")
private String FTP_PASSWORD;
@Value("${FTP_BASE_PATH}")
private String FTP_BASE_PATH;
@Value("${IMAGE_BASE_URL}")
private String IMAGE_BASE_URL;
@Override
public Map uploadPicture(MultipartFile uploadFile) {
Map<Object, Object> resultMap = new HashMap<>();
try {
// 生成一個(gè)新的文件名
// 取原始文件名
String oldName = uploadFile.getOriginalFilename();
// 生成新的文件名
// UUID.randomUUID();
String newName = IDUtils.genImageName();
newName = newName + oldName.substring(oldName.lastIndexOf("."));
String imagePath = new DateTime().toString("/yyyy/MM/dd");
// 圖片上傳
boolean result = FtpUtil.uploadFile(FTP_ADDRESS, FTP_PORT, FTP_USERNAME, FTP_PASSWORD, FTP_BASE_PATH,
imagePath, newName, uploadFile.getInputStream());
if (!result) {
resultMap.put("error", 1);
resultMap.put("message", "文件上傳失敗");
return resultMap;
}
resultMap.put("error", 0);
resultMap.put("url", IMAGE_BASE_URL + imagePath + "/" + newName);
return resultMap;
} catch (Exception e) {
resultMap.put("error", 1);
resultMap.put("message", "文件上傳異常");
return resultMap;
}
}
}
junit測(cè)試
package com.taotao.controller;
import java.io.File;
import java.io.FileInputStream;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.junit.Test;
import com.taotao.common.utils.FtpUtil;
public class FTPTest {
@Test
public void testFtpClient() throws Exception{
// 創(chuàng)建一個(gè)FtpClient對(duì)象
FTPClient ftpClient =new FTPClient();
//創(chuàng)建Ftp連接
ftpClient.connect("192.168.84.128", 21);
//登錄ftp服務(wù)器麦锯,使用用戶名和密碼
ftpClient.login("ftpuser", "123456");
//上傳圖片
//讀取本地文件
FileInputStream inputStream=new FileInputStream(new File("C:\\Users\\gyq\\Desktop\\hello1.jpg"));
//設(shè)置上傳的路徑
ftpClient.changeWorkingDirectory("/home/ftpuser/www/images");
//修改上傳文件的格式
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
//第一個(gè)參數(shù):服務(wù)器端文檔名
//第二個(gè)參數(shù):上傳文檔的inputStream
ftpClient.storeFile("hello1.jpg", inputStream);
//關(guān)閉連接
ftpClient.logout();
}
@Test
public void testFtpUtil() throws Exception{
FileInputStream inputStream=new FileInputStream(new File("C:\\Users\\gyq\\Desktop\\hello2.jpg"));
FtpUtil.uploadFile("192.168.84.128", 21, "ftpuser", "123456", "/home/ftpuser/www/images", "/2017", "hello2.jpg", inputStream);
}
}
表現(xiàn)層
package com.taotao.controller;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.taotao.service.PictureService;
/**
* 圖片上傳
*
* @author gyq
*
*/
@Controller
public class PictureController {
@Autowired
private PictureService pictureService;
@RequestMapping("/pic/upload")
@ResponseBody
public Map pictureUpLoad(MultipartFile uploadFile) {
Map result = pictureService.uploadPicture(uploadFile);
return result;
}
}
resource.properties
#FTP配置文件
#FTP的ip地址
FTP_ADDRESS=192.168.84.128
FTP_PORT=21
FTP_USERNAME=ftpuser
FTP_PASSWORD=123456
FTP_BASE_PATH=/home/ftpuser/www/images
#圖片服務(wù)器相關(guān)配置
#圖片服務(wù)器基礎(chǔ)url
IMAGE_BASE_URL=http://192.168.84.128/images
applicationContext-dao.xml中修改加載配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
<!-- 數(shù)據(jù)庫連接池 -->
<!-- 加載配置文件 -->
<context:property-placeholder location="classpath:resource/*.properties" />
<!-- 數(shù)據(jù)庫連接池 -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
destroy-method="close">
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<property name="driverClassName" value="${jdbc.driver}" />
<property name="maxActive" value="10" />
<property name="minIdle" value="5" />
</bean>
<!-- 配置sqlsessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml"></property>
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置掃描包恕稠,加載mapper代理對(duì)象 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.taotao.mapper"></property>
</bean>
</beans>
springmvc.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:p="http://www.springframework.org/schema/p"
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.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.taotao.controller" />
<mvc:annotation-driven />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- 資源映射 -->
<mvc:resources location="/WEB-INF/css/" mapping="/css/**"/>
<mvc:resources location="/WEB-INF/js/" mapping="/js/**"/>
<!-- 定義文件上傳解析器 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 設(shè)定默認(rèn)編碼 -->
<property name="defaultEncoding" value="UTF-8"></property>
<!-- 設(shè)定文件上傳的最大值5MB,5*1024*1024 -->
<property name="maxUploadSize" value="5242880"></property>
</bean>
</beans>