spring boot实现文件上传下载

Java 专栏收录该内容
18 篇文章 0 订阅


前言

spring boot 项目中的上传,下载。


1. controller

import org.apache.commons.compress.archivers.ArchiveEntry;
import org.apache.commons.compress.archivers.zip.Zip64Mode;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import cn.hutool.core.util.ZipUtil;
import java.util.zip.ZipOutputStream;

@RestController
@RequestMapping("/files")
public class FileController {

    @Autowired
    private FileService fileService;

    /**
     * 单一文件上传接口,上传失败由统一异常处理返回
     * @param file
     * @return
     */
    @PostMapping("/uploadFile")
    public R fileUpload(MultipartFile file){
        if(file.isEmpty()){
            return R.fail("请选择文件!");
        }
        String uploadFile = fileService.uploadFile(file);
        return R.ok(uploadFile, "文件上传成功!");
    }

    @PostMapping("/uploadFiles")
    public R filesUpload(MultipartFile[] files){
        if(files.length <=0 ){
            return R.fail("请选择文件!");
        }
        List<String> filesPath = fileService.uploadFiles(files);
        return R.ok(filesPath, "文件上传成功!");
    }

    @GetMapping("/download")
    public void fileDownload(HttpServletRequest request, HttpServletResponse response){
        fileService.downloadFile(request, response);
    }
// zip打包
@RequestMapping("/download/zip")
    public void downloadForZip(HttpServletResponse response) throws IOException {
        //这里设置打包后的zip文件名
        String downloadName = "测试"+".zip";
        try{
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition", "attachment;fileName=" + new String(downloadName.getBytes(),"ISO8859-1"));
        }catch(UnsupportedEncodingException e){
            System.out.println("----------下载文件名编码时出现错误------"+e.getMessage());
        }
        OutputStream outputStream = response.getOutputStream();
        ZipOutputStream zos = new ZipOutputStream(outputStream);
        // 方式一:
//        ZipArchiveOutputStream zous = new ZipArchiveOutputStream(outputStream);
//        zous.setUseZip64(Zip64Mode.AsNeeded);
//        zous.setEncoding("utf-8");
        try{
            //我这里是通过不同产品类型生成不同产品的二维码图片流
            //具体你想生成什么类型的多个文件打包,只需要循环创建ArchiveEntry 然后zous.putArchiveEntry(entry)就可以了
//            StoreProductType[] storeProductTypes = StoreProductType.values();
//            for (StoreProductType storeProductType : storeProductTypes) {
//                String url = "http://m.xxx.cn/goods/pay/xxx.html?productid="+storeProductType.getProductId()
//                        + "&agencycode="+ agencyId +"&channelid=def&appfrom=sqjk&isstore=1";
//                //打包文件里的每个文件的名字
//                String imgName = storeProductType.getDescription()+".png";
//                ByteArrayOutputStream out = QRCode.from(url).to(ImageType.PNG).withSize(300,300).stream();
//                byte[] bytes = out.toByteArray();
//                ArchiveEntry entry = new ZipArchiveEntry(imgName);
//                zous.putArchiveEntry(entry);
//                zous.write(bytes);
//                zous.closeArchiveEntry();
//                if (out != null) {
//                    out.close();
//                }
            // 方式二: 
            String filePath = "http://192.168.1.138/group1/M00/00/00/wKgBvWBQY_OAaRBKAAIIxvji4o8112.pdf";
            String[] strings = filePath.substring(accessPath.length()).split("/", 2);
            String[] paths = new String[2];
            InputStream[] ins = new InputStream[2];
            for (int i=0; i<2; i++) {
                //打包文件里的每个文件的名字
                String imgName = "每个文件名" +i +".pdf";
                paths[i] = imgName;
                byte[] bytes = fastdfsClientService.download(strings[0], strings[1]);
                ins[i] = new ByteArrayInputStream(bytes);
            }
            ZipUtil.zip(zos, paths, ins);
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("---------------生成打包流出错----------------"+e.getMessage());
        }finally {
            zos.close();
//            zous.close();
            if (outputStream != null) {
                outputStream.close();
            }
        }
    }
}

生成二维码并打包参考资料

2. service

2.1 LocalFileServiceImpl

@Service
@Primary      //用哪个实现
public class LocalFileServiceImpl implements FileService {

    Logger logger = LoggerFactory.getLogger(LocalFileServiceImpl.class);

    @Value("${file.upload.path}")
    private String uploadPath;
    @Value("${file.download.path}")
    private String downloadPath;

    @Override
    public String uploadFile(MultipartFile file) {
        String filename = file.getOriginalFilename();
        File filePath;
        try {
            filePath = new File(uploadPath + filename);
            // 检测是否存在目录
            if (!filePath.getParentFile().exists()) {
                filePath.getParentFile().mkdirs();// 新建文件夹
            }
            file.transferTo(filePath);
            logger.info("文件上传成功!");
            return uploadPath + filename;
        } catch (IOException e) {
            logger.info("文件上传失败!");
            throw new BaseException(e.getMessage());
        }
    }

    @Override
    public List uploadFiles(MultipartFile[] files) {
        File filePath;
        List<String> filesPath = new ArrayList<>();
        for (int i = 0; i < files.length; i++) {
            if (files[i].isEmpty()) {
                throw new BaseException("上传第\" + (i++) + \"个文件失败");
            }
            String fileName = files[i].getOriginalFilename();

            filePath = new File(uploadPath + fileName);
            try {
                // 检测是否存在目录
                if (!filePath.getParentFile().exists()) {
                    filePath.getParentFile().mkdirs();// 新建文件夹
                }
                files[i].transferTo(filePath);
                logger.info("第" + (i + 1) + "个文件上传成功");
                filesPath.add(uploadPath + fileName);
            } catch (IOException e) {
                logger.error(e.toString(), e);
                throw new BaseException("上传第\" + (i++) + \"个文件失败");
            }
        }
        return filesPath;
    }

    @Override
    public void downloadFile(HttpServletRequest request, HttpServletResponse response) {
        String fileName = "服务器及终端配置.xlsx";// 文件名
        if (fileName != null) {
            //设置文件路径
            File file = new File(downloadPath + fileName);
            //File file = new File(realPath , fileName);
            if (file.exists()) {
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    response.setContentType("application/force-download");// 设置强制下载不打开
                    response.addHeader("Content-Disposition", "attachment;fileName=" + new String(fileName.getBytes("utf-8"),"ISO8859-1"));// 设置文件名
                    byte[] buffer = new byte[1024];
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                    logger.info("下载成功!");
                } catch (Exception e) {
                    logger.info("下载失败!");
                    throw new BaseException("下载失败!" + e.getMessage());
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }
}

2.2 FastDFSFileServiceImpl

@Service
public class FastDFSFileServiceImpl implements FileService {

    @Override
    public String uploadFile(MultipartFile file) {
        return null;
    }

    @Override
    public List<String> uploadFiles(MultipartFile[] files) {
        return null;
    }

    @Override
    public void downloadFile(HttpServletRequest request, HttpServletResponse response) {

    }
}

3. 配置文件

# 上传文件总的最大值
spring.servlet.multipart.max-request-size=10MB
# 单个文件的最大值
spring.servlet.multipart.max-file-size=10MB
#文件:
file.upload.path=D:/code/test/user/data/upload/
file.download.path=D:/code/test/user/data/download/

FastDFS相关,有机会补充

  • 1
    点赞
  • 0
    评论
  • 0
    收藏
  • 打赏
    打赏
  • 扫一扫,分享海报

参与评论 您还未登录,请先 登录 后发表或查看评论
<p> <span style=&quot;font-size:16px;color:#E53333;&quot;><strong>内容简介:</strong></span> </p> <p> <span style=&quot;font-size:16px;&quot;>本课程主要是从最基础的技术要点一步一个脚印的介绍Spring Boot2.0相关的核心技术栈,包括如何基于Spring Boot2.0搭建一个企业级的多模块项目、整合Spring MVC和Mybatis实现项目中功能模块的CRUD,校验器Validator、Lombok、动态配置参数、开发环境切换、全局异常处理、定时任务、多线程、热加载、发送邮件、上传下载文件、多数据源等核心干货,为各位小伙伴提供企业级项目开发中常见且典型的核心技术!</span> </p> <p> <br /> </p> <p> <span style=&quot;font-size:16px;color:#E53333;&quot;><strong>其课程大纲如下所示:</strong></span> </p> <p> <img src=&quot;https://img-bss.csdn.net/202004070546409819.jpg&quot; alt=&quot;&quot; /><span style=&quot;font-size:16px;&quot;></span> </p> <p> <br /> </p> <p> <br /> </p> <p> <br /> </p> <p> <br /> </p> <p> <br /> </p> <p> <span style=&quot;font-size:16px;&quot;>在课程的最后,我们介绍并实战了一个典型的应用场景:“<span style=&quot;font-size:16px;&quot;>用户注册</span>”,主要是将前面章节介绍的内容融入到一个完整的功能模块中,做到学以致用!</span><span style=&quot;font-size:16px;&quot;>其完整的功能流程图如下图所示:</span> </p> <p> <img src=&quot;https://img-bss.csdn.net/202004070548344015.png&quot; alt=&quot;&quot; /> </p> <p> <span style=&quot;font-size:16px;&quot;>基本要求:</span> </p> <span style=&quot;font-size:16px;&quot;></span> <p> <br /> </p> <p> <br /> </p> <p> <span style=&quot;font-size:16px;&quot;>1、</span><span style=&quot;font-size:16px;&quot;>基本要求:具备一定的</span><span style=&quot;font-size:16px;&quot;>JavaSE</span><span style=&quot;font-size:16px;&quot;>以及</span><span style=&quot;font-size:16px;&quot;>Java Web</span><span style=&quot;font-size:16px;&quot;>项目的开发基础、了解</span><span style=&quot;font-size:16px;&quot;>spring boot</span><span style=&quot;font-size:16px;&quot;>更佳</span><span></span> </p> <p> <span style=&quot;font-size:16px;&quot;>2、</span><span style=&quot;font-size:16px;&quot;>工具要求:会使用</span><span style=&quot;font-size:16px;&quot;>Intellij IDEA </span><span style=&quot;font-size:16px;&quot;>、</span><span style=&quot;font-size:16px;&quot;>Navicat </span><span style=&quot;font-size:16px;&quot;>以及</span><span style=&quot;font-size:16px;&quot;> Postman</span> </p>
©️2022 CSDN 皮肤主题:书香水墨 设计师:CSDN官方博客 返回首页

打赏作者

6Apricity6

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值