SpringBoot整合上传下载

准备HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>user</title>
</head>
<body>
    <h1>文件上传</h1>
    <form action="/user/upload" method="post" enctype="multipart/form-data">
        <label>账号</label><input type="text" name="username"><br/>
        <label>照片</label><input type="file" name="upload"><br/>
        <input type="submit" value="提交">
    </form>
    <h1><a href="/user/download">文件下载</a></h1>
</body>
</html>

controller

@RestController
public class UplaodController {
    //上传 注意:upload名称要和html input中name相同
    @RequestMapping("/user/upload")
    public String upload(MultipartFile upload, String username) throws IOException {
        System.out.println("username="+username+"----"+"upload="+upload.getOriginalFilename());
        upload.transferTo(new File("D:\\",upload.getOriginalFilename()));

        return "success";
    }

    //下载
    @RequestMapping("/user/download")
    public String download(HttpServletResponse req,HttpServletResponse resp){
        File file = new File("D:\\1.webp");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("multipart/form-data");
        resp.setHeader("Content-Disposition","attachment;filename=1.webp");
        FileInputStream in =null;
        ServletOutputStream out =null;
        try {
            in = new FileInputStream(file);
            out = resp.getOutputStream();
            byte [] b =new byte[1024];
            int len =0;
            while ((len=in.read(b))!= -1){
                out.write(b,0,len);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                in.close();
                out.close() ;
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return "success!!!";
    }
}

application.properties添加下面三个选项

spring.servlet.multipart.enabled=true
#设置单个文件总大小
spring.servlet.multipart.max-file-size=20MB
#一次上传文件的总大小
spring.servlet.multipart.max-request-size=20MB

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值