springboot实现文件上传下载功能

本人在学习SpringBoot时,看到一篇关于文件上传下载功能的实现的博客。这里记录一下在Springboot中实现文件上传下载的核心代码

package com.file.demo.springbootfile;

import com.file.util.ResultUtil;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.apache.tomcat.util.http.fileupload.util.Streams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
/*
* springboot整合vue,文件上传下载
* */
//上传不要用@Controller,用@RestController
@RestController
@RequestMapping("/file")
public class FileController {
    private static final Logger logger = LoggerFactory.getLogger(FileController.class);
    //在文件中,不用/或者\最好,推荐使用File.separator
    private final static String fileDir="files";
    private final static String rootPath = System.getProperty("user.home")+ File.separator+fileDir+File.separator;

    /*
    * 文件上传
    * */
    @RequestMapping("/upload")
    public Object uploadFile(@RequestParam("file")MultipartFile[] multipartFiles, final HttpServletResponse response, final HttpServletRequest request){
        File fileDir = new File(rootPath);
        /*
        * exists():测试此抽象路径名表示的文件是否存在
        * isDirectory():检查一个对象是否是文件夹
        * isFile():判断是否为文件,也可能是文件目录
        * */
        if(!fileDir.exists() && !fileDir.isDirectory()){
            //检查到文件不存在则创建
            fileDir.mkdir();//创建文件,一级
            fileDir.mkdirs();//创建多级
        }
        try{
            if(multipartFiles != null  && multipartFiles.length > 0){
                for ( int i = 0;i<multipartFiles.length;i++){
                    try{
                        String storagePath = rootPath+multipartFiles[i].getOriginalFilename();
                        logger.info("上传的文件:" + multipartFiles[i].getName()+","+multipartFiles[i].getContentType()+","
                                +multipartFiles[i].getOriginalFilename() + ",保持的路径为:" + storagePath);
                        Streams.copy(multipartFiles[i].getInputStream(), new FileOutputStream(storagePath), true);
                    }catch (IOException e){
                        logger.info(ExceptionUtils.getFullStackTrace(e));
                    }
                }
            }
        }catch (Exception e){
            return ResultUtil.error(e.getMessage());
        }
        return ResultUtil.success("上传成功!");
    }


    /*
    * 文件下载
    * */
    @RequestMapping("/download")
    public Object downkiadFile(@RequestParam String fileName,final HttpServletResponse response,final HttpServletRequest request){
        OutputStream os = null;
        InputStream is = null;
        try{
            //获取输出流rootPath
            os = response.getOutputStream();
            //重置输出流
            response.reset();
            response.setContentType("application/x-download;charset=GBK");
            response.setHeader("Content-Disposition", "attachment;filename="+ new String(fileName.getBytes("utf-8"), "iso-8859-1"));

            //读取流
            File f= new File(rootPath+fileName);
            is = new FileInputStream(f);
            if(is == null){
                logger.error("下载文件失败,请检查文件“"+ fileName +"”是否存在");
                return ResultUtil.error("下载附件失败,请检查文件“" + fileName + "”是否存在");
            }
            //复制文件
            IOUtils.copy(is,response.getOutputStream());
            //刷新缓冲
            response.getOutputStream().flush();
        }catch (IOException e){
            return ResultUtil.error("下载文件失败,error:" + e.getMessage());
        }
        //文件的关闭在finally中执行
        finally {
            {
                try {
                    if(is != null){
                        is.close();
                    }
                }catch (IOException e){
                    logger.error(ExceptionUtils.getFullStackTrace(e));
                }
                try{
                    if(os != null){
                        os.close();
                    }
                }catch (IOException e){
                    logger.info(ExceptionUtils.getFullStackTrace(e));
                }
            }
        }
        return null;
    }
}

源码下载地址: https://github.com/struggle0903/SpringBootfiledemo.git

文章来自:https://www.cnblogs.com/Struggle-xh/p/11124181.html

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值