springboot文件上传和下载接口的简单思路

springboot文件上传和下载的简单思路

文件上传

在springboot中,上传文件只需要在接口中通过 MultipartFile 对象来获取前端传递的数据,然后将数据存储,并且返回一个对外访问路径即可。一般对于上传文件的文件名,都要通过uuid进行处理。

@RestController
@RequestMapping("/file")
public class FileController {

	// 服务器存储位置
    private static  String parentPath = "D:\\IdeaProjects\\demoZ\\src\\main\\resources\\static\\";

    // 上传接口
    @RequestMapping("/upload")
    public String uploadFile(@RequestParam MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename(); // 获取文件名
        String type = file.getContentType(); // 获取文件类型
        long size = file.getSize(); // 获取文件大小
        // 这里只对一种类型进行了简单判断,可以自行修改
        if ("image/jpeg".equals(type)){
            type = ".jpg";
        }
        // 构建uuid作为唯一标识
        String uuid = UUID.randomUUID().toString()+type;
        File uploadFile = new File(parentPath+uuid);
        // 判断父级目录是否存在,不存在则创建
        File parentFile = uploadFile.getParentFile();
        if(!parentFile.exists()){
            parentFile.mkdirs();
        }
        // 文件存储到磁盘上
        file.transferTo(uploadFile);
        // 返回对外访问路径
        return "http://localhost:9090/file/"+uuid;
    }
}

在这里插入图片描述
在这里插入图片描述

文件下载

文件下载的话,只需要在接口中传入文件的uuid名称,然后通过流的方式直接输出即可。

@RestController
@RequestMapping("/file")
public class FileController {


    private static  String parentPath = "D:\\IdeaProjects\\demoZ\\src\\main\\resources\\static\\";

	// 文件上传接口....


	// 文件下载接口
    @RequestMapping("/{uuid}")
    public void download(@PathVariable String uuid, HttpServletResponse response) throws IOException {
        // 通过response将数据输出
        // 根据文件的唯一标识码获取文件
        File uploadFile = new File(parentPath+uuid);
        // 设置输出流的格式
        ServletOutputStream os = response.getOutputStream();
        response.addHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(uuid,"UTF-8"));
        response.setContentType("application/octet-stream");
		// 创建文件输入流
        FileInputStream fis = new FileInputStream(uploadFile);

        // 读取文件的字节流
        byte[] buf = new byte[1024];
        int readLen = 0;
        while ((readLen=fis.read(buf))!=-1){
            // 边读边写
            os.write(buf,0,readLen);
        }

        os.flush();
        os.close();
    }
}

tips:通过文件上传的返回值即可测试下载接口 http://localhost:9090/file/59038923-ea78-40df-970e-70f49dc966b3.jpg

这里的话,为了简单就只写了后端的文件上传和下载,没有涉及到数据库的文件信息存储,正常情况下是根据你文件的唯一标识去获取下载这张图片的url地址的。(不过接口写的没问题哈)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

杀死一只知更鸟debug

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值