Spring Boot搭建文件上传和下载接口

点我查看视频教程

文件上传和下载接口

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.WritableByteChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @Author Da
 * @Description: 三十年生死两茫茫,写程序,到天亮。
 * 千行代码,Bug何处藏。
 * 纵使上线又怎样,朝令改,夕断肠。
 * 领导每天新想法,天天改,日日忙。
 * 相顾无言,惟有泪千行。
 * 每晚灯火阑珊处,夜难寐,又加班。
 * @Date 2022/3/24 13:48
 */
@Slf4j
@RequestMapping("/file")
@RestController
public class FileController {

    @PostMapping("/upload")
    public String upload(MultipartFile file) throws IOException {

        log.warn("file => {}", file);

//        获取上传文件的名字
        final String filename = file.getOriginalFilename();
//        获取存放文件的位置
        final Path rootPath = Paths.get(System.getProperty("user.dir") + File.separator + "files");
//        不存在就创建
        if (!Files.exists(rootPath)) {
            Files.createDirectory(rootPath);
            System.out.println("创建" + rootPath.toString());
        }
//        文件保存的位置
        final Path path = Paths.get(rootPath.toString() + File.separator + filename);
//        写入内容到指定位置
        file.transferTo(path);
        return filename;
    }


    @GetMapping("/{fileName}")
    public void download(@PathVariable String fileName, HttpServletResponse response) throws IOException {
        final Path path = Paths.get(System.getProperty("user.dir") + File.separator + "files" + File.separator + fileName);
//        设置响应头
        response.setContentType("application/octet-stream");
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
//        获取输出流
        final WritableByteChannel writableByteChannel = Channels.newChannel(response.getOutputStream());
//        读取文件流通道
        final FileChannel fileChannel = new FileInputStream(path.toFile()).getChannel();
//        写入数据到通道
        fileChannel.transferTo(0, fileChannel.size(), writableByteChannel);
        fileChannel.close();
        writableByteChannel.close();
    }

}

测试上传

<form action="/file/upload" method="post" enctype="multipart/form-data">
    <input type="file" name="file"/>
    <input type="submit" value="上传">
</form>

下载就直接使用localhost:你的端口/file/要下载的文件名字

  • 9
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值