springboot 将文件上传到ftp文件服务器

先放上代码

//controller层:
public ServerResponse upload(@RequestParam("file") MultipartFile file, HttpServletRequest request){
        String path=request.getSession().getServletContext().getRealPath("/upload");
        String targetFileName=fileService.upload(file,path);
        String url= PropertiesUtil.getPropertity("ftp.server.http.prefix")+targetFileName;
        Map fileMap=new HashMap();
        fileMap.put("uri",targetFileName);
        fileMap.put("url",url);
        return ServerResponse.success(fileMap);
    }
//serivce层
@Service
@Slf4j
public class FileServiceImpl implements IFileService {
    public  String  upload(MultipartFile file,String path){
        String fileName=file.getOriginalFilename();
        String fileExtensionName=fileName.substring(fileName.lastIndexOf(".")+1);
        String uploadFileName= UUID.randomUUID().toString()+"."+fileExtensionName;
        log.info("开始上传文件,上传文件名{},上传路径{},新文件名{}",fileName,path,fileExtensionName);
        File fileDir=new File(path);
        if (!fileDir.exists()){
            fileDir.setWritable(true);
            fileDir.mkdirs();
        }
        File targetFile=new File(path,uploadFileName);
        try {
            file.transferTo(targetFile);
            //file upload successful

            // upload targetFile to my FTP server
            FTPUtil.uploadFile(Lists.newArrayList(targetFile));

            //  delete the file in upload folder after uploaded
            targetFile.delete();
        } catch (IOException e) {
            log.error("文件上传异常",e);
            return null;
        }
        return targetFile.getName();
    }
}
//ftp工具包类
package com.van.mall.util;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTPClient;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;

/**
 * @author Van
 * @date 2020/3/11 - 21:49
 */
@Data
@Slf4j
public class FTPUtil {
//    private static String ftpIp=PropertiesUtil.getPropertity("ftp.server.ip");
//    private static String ftpUser=PropertiesUtil.getPropertity("ftp.user");
//    private static String ftpPass=PropertiesUtil.getPropertity("ftp.pass");
    private static String ftpIp="ftp服务器ip";
    private static String ftpUser="root";
    private static String ftpPass="123";
    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;
    }
    private boolean connectServer(String ip,int port,String user,String pwd){
        ftpClient=new FTPClient();
        Boolean isSuccess=false;
        try {
            ftpClient.connect(ip);
            isSuccess=ftpClient.login(user,pwd);
        } catch (IOException e) {
            log.error("连接ftp服务器失败",e);
        }
        return isSuccess;
    }

    private boolean uploadFile(String remotePath, List<File>fileList) throws IOException {
        boolean upload=true;
        FileInputStream fileInputStream=null;
        //connect to ftpServer
        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
                     ) {
                    fileInputStream=new FileInputStream(fileItem);
                    ftpClient.storeFile(fileItem.getName(),fileInputStream);
                }
            } catch (IOException e) {
                log.error("上传文件异常",e);
                upload=false;
            }finally {
                fileInputStream.close();
                ftpClient.disconnect();
            }
        }
        return upload;
    }

    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服务器,结束上传,上传结果{}");
        return  result;
    }
}

1.从前端来的文件转给tomcat

controller:

在这里插入图片描述
前端传过来的文件,用MultipartFile类接收。
getRealPath是获取当前tomcat容器在这个电脑上的绝对位置
我的是:
在这里插入图片描述
等于我这里的path是
path=C:\Users\van\AppData\Local\Temp\tomcat-docbase.127561134716705087.8080/upload
注意这个文件夹一开始我是没有创建的

service层

这里避免整个文件夹下的文件名重复导致覆盖掉其他用户上传的文件,我给每个上传到tomcat的文件都重新改了名字,用UUID类,生成不可能重复的字符串
在这里插入图片描述
接着创建我的upload文件夹,并且在父文件类下创建子文件类
在这里插入图片描述
最后调用
在这里插入图片描述
方法,把文件传入该类,生成文件。
到这里就完成了从前端到tomcat的文件传输过程

文件从tomcat到ftp服务器的传输

首先我让自己的电脑变成ftp服务器:
在这里插入图片描述
这样的话浏览器输入,ftp:我的ip 就可访问到这个共享目录文件夹
可以从cmd命令ipconfig看到主机ip
在这里插入图片描述
在我电脑里面的话就是这个文件夹
在这里插入图片描述
在这里插入图片描述
我这里用得FTPClient是这个包:
import org.apache.commons.net.ftp.FTPClient;
依赖:

<dependency>
            <groupId>commons-net</groupId>
            <artifactId>commons-net</artifactId>
            <version>3.6</version>
        </dependency>

接着:
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200312214848431.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NDg0MTg0OQ==,size_16,color_FFFFFF,t_70在这里插入图片描述
在这里插入图片描述
最后是html

<form name="form1" action="/manage/product/upload.do" method="post" enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="submit" value="upload file">

</form>

我这里用的模板是thymleaf 用freemarker有点问题

大功告成

发布了34 篇原创文章 · 获赞 0 · 访问量 593

猜你喜欢

转载自blog.csdn.net/weixin_44841849/article/details/104828386