springboot上传下载

文件上传

1.创建提交表单

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>文件上传</h1>
<form action="/user/upload" method="post" enctype="multipart/form-data">
    <label>账号:</label><input type="text" name="username">
    <label>照片:</label><input type="file" name="upload">
    <input type="submit" value="提交">
</form>
</body>
</html>
  • 添加控制器处理上传的文件信息
@RestController
@RequestMapping("user")
public class UserContorller {
    @RequestMapping("upload")
    public String upolad(MultipartFile upload, String username) throws IOException {
        System.out.println("username" + username + "文件名称" +upload.getOriginalFilename());
        upload.transferTo(new File("d:/",upload.getOriginalFilename()));
        return "success..";
    }
}

2.配置相关的上传参数

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

文件下载

1.页面提供下载按钮

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

2.服务端处理下载请求

 @RequestMapping("download")
    public void  downloadFile(HttpServletRequest request , HttpServletResponse response) {
        File file = new File("D:\\Documents\\1.jpg");
        //设置响应头和客户端保存文件名
        response.setCharacterEncoding("UTF-8");
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition", "attachment; filename=" + file.getName());
        FileInputStream in = null;
        ServletOutputStream out = null;
        try {
            //文件复制
             in = new FileInputStream(file);
             out = response.getOutputStream();
            byte[] b = new byte[1024];
            int lenth = 0;
            while ((lenth = in.read(b)) >0){
                out.write(b,0,lenth);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                out.flush();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值