springboot 文件上传和下载

6 篇文章 0 订阅
2 篇文章 0 订阅

 

FileServiceImpl 类:
 
package com.rbpm.service.Impl;

import ch.qos.logback.core.spi.ScanException;
import com.rbpm.service.FileService;
import io.swagger.models.auth.In;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;

@Service
public class FileServiceImpl implements FileService {

    // 文件上传根目录
    @Value("${UPLOAD_URL}")
    private String UPLOAD_URL;

    // 下载的文件的根路径
    @Value("${download_URL}")
    private String download_URL;

    private Logger m_Logger = LoggerFactory.getLogger("FileServiceImpl");
    private Integer m_Index = 0;

    /**
     * @Description: 单文件上传
     * @Author:
     * @Date: 2018/4/9 17:15
     */
    public String upload(MultipartFile file) {
        try {
            if (file.isEmpty()) {
                return "文件为空";
            }
            // 获取文件名
            String fileName = file.getOriginalFilename();
            m_Logger.info("上传的文件名为:" + fileName);
            // 获取文件的后缀名
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            m_Logger.info("文件的后缀名为:" + suffixName);

            // 设置文件存储路径
            String filePath = UPLOAD_URL;
            String path = filePath + fileName + suffixName;

            File dest = new File(path);
            // 检测是否存在目录
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();// 新建文件夹
            }
            file.transferTo(dest);// 文件写入
            return "上传成功";
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "上传失败";
    }

    /**
     * @Description: 创建文件夹
     * @Author:
     * @Date: 2018/4/9 17:15
     */
    public Map addFileFolder(HttpServletRequest request, String Path) {
        Map tResultMap = new HashMap();
        String mkDirectoryPath = Path;  // 路径格式:"d:\\aim\\y"

        File file = null;
        int j = 1;
        try {
            file = new File(Path);
            if (!file.exists()) {
                file.mkdirs();
            } else {
                while (file.exists()) {
                    mkDirectoryPath = Path + "-副本(" + getNum(j, Path) + ")";
                    file = new File(mkDirectoryPath);
                    file.mkdirs();
                    break;
                }
            }
            tResultMap.put("msg", "建立成功");
            System.out.println(mkDirectoryPath + "建立完毕");
        } catch (Exception e) {
            tResultMap.put("msg", "建立失败");
            System.out.println(mkDirectoryPath + "建立失败");
        } finally {
            file = null;
        }
        return tResultMap;
    }

    public int getNum(int i, String Path) {
        String path = Path + "-副本(" + i + ")";
        File file = new File(path);
        if (file.exists()) {
            i++;
            return getNum(i, Path);
        } else {
            return i;
        }
    }

    /**
     * @Description: 上传多个文件
     * @Author: Mr.Zhong
     * @Date: 2018/4/9 17:26
     */
    public String uploads(HttpServletRequest request, MultipartFile[] file) {
        try {
            //上传目录地址
            String uploadDir = request.getSession().getServletContext().getRealPath("/") + "upload/";
            //如果目录不存在,自动创建文件夹
            File dir = new File(uploadDir);
            if (!dir.exists()) {
                dir.mkdir();
            }
            //遍历文件数组执行上传
            for (int i = 0; i < file.length; i++) {
                if (file[i] != null) {
                    //调用上传方法
                    executeUpload(uploadDir, file[i]);
                }
            }
        } catch (Exception e) {
            //打印错误堆栈信息
            e.printStackTrace();
            return "上传失败";
        }
        return "上传成功";
    }


    /**
     * 上传方法为公共方法
     */
    private void executeUpload(String uploadDir, MultipartFile file) throws Exception {
        //文件后缀名
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        //上传文件名
        String filename = UUID.randomUUID() + suffix;
        //服务器端保存的文件对象
        File serverFile = new File(uploadDir + filename);
        //将上传的文件写入到服务器端文件内
        file.transferTo(serverFile);
    }

    /**
     * @Description: 扫描文件(根据父级目录查当前目录下的文件和文件夹)
     * @Author:
     * @Date: 2018/4/9 17:39
     */
    private static ArrayList<Object> scanFiles = new ArrayList<Object>();

    public Map scanFilesWithRecursion(String folderPath) throws ScanException {
        folderPath = UPLOAD_URL;
        folderPath.length();

        HashMap tResultMap = new HashMap();
        tResultMap.put("status", "failed");
        ArrayList<String> dirctorys = new ArrayList<String>();
        File directory = new File(folderPath);
        if (!directory.isDirectory()) {
            throw new ScanException('"' + folderPath + '"' + " input path is not a Directory , please input the right path of the Directory. ^_^...^_^");
        }

        File[] filelist = directory.listFiles();

        List tFolderList = new ArrayList();
        List tFilesList = new ArrayList();
        for (File tFile : filelist) {
            /**如果当前是文件夹,进入递归扫描文件夹**/
            if (tFile.isDirectory())
                tFolderList.add(tFile.getName());
            else {
                tFilesList.add(tFile.getName());
            }
        }
        tResultMap.put("folder", tFolderList);
        tResultMap.put("files", tFilesList);
        tResultMap.put("status", "success");
        return tResultMap;
    }

    /**
     * @Description: 获取目录树
     * @Author:
     * @Date: 2018/4/9 17:39
     */
    public Map scanFilesWithNoRecursion(String folderPath) {
        Map tResultMap = new HashMap();
        m_Index = 0;
        tResultMap.put("data", recursion(folderPath));
        return tResultMap;
    }

    /**
     * @Description: 获取目录树的处理方法
     * @Author:
     * @Date: 2018/4/9 17:39
     */
    public List recursion(String vFolderPath) {
        List tResultList = new ArrayList();

        File directory = new File(vFolderPath);
        File[] tfiles = directory.listFiles();

        for (File tFile : tfiles) {
            Map tMap = new HashMap();
            if (tFile.isDirectory()) {
                tMap.put("children", recursion(vFolderPath + "/" + tFile.getName()));
                tMap.put("label",tFile.getName());
                tMap.put("id", ++m_Index);
                tResultList.add(tMap);
            }

        }
        return tResultList;
    }

    /**
     * @Description: 下载
     * @Author:
     * @Date: 2018/4/9 17:39
     */
    public Map download(HttpServletResponse res) {
        Map tResultMap = new HashMap();
        String fileName = download_URL;
        res.setHeader("content-type", "application/octet-stream");
        res.setContentType("application/octet-stream");
        res.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        byte[] buff = new byte[1024];
        BufferedInputStream bis = null;
        OutputStream os = null;
        try {
            os = res.getOutputStream();
            bis = new BufferedInputStream(new FileInputStream(new File(UPLOAD_URL
                    + fileName)));
            int i = bis.read(buff);
            while (i != -1) {
                os.write(buff, 0, buff.length);
                os.flush();
                i = bis.read(buff);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.println("success");
        return tResultMap;
    }

    /**
     * @Description: 文件或文件夹重命名
     * @Author:
     * @Date: 2018/4/9 17:39
     */
    public Map updateFileName(String Path , String newPath) {

        Map tResultMap = new HashMap();

        //想命名的原文件的路径
        File file = new File(Path);
        if(file.exists()) {
            file.renameTo(new File(newPath));
            tResultMap.put("msg","修改文件名成功");
        }
        return tResultMap;
    }

    public Map deleteDirectory(List<String> pathList) {
        Map tResultMap = new HashMap();
        tResultMap.put("status","failed");

        for (int i=0;i<pathList.size();i++){
            deleteDirectoryDetail(UPLOAD_URL+pathList.get(i));
        }
        tResultMap.put("status","success");
        return tResultMap;
    }

    /**
     * 删除文件和文件夹
     * @param path
     * @return
     */
    public Map deleteDirectoryDetail(String path){
        Map tResultMap = new HashMap();
        //tResultMap.put("status","failed");
        // 如果dir不以文件分隔符结尾,自动添加文件分隔符
        if (!path.endsWith(File.separator))
            path = path + File.separator;
        File dir = new File(path);
        try {
            if(dir.exists()){
                File[] tmp=dir.listFiles();
                for(int i=0;i<tmp.length;i++){
                    if(tmp[i].isDirectory()){
                        deleteDirectoryDetail(path+"/"+tmp[i].getName());

                    }
                    else{
                        tmp[i].delete();
                        System.out.println(tmp[i]+"删除成功");
                    }
                }
                dir.delete();
                System.out.println(dir+"删除成功");
            }
            //tResultMap.put("status","success");
        }catch (Exception e){
            e.printStackTrace();
            tResultMap.put("msg",e.getMessage());
        }finally {
            return tResultMap;
        }


    }
}
FileController 处理类
 
package com.rbpm.controller.controller;

import ch.qos.logback.core.spi.ScanException;
import com.rbpm.service.FileService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

@RestController
@RequestMapping("/file")
@CrossOrigin
public class FileController {

    @Autowired
    private FileService m_fileService;

    @Value("${UPLOAD_URL}")
    private String UPLOAD_URL;

    // 单文件上传
    @ApiOperation(value = "/upload", notes = "上传文件")
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public String upload(@RequestParam("file") MultipartFile file) {
        return m_fileService.upload(file);
    }

    // 多个文件上传
    @ApiOperation(value = "uploads", notes = "多个文件上传")
    @RequestMapping(value = "/uploads", method = RequestMethod.POST)
    @ResponseBody
    public String uploads(HttpServletRequest request, MultipartFile[] file) {
        return m_fileService.uploads(request, file);
    }

    // 创建文件夹
    @ApiOperation(value = "createFolder", notes = "创建文件夹")
    @RequestMapping(value = "/createFolder", method = RequestMethod.POST)
    public Map addFileFolder(HttpServletRequest request, String Path) {
        return m_fileService.addFileFolder(request, Path);
    }

    // 扫描文件(根据父级目录查当前目录下的文件和文件夹)
    @ApiOperation(value = "getCurrentFolderList", notes = "扫描文件(根据父级目录查当前目录下的文件和文件夹)")
    @RequestMapping(value = "/getCurrentFolderList", method = RequestMethod.GET)
    public Map scanFilesWithRecursion(String folderPath) throws ScanException {
        return m_fileService.scanFilesWithRecursion(folderPath);
    }

    // 获取目录树
    @ApiOperation(value = "getFolderTree", notes = "获取目录树")
    @RequestMapping(value = "/getFolderTree", method = RequestMethod.GET)
    public Map scanFilesWithNoRecursion(String folderPath) throws ScanException {
        return m_fileService.scanFilesWithNoRecursion(UPLOAD_URL);
    }

    // 文件下载
    @ApiOperation(value = "download", notes = "文件下载")
    @RequestMapping(value = "/download", method = RequestMethod.GET)
    public Map download(HttpServletResponse res) throws IOException {
        return m_fileService.download(res);
    }

    // 文件或文件夹重命名
    @ApiOperation(value = "updateFileName", notes = "文件或文件夹重命名")
    @RequestMapping(value = "/updateFileName", method = RequestMethod.POST)
    public Map rename(String Path, String newPath) {
        return m_fileService.updateFileName(Path, newPath);
    }

    // 删除文件或文件夹
    @ApiOperation(value = "deleteDirectory", notes = "删除文件或文件夹")
    @RequestMapping(value = "/deleteDirectory", method = RequestMethod.POST)
    public Map deleteDirectory(List<String> Path) {
        return m_fileService.deleteDirectory(Path);
    }
}
application.properties配置文件
 
 
#文件上传大小限制
spring.http.multipart.maxFileSize=5096Mb
spring.http.multipart.maxRequestSize=5096Mb

#文件上传根目录
UPLOAD_URL=D:/aim/

#下载的文件
download_URL=a.txt

 

 

 

 

 

 

 

 

 

 

 

 

 

Spring Boot 提供了方便的方式来处理文件上传下载。下面我们来详细了解一下它的用法。 ## 文件上传 ### 1. 添加依赖 在 pom.xml 文件中添加以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <version>2.5.5</version> </dependency> ``` ### 2. 配置文件上传限制 在配置文件中增加以下配置: ```yaml spring: servlet: multipart: max-file-size: 10MB # 最大文件大小 max-request-size: 20MB # 最大请求大小 ``` ### 3. 创建文件上传接口 创建一个文件上传的接口,代码如下: ```java @RestController public class FileUploadController { private static final Logger logger = LoggerFactory.getLogger(FileUploadController.class); @PostMapping("/upload") public String uploadFile(@RequestParam("file") MultipartFile file) { try { // 获取文件名 String fileName = file.getOriginalFilename(); // 获取文件内容 byte[] content = file.getBytes(); // 处理文件内容 // ... return "上传成功!"; } catch (IOException e) { logger.error("文件上传失败!", e); } return "上传失败!"; } } ``` ### 4. 测试文件上传 使用 Postman 等工具测试文件上传接口即可。 ## 文件下载 ### 1. 添加依赖 同文件上传。 ### 2. 创建文件下载接口 创建一个文件下载的接口,代码如下: ```java @RestController public class FileDownloadController { private static final Logger logger = LoggerFactory.getLogger(FileDownloadController.class); @GetMapping("/download") public void downloadFile(HttpServletResponse response) { try { // 获取文件路径 String filePath = "file.txt"; // 获取文件内容 byte[] content = Files.readAllBytes(Paths.get(filePath)); // 设置响应头 response.setContentType("text/plain"); response.setHeader("Content-Disposition", "attachment; filename=file.txt"); // 写出文件内容 OutputStream outputStream = response.getOutputStream(); outputStream.write(content); outputStream.flush(); outputStream.close(); } catch (IOException e) { logger.error("文件下载失败!", e); } } } ``` ### 3. 测试文件下载 使用浏览器访问文件下载接口即可下载文件
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值