1,下载FtpSever
|启动exe文件后可看到,ftpsever将本地D盘下的ftpfile作为ftp服务器的根路径。
2,nginx 将图片域名映射到本地目录
server
{ listen 80;
autoindex off;
server_name image.imooc.com;
access_log c:/access.log combined; index index.html index.htm index.jsp index.php;
#error_page 404 /404.html;
if ( $query_string ~* ".*[\;'\<\>].*" ){ return 404; }
location ~ /(mmall_fe|mmall_admin_fe)/dist/view/* { deny all; }
location / { root D:\ftpfile; add_header Access-Control-Allow-Origin *; }
}
复制代码
|将域名为image.imooc.com的地址映射到本地 D:\ftpfile 下,这样当地址栏输入图片域名+图片名称 就能获得本地图片了。
3,上传图片到ftp服务器(apache ftpclient)
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.6</version>
</dependency>
复制代码
FTPUtil
@Slf4j
public class FTPUtil {
private static String ftpIp = PropertiesUtil.getValue("ftp.server.ip");
private static String ftpUser = PropertiesUtil.getValue("ftp.user");
private static String ftpPass = PropertiesUtil.getValue("ftp.pass");
private String ip;
private int port;
private String user;
private String pwd;
private FTPClient ftpClient;
public FTPUtil(String ip,int port,String user,String pwd){
this.ip = ip;
this.port = port;
this.user = user;
this.pwd = pwd;
}
public static boolean uploadFile(List<File> fileList) throws IOException {
FTPUtil ftpUtil = new FTPUtil(ftpIp,21,ftpUser,ftpPass);
log.info("开始连接ftp服务器");
boolean result = ftpUtil.uploadFile("img",fileList);
log.info("开始连接ftp服务器,结束上传,上传结果:{}",result);
return result;
}
private boolean uploadFile(String remotePath,List<File> fileList) throws IOException {
boolean uploaded = true;
FileInputStream fis = null;
//连接FTP服务器
if(connectServer(this.ip,this.port,this.user,this.pwd)){
try {
ftpClient.changeWorkingDirectory(remotePath);
ftpClient.setBufferSize(1024);
ftpClient.setControlEncoding("UTF-8");
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
//告诉系统开启一个端口来传输数据
ftpClient.enterLocalPassiveMode();
for(File fileItem : fileList){
fis = new FileInputStream(fileItem);
ftpClient.storeFile(fileItem.getName(),fis);
}
} catch (IOException e) {
log.error("上传文件异常",e);
uploaded = false;
e.printStackTrace();
} finally {
fis.close();
ftpClient.disconnect();
}
}
return uploaded;
}
private boolean connectServer(String ip,int port,String user,String pwd){
boolean isSuccess = false;
ftpClient = new FTPClient();
try {
ftpClient.connect(ip);
isSuccess = ftpClient.login(user,pwd);
} catch (IOException e) {
log.error("连接FTP服务器异常",e);
}
return isSuccess;
}
}
复制代码
PropertyUtil
@Slf4j
public class PropertiesUtil {
private static Properties props;
static {
String filename = "mmall.properties";
props = new Properties();
try {
props.load(new InputStreamReader(PropertiesUtil.class.getClassLoader().getResourceAsStream(filename), "utf-8"));
} catch (IOException e) {
log.error("配置文件读取异常,", e);
}
}
public static String getValue(String key) {
String value = props.getProperty(key.trim());
if (StringUtils.isBlank(value)) {
return null;
}
return value;
}
}
复制代码