SpringBoot+Ftp+Nginx搭建静态资源服务器实现静态资源服务的上传(Windows端)
1.需要的资源
ftp服务器:FileZilla_Server
下载链接:https://www.filezilla.cn/download/server
nginx服务器:
下载地址:http://nginx.org/en/download.html
2.服务的安装
第一步安装Ftp服务器
安装FileZilla_Server
配置用户和目录
添加一个用户,配置密码
找到编辑选择用户
添加用户
配置密码
配置资源路径
给给文件目录权限
最后确认就完成了
第二步配置和启动Nginx服务器
windows下的nginx配配置和启动相对简单可以直接拷贝我的然后修改访问文件根目录
#user nobody;
worker_processes 1;
#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;
#pid logs/nginx.pid;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
#log_format main '$remote_addr - $remote_user [$time_local] "$request" '
# '$status $body_bytes_sent "$http_referer" '
# '"$http_user_agent" "$http_x_forwarded_for"';
#access_log logs/access.log main;
sendfile on;
#tcp_nopush on;
#keepalive_timeout 0;
keepalive_timeout 65;
#gzip on;
autoindex on;# 显示目录
autoindex_exact_size on;# 显示文件大小
autoindex_localtime on;# 显示文件时间
server { #这里是我自己配置服务端口
listen 8081;
server_name resouce;
root C:/Users/Administrator/Desktop/shior1.2.3; #访问文件根目录
autoindex on; #是否浏览文件下的列表
location / { #是否允许跨域
add_header Access-Control-Allow-Origin *;
}
add_header Cache-Control "no-cache,must-revalidate";# 是否缓存
}
}
然后启动访问也面http://127.0.0.1:8081/
3.SpringBoot中ftp图片上传以及配置
3.1 所需依赖
<!-- 文件上传的类 --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.2.2</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency> <dependency> <groupId>org.apache.camel</groupId> <artifactId>camel-ftp</artifactId> <version>2.13.2</version> </dependency>
3.2ftp文件上传工具类 FtpUtil
import org.apache.commons.net.ftp.FTP; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPReply; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; /** * 作者:yangmian * 包名:com.haiwei.parkweb.utils * 类名:FtpUtil * 创建时间:2019/5/13 * 描述信息: */ public class FtpUtil { /** * Description: 向FTP服务器上传文件 * @param host FTP服务器ip * @param port FTP服务器端口 * @param username FTP登录账号 * @param password FTP登录密码 * @param basePath FTP服务器基础目录,/home/ftpuser/images * @param filePath FTP服务器文件存放路径。例如分日期存放:/2018/05/28。文件的路径为basePath+filePath * @param filename 上传到FTP服务器上的文件名 * @param input 输入流 * @return 成功返回true,否则返回false */ public static boolean uploadFile(String host, int port, String username, String password, String basePath, String filePath, String filename, InputStream input) { boolean result = false; FTPClient ftp = new FTPClient(); try { int reply; ftp.connect(host, port);// 连接FTP服务器 // 如果采用默认端口,可以使用ftp.connect(host)的方式直接连接FTP服务器 ftp.login(username, password);// 登录 reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); return result; } //切换到上传目录 if (!ftp.changeWorkingDirectory(basePath+filePath)) { //如果目录不存在创建目录 String[] dirs = filePath.split("/"); String tempPath = basePath; for (String dir : dirs) { if (null == dir || "".equals(dir)) continue; tempPath += "/" + dir; if (!ftp.changeWorkingDirectory(tempPath)) { if (!ftp.makeDirectory(tempPath)) { return result; } else { ftp.changeWorkingDirectory(tempPath); } } } } //设置为被动模式 ftp.setBufferSize(1024*1024*2); BufferedInputStream bufferedInputStream = new BufferedInputStream(input); ftp.enterLocalPassiveMode(); //设置上传文件的类型为二进制类型 ftp.setFileType(FTP.BINARY_FILE_TYPE); //上传文件 if (!ftp.storeFile(filename, bufferedInputStream)) { return result; } input.close(); ftp.logout(); result = true; } catch (IOException e) { e.printStackTrace(); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ioe) { } } } return result; } }
3.3最后一项就是接口和配置项了
//@RestController //@CrossOrigin //@RequestMapping("/FileUpload/*") //@Api(value = "文件上传的接口",tags = {"文件上传的接口"}) public class FileUploadReController { @Value("${ftp.ftp-host}") private String host; @Value("${ftp.ftp-port}") private int port; @Value("${ftp.ftp-username}") private String username; @Value("${ftp.ftp-password}") private String password; @Value("${ftp.ftp-basePath}") private String basePath; @Value("${nginx.nginx-url}") private String nginxUrl; public static final String PATH ="/src/main/resources/"; @PostMapping(value="/fileUpload",headers="content-type=multipart/form-data") @ApiOperation(value = "上传图片的接口",notes = "上传图片的接口",httpMethod = "POST") @CrossOrigin public String fileUpload( @ApiParam(value="项目的SVG",required=true) MultipartFile file) { //获取文件的老名称 String oldFileName = file.getOriginalFilename(); //获取文件要保存的路径 String url1 = String.valueOf(ClassLoader.getSystemResource("")); String url = url1.replace("/target/classes/",""); String newUrl =url.replace("file:/","").replace("%20"," "); String uuid = UUID.randomUUID().toString().replaceAll("-",""); String newFileName = uuid+oldFileName.substring(oldFileName.lastIndexOf(".")); //设置文件存放的位置 String strNow = new SimpleDateFormat("yyyyMMdd").format(new Date()).toString(); String roolPath = newUrl+PATH+"static/systemimg/"+strNow+"/"+newFileName; System.out.println(roolPath); // File files = new File(roolPath); if(!files.getParentFile().exists()){ files.getParentFile().mkdirs(); }else{ System.out.println("存在"); } try { if(!files.exists()){ System.out.println("存入文件"); file.transferTo(files); } }catch (Exception e){ e.printStackTrace(); } return "systemimg/"+strNow+"/"+newFileName; } @PostMapping(value="/ftpfileUpload",headers="content-type=multipart/form-data") @ApiOperation(value = "ftp上传图片的接口",notes = "ftp上传图片的接口",httpMethod = "POST") @CrossOrigin public Results<Object> ftpfileUpload(MultipartFile file) throws IOException { //C:/Users/Administrator/Desktop/img/image //获取文件的老名称 System.out.println("ftp文件上传"); String oldFileName = file.getOriginalFilename(); System.out.println("文件的Md5为:"+FileMd5.calcMD5(file.getInputStream())); String uuid = UUID.randomUUID().toString().replaceAll("-",""); String newFileName = uuid+oldFileName.substring(oldFileName.lastIndexOf(".")); //设置文件存放的位置 String strNow = new SimpleDateFormat("yyyyMMdd").format(new Date()).toString(); String fielPath = strNow+"/"+newFileName; String url=nginxUrl+fielPath; InputStream iput = null; try { iput = file.getInputStream(); } catch (IOException e) { e.printStackTrace(); } Boolean flag = FtpUtil.uploadFile(host,port,username,password,basePath,strNow,newFileName,iput); if(flag){ Results<Object> results = new Results<Object>(200,"SUCCESS", url); return results; } String filed = "FtpfileUpload filed"; Results<Object> results = new Results<Object>(235,"Error", filed); return results; } @PostMapping(value="/getFileMd5") @ApiOperation(value = "获取文件的MD5",notes = "获取文件的MD5",httpMethod = "POST") @CrossOrigin public Results<Object> getFileMd5(MultipartFile file) { Results<Object> results = null; //C:/Users/Administrator/Desktop/img/image //获取文件的老名称 try { byte [] byteArr=file.getBytes(); InputStream inputStream = new ByteArrayInputStream(byteArr); String fileMd = FileMd5.calcMD5(inputStream); results = new Results<Object>(235,"Success!", fileMd); }catch (Exception e){ e.printStackTrace(); String filed = "FtpfileUpload filed"; results = new Results<Object>(235,"Error", filed); } return results; } }
yml文件中的配置:
#Ftp静态资源服务器上传的路径 ftp: ftp-host: 192.168.0.114 ftp-port: 21 ftp-username: user ftp-password: sda!sdadas ftp-basePath: /NginxFile/Img/ #Nginx静态资源服务器的的配置 nginx: nginx-url: http://192.168.0.114:8080/Img/
最后各位看官们,记得给个赞哦,后续我会把linux上的ftp+nginx部署发出来,需要催更的请评论!