springboot 文件上传与下载

接触springboot不多,实验下附件上传与下载,记录下。

1 文件的多上传

JSP页面:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>上传文件</title>
</head>
<body>
    <form action="${pageContext.request.contextPath}/uploadFile" method="post" enctype="multipart/form-data">
        <input type="file" name="fileTest"/>
        <input type="file" name="fileTest"/>
        <input type="submit" value="上传"/>
    </form>
</body>
</html>

Java代码:

    /**
     * 文件上传
     */
    @RequestMapping("/uploadFile")
    public String uploadFile(@RequestParam("fileTest") MultipartFile[] multipartFiles, HttpServletRequest request) throws IOException {
        String realPath = request.getSession().getServletContext().getRealPath("/upload");
        if(null != multipartFiles && multipartFiles.length > 0){
            for(MultipartFile file : multipartFiles){
                //获取文件的原始名
                String fileName = file.getOriginalFilename();
                if(StringUtils.isNotBlank(fileName)){
                    System.out.println(fileName);
                    //根据相对路径获取绝对路径
                    file.transferTo(new File(realPath,fileName));

                    //将文件路径信息保存到数据库
                    fileMapper.upFile(realPath,fileName);
                }
            }
        }
        return "success";
    }

文件上传到的目录:

2 文件的下载

Jsp页面:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>下载页面</title>
</head>
<body>
<a href="${pageContext.request.contextPath}/downFile?fileName=报表宏备份.txt">报表宏备份.txt</a>
</body>
</html>

Java代码:

    /**
     * 文件下载
     */
    @RequestMapping("/downFile")
    public void downFile(String fileName, HttpServletRequest request, HttpServletResponse response) throws Exception {
        //获取文件的绝对路径
        String realPath = request.getSession().getServletContext().getRealPath("upload");
        //获取输入流对象
        FileInputStream fis = new FileInputStream(new File(realPath,fileName));
        //获取文件后缀
        String extendFileName = fileName.substring(fileName.lastIndexOf("."));
        //动态设置相应类型,根据前台文件类型设置响应类型
        response.setContentType(request.getSession().getServletContext().getMimeType(extendFileName));
        //设置响应头,attachment表示以附件形式下载,inline表示在线打开
        response.setHeader("content-disposition","attachment;fileName="+ URLEncoder.encode(fileName,"UTF-8"));
        //获取输出流对象
        ServletOutputStream os = response.getOutputStream();
        //下载文件,使用spring框架中的FileCopyUtils工具
        FileCopyUtils.copy(fis,os);
    }

演示界面:

下载成功。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值