Bootstrap

SpringBoot实现文件上传、下载到服务器

通过一个小项目实现文件的上传、下载,在线打开与文件删除,并将文件的信息保存到数据库中。
所用技术:SpringBoot+thymeleaf+Mybatis
小项目地址:https://github.com/lindaifeng/MyFileUpload

页面没有任何花里胡哨的东西,只用于做数据展示用,主要关注于后端代码的实现。
用户登录后进入首页展示该用户上传的文件信息,并可以进行文件上传,下载,删除,注销和在线打开功能,文件被保存在项目的指定路径下,文件信息保存在了数据库中。

在这里插入图片描述

一、SpringBoot实现文件上传,下载

1、文件上传:

文件前端传入,后端获取到文件通过输出流写入文件。

上传的主要核心是ResourceUtils获取项目的相对路径,然后通过文件的transferTo方法保存到指定路径的文件夹下

#文件上传大小配置 单个文件大小 总的文件大小
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=100MB
 		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency> 
@PostMapping("/upload")
    public String upload(HttpSession session, @RequestParam("file") MultipartFile file, RedirectAttributes attributes) throws IOException {
        System.out.println("准备上传");
        if (file.isEmpty()) {
            attributes.addFlashAttribute("msg", "上传的文件不能为空");
            return "redirect:/files/fileAll";
        }

        //获取原始文件名称
        String originalFilename = file.getOriginalFilename();

        //获取文件后缀名
        String extension = "." + FilenameUtils.getExtension(originalFilename); //.jpg
        //获取新文件名称 命名:时间戳+UUID+后缀
        String newFileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())
                + UUID.randomUUID().toString().substring(0, 4)
                + extension;

        //获取资源路径 classpath的项目路径+/static/files  classpath就是resources的资源路径
        String path = ResourceUtils.getURL("classpath:").getPath() + "static/files/";
        //新建一个时间文件夹标识,用来分类
        String format = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        //全路径(存放资源的路径) 资源路径+时间文件夹标识
        String dataDir = path + format;
        System.out.println(dataDir);

        //全路径存放在文件类中,判断文件夹是否存在不存在就创建
        File dataFile = new File(dataDir);  //也可以直接放进去进行拼接 File dataFile = new File(path,format);
        if (!dataFile.exists()) {
            dataFile.mkdirs();
        }

        //文件上传至指定路径
        file.transferTo(new File(dataFile, newFileName));

        //文件信息保存到数据库
        //获取文件格式
        String type = file.getContentType();
        //获取文件大小
        long size = file.getSize();
		//封装进实体类
        fileUpload.setOldFileName(originalFilename);
        fileUpload.setNewFileName(newFileName);
        fileUpload.setExt(extension);
        fileUpload.setPath("/files/" + format);
        fileUpload.setGlobalPath(dataDir);
        fileUpload.setDownCounts(0);
        fileUpload.setType(type);
        fileUpload.setSize(size);
        fileUpload.setUploadTime(new Date());
        User user = (User) session.getAttribute("user");
        fileUpload.setUserId(user.getId());

        boolean img = type.startsWith("image");//检测字符串是否以指定的前缀开始
        if (img) {
            fileUpload.setIsImg("是");
        } else {
            fileUpload.setIsImg("否");
        }
        System.out.println(fileUpload);
        int b = fileUploadService.saveFile(fileUpload);
        System.out.println(b);
        if (b == 1) {
            attributes.addFlashAttribute("msg", "保存成功!");
        } else {
            attributes.addFlashAttribute("msg", "保存失败!");
        }
        System.out.println("上传结束");
        return "redirect:/files/fileAll";
    }

2、文件下载

下载:获取到文件路径,通过输入流读取,再获取响应输出流,通过工具类中的拷贝方法IOUtils.copy()实现在线打开,通过附件形式实现文件下载。(前提是需要依赖包才能使用IOUtils工具类)

 		<dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.4</version>
     	</dependency>

在这里插入图片描述

 @GetMapping("/download")
    public void download(Integer id, String openStyle, HttpServletResponse response) throws IOException {
        
        FileUpload fileUpload = fileUploadService.findFileById(id);
        //获取全路径
//        String globalPath = ResourceUtils.getURL("classpath:").getPath() + "static" + fileUpload.getPath() + "/";
        String globalPath = fileUpload.getGlobalPath();
        System.out.println(globalPath);
        FileInputStream fis = new FileInputStream(new File(globalPath, fileUpload.getNewFileName()));
        //根据传过来的参数判断是下载,还是在线打开
        if ("attachment".equals(openStyle)) {
            //并更新下载次数
            fileUpload.setDownCounts(fileUpload.getDownCounts() + 1);
            fileUploadService.updateFileDownCounts(id, fileUpload.getDownCounts());
            //以附件形式下载  点击会提供对话框选择另存为:
            response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileUpload.getOldFileName(), "utf-8"));

        }
        //获取输出流
        ServletOutputStream os = response.getOutputStream();
        //利用IO流工具类实现流文件的拷贝,(输出显示在浏览器上在线打开方式)
        IOUtils.copy(fis, os);
        IOUtils.closeQuietly(fis);
        IOUtils.closeQuietly(os);
    }

点击会提供对话框选择另存为: response.setHeader( “Content-Disposition “,
“attachment;filename= “+filename);

通过IE浏览器直接选择相关应用程序插件打开: response.setHeader( “Content-Disposition “,
“inline;filename= “+fliename)

下载前询问(是打开文件还是保存到计算机) response.setHeader( “Content-Disposition “,
“filename= “+filename);

至此文件的上传下载就完成了,其他用户名显示,注销,删除功能可在项目中查看(删除功能需要实现删除数据库指定文件信息并删除指定文件)

二、SpringBoot实现文件上传至远程服务器(ftp)

FTP服务器(File Transfer Protocol Server)是在互联网上提供文件存储和访问服务的计算机,它们依照FTP协议提供服务。 FTP是File Transfer Protocol(文件传输协议)。顾名思义,就是专门用来传输文件的协议。简单地说,支持FTP协议的服务器就是FTP服务器。
FTP是用来在两台计算机之间传输文件,是Internet中应用非常广泛的服务之一。它可根据实际需要设置各用户的使用权限,同时还具有跨平台的特性,快速方便地上传、下载文件。

  <!-- Apache 的 common-net  是 commos 顶级项目下一个非常强大的用于网络编程的子项目 -->
        <dependency>
            <groupId>commons-net</groupId>
            <artifactId>commons-net</artifactId>
            <version>3.6</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.TimeZone;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

import org.apache.log4j.Logger;


/**
 * @author: 清峰
 * @date: 2020/11/2 9:30
 * @code: 愿世间永无Bug!
 * @description:
 */

public class Ftp {
    private FTPClient ftpClient;
    private String strIp;
    private int intPort;
    private String user;
    private String password;

    private static Logger logger = Logger.getLogger(Ftp.class.getName());

    /* *
     * Ftp构造函数
     */
    public Ftp(String strIp, int intPort, String user, String Password) {
        this.strIp = strIp;
        this.intPort = intPort;
        this.user = user;
        this.password = Password;
        this.ftpClient = new FTPClient();
    }

    /**
     * @return 判断是否登入成功
     */
    public boolean ftpLogin() {
        boolean isLogin = false;
        FTPClientConfig ftpClientConfig = new FTPClientConfig();
        ftpClientConfig.setServerTimeZoneId(TimeZone.getDefault().getID());
        this.ftpClient.setControlEncoding("GBK");
        this.ftpClient.configure(ftpClientConfig);
        try {
            if (this.intPort > 0) {
                this.ftpClient.connect(this.strIp, this.intPort);
            } else {
                this.ftpClient.connect(this.strIp);
            }
            // FTP服务器连接回答
            int reply = this.ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                this.ftpClient.disconnect();
                logger.error("登录FTP服务失败!");
                return isLogin;
            }
            this.ftpClient.login(this.user, this.password);
            // 设置传输协议
            this.ftpClient.enterLocalPassiveMode();
            this.ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            logger.info("恭喜" + this.user + "成功登陆FTP服务器");
            isLogin = true;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(this.user + "登录FTP服务失败!" + e.getMessage());
        }
        this.ftpClient.setBufferSize(1024 * 2);
        this.ftpClient.setDataTimeout(30 * 1000);
        return isLogin;
    }

    /**
     * @退出关闭服务器链接
     */
    public void ftpLogOut() {
        if (null != this.ftpClient && this.ftpClient.isConnected()) {
            try {
                boolean reuslt = this.ftpClient.logout();// 退出FTP服务器
                if (reuslt) {
                    logger.info("成功退出服务器");
                }
            } catch (IOException e) {
                e.printStackTrace();
                logger.warn("退出FTP服务器异常!" + e.getMessage());
            } finally {
                try {
                    this.ftpClient.disconnect();// 关闭FTP服务器的连接
                } catch (IOException e) {
                    e.printStackTrace();
                    logger.warn("关闭FTP服务器的连接异常!");
                }
            }
        }
    }

    /***
     * 上传Ftp文件
     * @param localFile 当地文件
     * romotUpLoadePath上传服务器路径 - 应该以/结束
     * */
    public boolean uploadFile(File localFile, String romotUpLoadePath) {
        BufferedInputStream inStream = null;
        boolean success = false;
        try {
            this.ftpClient.changeWorkingDirectory(romotUpLoadePath);// 改变工作路径
            inStream = new BufferedInputStream(new FileInputStream(localFile));
            logger.info(localFile.getName() + "开始上传.....");
            success = this.ftpClient.storeFile(localFile.getName(), inStream);
            if (success == true) {
                logger.info(localFile.getName() + "上传成功");
                return success;
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            logger.error(localFile + "未找到");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inStream != null) {
                try {
                    inStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return success;
    }

    /***
     * 下载文件
     * @param remoteFileName   待下载文件名称
     * @param localDires 下载到当地那个路径下
     * @param remoteDownLoadPath remoteFileName所在的路径
     * */

    public boolean downloadFile(String remoteFileName, String localDires,
                                String remoteDownLoadPath) {
        String strFilePath = localDires + remoteFileName;
        BufferedOutputStream outStream = null;
        boolean success = false;
        try {
            this.ftpClient.changeWorkingDirectory(remoteDownLoadPath);
            outStream = new BufferedOutputStream(new FileOutputStream(
                    strFilePath));
            logger.info(remoteFileName + "开始下载....");
            success = this.ftpClient.retrieveFile(remoteFileName, outStream);
            if (success == true) {
                logger.info(remoteFileName + "成功下载到" + strFilePath);
                return success;
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(remoteFileName + "下载失败");
        } finally {
            if (null != outStream) {
                try {
                    outStream.flush();
                    outStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        if (success == false) {
            logger.error(remoteFileName + "下载失败!!!");
        }
        return success;
    }

    /***
     * @上传文件夹
     * @param localDirectory
     *            当地文件夹
     * @param remoteDirectoryPath
     *            Ftp 服务器路径 以目录"/"结束
     * */
    public boolean uploadDirectory(String localDirectory,
                                   String remoteDirectoryPath) {
        File src = new File(localDirectory);
        try {
            remoteDirectoryPath = remoteDirectoryPath + src.getName() + "/";
            this.ftpClient.makeDirectory(remoteDirectoryPath);
            // ftpClient.listDirectories();
        } catch (IOException e) {
            e.printStackTrace();
            logger.info(remoteDirectoryPath + "目录创建失败");
        }
        File[] allFile = src.listFiles();
        for (int currentFile = 0; currentFile < allFile.length; currentFile++) {
            if (!allFile[currentFile].isDirectory()) {
                String srcName = allFile[currentFile].getPath().toString();
                uploadFile(new File(srcName), remoteDirectoryPath);
            }
        }
        for (int currentFile = 0; currentFile < allFile.length; currentFile++) {
            if (allFile[currentFile].isDirectory()) {
                // 递归
                uploadDirectory(allFile[currentFile].getPath().toString(),
                        remoteDirectoryPath);
            }
        }
        return true;
    }

    /***
     * @下载文件夹
     * @param
     * @param remoteDirectory 远程文件夹
     * */
    public boolean downLoadDirectory(String localDirectoryPath, String remoteDirectory) {
        try {
            String fileName = new File(remoteDirectory).getName();
            localDirectoryPath = localDirectoryPath + fileName + "//";
            new File(localDirectoryPath).mkdirs();
            FTPFile[] allFile = this.ftpClient.listFiles(remoteDirectory);
            for (int currentFile = 0; currentFile < allFile.length; currentFile++) {
                if (!allFile[currentFile].isDirectory()) {
                    downloadFile(allFile[currentFile].getName(), localDirectoryPath, remoteDirectory);
                }
            }
            for (int currentFile = 0; currentFile < allFile.length; currentFile++) {
                if (allFile[currentFile].isDirectory()) {
                    String strremoteDirectoryPath = remoteDirectory + "/" + allFile[currentFile].getName();
                    downLoadDirectory(localDirectoryPath, strremoteDirectoryPath);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            logger.info("下载文件夹失败");
            return false;
        }
        return true;
    }

    // FtpClient的Set 和 Get 函数
    public FTPClient getFtpClient() {
        return ftpClient;
    }

    public void setFtpClient(FTPClient ftpClient) {
        this.ftpClient = ftpClient;
    }

    public static void main(String[] args) throws IOException {
        Ftp ftp = new Ftp("10.3.15.1", 21, "ghips", "ghipsteam");
        ftp.ftpLogin();
        //上传文件夹
        ftp.uploadDirectory("d://DataProtemp", "/home/data/");
        //下载文件夹
        ftp.downLoadDirectory("d://tmp//", "/home/data/DataProtemp");
        ftp.ftpLogOut();
    }
}


;