springboot文件上传下载

1 文件上传

html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
    <input type="file" name="file" value="上传文件"><br>
    <input type="submit" value="提交">
</form>
</body>
</html>

controller

@RequestMapping("/upload")
@ResponseBody
public String upload(@RequestParam("file") MultipartFile file) throws IOException {
    String fileName = file.getOriginalFilename(); // 获取文件名
    String path = ClassUtils.getDefaultClassLoader().getResource("templates/").getPath(); // 获取项目绝对路径
    File dest = new File(path + fileName);
    if (!dest.exists()){ // 如果文件不存在则新建
        dest.mkdir();
    }
    file.transferTo(dest); // 将输入流输出到dest中
    return "ok";
}

2 文件下载

@RequestMapping("/download")
@ResponseBody
public String download(HttpServletResponse response) {
    String path = ClassUtils.getDefaultClassLoader().getResource("templates/").getPath();
    response.setContentType("application/force-download"); // 设置为强制下载
    response.addHeader("Content-Disposition", "attachment;fileName=hzj.sql"); // 设置下载的文件名
    FileInputStream inputStream = null;
    ServletOutputStream outputStream = null;
    try {
        inputStream = new FileInputStream(new File(path + "hzj.sql"));
        outputStream = response.getOutputStream();
        byte[] b = new byte[1024];
        while (inputStream.read(b) != -1){ // 从输入流读取byte并在输出流写出
            outputStream.write(b);
            outputStream.flush();
        }
    } catch (IOException e){
        e.printStackTrace();
    } finally {
        try {
            inputStream.close();
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return "ok";
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值