1.安装服务器 在项目中配置服务器属性
ftp.server.ip=你的FTP服务器ip地址
ftp.user=ftp
ftp.pass=ftppassword
ftp.server.http.prefix=ftp服务器配置的host路径
该路径为你的nginx\conf\vhost 下配置的location 具体配置可以搜索nginx配置
2.创建fileupload的service接口和实现类
在实现类中进行文件上传
private static Logger logger = LoggerFactory.getLogger(FileServiceImpl.class);
public String upload(MultipartFile file, String path){
//拿到文件名
String fileName = file.getOriginalFilename();
/**
* 对文件名重新命一个独一无二名避免在同一文件夹下发生覆盖
*/
//拿到文件格式名如 gpg , txt 等
String fileExtentionName = fileName.substring(fileName.lastIndexOf(".") + 1);
//拿到上传的文件名
String uploadFileName = UUID.randomUUID().toString() + "." + fileExtentionName;
//拿到上传的文件夹路径
File fileDir = new File(path);
//如果不存在进行创建
if(!fileDir.exists()){
//赋予创建文件夹的权限
fileDir.setWritable(true);
fileDir.mkdirs();
}
//创建完整的文件 此文件为tomcat下创建的用于中转的文件夹,该文件夹下完成上述file名的命名
File targetFile = new File(path, uploadFileName);
//进行文件上穿
try{
file.transferTo(targetFile);
//TODO 上传FTP服务器
FTPutils.uploadFile(Lists.newArrayList(targetFile));//请看3.
//TODO 删除tomcat下文件
targetFile.delete();
} catch (Exception e){
logger.error("文件上传异常", e);
}
return targetFile.getName();
}
3.ftp文件上传
private static Logger logger = LoggerFactory.getLogger(FtpClient.class);
//在配置文件中拿到ftp配置
private static String ftpIp = PropertiesUtils.getProperties("ftp.server.ip");
private static String ftpuser = PropertiesUtils.getProperties("ftp.user");
private static String ftppass = PropertiesUtils.getProperties("ftp.pass");
private String ip;
private int port;
private String use;
private String pwd;
private FTPClient ftpClient;
public FTPutils(String ip, int port, String use, String pwd){
this.ip = ip;
this.port = port;
this.pwd = pwd;
this.use = use;
}
//上传文件 对外开放唯一方法
public static boolean uploadFile(List<File> fileList){
//构造FTPutils
FTPutils ftPutils = new FTPutils(ftpIp, 21, ftpuser, ftppass);
logger.error("建立链接,开始上传文件");
//上传到ftp文件共享下的img文件夹,该文件夹提前收送创建
boolean result = ftPutils.uploadFile("img", fileList);
logger.error("上传文件结束");
return result;
}
private boolean uploadFile(String remotePath, List<File> fileList){
boolean upload = true;
FileInputStream fis = null;
if(connectFtp(ip, port, use, 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) {
logger.error("上传文件异常", e);
upload = false;
e.printStackTrace();
}finally {
try {
ftpClient.disconnect();
fis.close();
} catch (IOException e) {
logger.error("释放资源异常", e);
e.printStackTrace();
}
}
}
return upload;
}
private boolean connectFtp(String ip, int port, String use, String pwd){
boolean isSuccess = false;
ftpClient = new FTPClient();
try {
ftpClient.connect(ip);
ftpClient.login(use, pwd);
isSuccess = true;
} catch (IOException e) {
logger.error("链接错误", e);
}
return isSuccess;
}
}
4.配置文件中属性提取
private static Logger logger = LoggerFactory.getLogger(PropertiesUtils.class);
private static Properties properties;
//设置静态代码块 加载属性文件,初始化properties 类
static {
String fileName = "tmall.properties";
properties = new Properties();
try{
//加载属性配置文件
properties.load(new InputStreamReader(PropertiesUtils.class.getClassLoader().getResourceAsStream(fileName)));
} catch (Exception e){
logger.error("配置文件错误", e);
}
}
public static String getProperties(String key){
String value = properties.getProperty(key.trim());
if(value == null){
return "";
}
return value.trim();
}
public static String getProperties(String key, String defalueValue){
String value = properties.getProperty(key.trim());
if(value == null){
value = defalueValue;
}
return value.trim();
}
5.controller层进行调用
@RequestMapping("upload.do")
@ResponseBody
public ServerResponse upload(HttpSession session, @RequestParam(value = "upload_file", required = false) MultipartFile file, HttpServletRequest request){
User user = (User) session.getAttribute(Const.CURRENT_USER);
if(user == null){
return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(), "请登录后重试");
}
if(iUserService.checkAdminRole(user).isSuccess()){
//先拿到servlet上下文的路径 upload 页面调用的文件名
String path = request.getSession().getServletContext().getRealPath("upload");
String targetFileName = ifileService.upload(file, path);
String url = PropertiesUtils.getProperties("ftp.server.http.prefix") + targetFileName;
Map map = Maps.newHashMap();
map.put("uri", targetFileName);
map.put("url", url);
return ServerResponse.createBySuccess(map);
} else {
return ServerResponse.createByErrorMessage("登录用户无权限");
}
}
遇到的坑:
1.如果用nginx坐图片访问转发,在nginx中的image.imooc.com.conf文件的配置尤其重要,先自己配置完看能否打通,location的配置路径就是文章开头说的ftp.server.http.prefix=http://image.imooc.com/的路径,该路径就是ftp文件服务器上传文件的路径。
image.imooc.com.conf文件
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 / {
alias D:/ftpfile/img/;
add_header Access-Control-Allow-Origin *;
}
}
2.ftp服务器开启时候,共享目录也为nginx下的配置的路径 D:/ftpfile , img在上传的时候再加。不然copying文件的时候无法找到。