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();
    }
}


  • 10
    点赞
  • 72
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
### 回答1: 在 Spring Boot实现文件上传下载非常简单,你只需要在你的项目中引入对应的依赖,然后在你的代码中使用 Spring 提供的工具类即可。 首先,你需要在项目的 pom.xml 文件中引入 spring-boot-starter-web 依赖: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> ``` 然后你就可以在你的 Controller 中使用 Spring 提供的工具类来实现文件的上传下载了。 文件上传示例代码如下: ``` import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; @PostMapping("/upload") public void upload(@RequestParam("file") MultipartFile file) { // 使用 file.getInputStream() 和 file.getOriginalFilename() 获取文件输入流和文件名 // 然后你可以使用这些信息将文件保存到你的服务器中 } ``` 文件下载示例代码如下: ``` import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.InputStreamResource; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; @GetMapping("/download") public ResponseEntity<InputStreamResource> download() throws IOException { File file = new File("/path/to/your/file.txt"); InputStreamResource resource = new InputStreamResource(new FileInputStream(file)); return ResponseEntity.ok() .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + file.getName()) .contentType(MediaType.APPLICATION_OCTET_STREAM) .contentLength(file.length()) .body(resource); } ``` 注意, ### 回答2: Spring Boot提供了简单且方便的方式来实现文件上传下载的功能。以下是基于Spring Boot文件上传下载实现步骤: 文件上传: 1. 创建Spring Boot项目并添加所需的依赖项,例如spring-boot-starter-web和spring-boot-starter-data-jpa。 2. 创建一个Controller类来处理文件上传请求。在该类中,使用@RequestParam注解来接收上传的文件,并使用MultipartFile类型来处理文件数据。 3. 在Controller类中,使用File类来创建一个新的文件,并使用transferTo()方法将上传的文件保存到指定的位置。 4. 在Controller类中,使用ResponseEntity来返回上传成功的消息或错误消息。 文件下载: 1. 创建一个Controller类来处理文件下载请求。在该类中,使用@RequestParam注解来接收要下载的文件名。 2. 在Controller类中,使用File类来获取要下载的文件,并使用InputStreamResource类来将文件包装为可发送的资源。 3. 在Controller类中,使用ResponseEntity来返回文件资源,并设置响应头部信息,例如Content-Disposition来指定文件名。 4. 在客户端发出下载文件请求时,将通过Controller类提供的链接来下载文件。 在实现文件上传下载时,还可以添加文件大小限制、文件类型限制和安全校验等功能来提高系统的稳定性和安全性。此外,还可以使用第三方库,如Apache Common FileUpload和Apache POI来更好地处理文件的上传下载。 ### 回答3: Spring Boot是一个开源的Java开发框架,可以非常方便地实现文件的上传下载功能。 文件上传功能可以通过使用Spring Boot提供的MultipartFile类来实现。首先,需要在Spring Boot的Controller中定义一个接口来处理文件上传的请求。可以使用@PostMapping注解来标识这个接口处理POST请求,然后使用@RequestParam注解来指定接收文件的参数,例如@RequestParam("file") MultipartFile file。接收到文件后,可以调用MultipartFile类的transferTo()方法将文件保存到指定的路径。 文件下载功能可以通过使用Spring Boot提供的Resource类来实现。首先,需要在Spring Boot的Controller中定义一个接口来处理文件下载的请求。可以使用@GetMapping注解来标识这个接口处理GET请求,然后使用@RequestParam注解来指定接收文件名的参数,例如@RequestParam("filename") String filename。接收到文件名后,可以使用Resource类的createResource()方法创建一个Resource对象,然后使用ResponseEntity类将文件返回给客户端。 在实现文件上传下载功能时,还需要注意设置合适的文件保存路径和文件访问路径。可以在application.properties文件中配置文件保存路径,例如spring.servlet.multipart.location=/path/to/save/files。在文件访问路径方面,可以使用ResourceHandlerRegistry类的addResourceHandler()方法来配置文件访问路径,例如registry.addResourceHandler("/files/**").addResourceLocations("file:/path/to/save/files/")。 通过上述方式,可以很方便地使用Spring Boot实现文件的上传下载功能。在实际开发中,还可以结合前端技术实现更加友好的文件上传下载界面。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值