Spring Boot--文件上传和下载

文件上传和下载

前言

文件上传是指本地图片、视频、音频等文件上传到服务器上,可以供其他用户浏览和下载的过程

文件上传的前提调节:

必须将file的流以formdata的形式传参,并且必须以post请求提交

文件上传

1、以MultipartFile 接口流文件,流的名称需要和前台传过来的名称对应上

2、获取到文件名称截取后缀

3、为了放置文件名重复使用uuid来随机生成id+后缀

4、判断转存路径中是否有这个文件夹如果没有就创建

5、将文件存储到转存的目录中

文件下载

1、通过输入流获取到文件

2、通过输出流输出文件

3、判断文件读取是否完成,如果为-1就是读取完成

4、读取陈工后写入到输出流并返回

5、关闭资源

java 复制代码
package com.example.ruiji_demo.controller;

import com.example.ruiji_demo.common.R;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * @author jitwxs
 * @date 2024年04月03日 18:17
 */
@Slf4j
@RestController
@RequestMapping("/common")
public class CommponContreller {
//    获取转存的地址
    @Value("${reggie.path}")
    private String basePath;

//    定义上传文件的接口
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file){
        String originalFilename = file.getOriginalFilename();
//        截取后缀
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

//        使用uuid重新生成文件名,放置文件名称重复
        String filName = UUID.randomUUID().toString()+suffix;

//        判断目录是否存在如果不存在就创建目录
        File dir = new File(basePath);
        if(!dir.exists()){
            dir.mkdir();
        }
        try {
//            将临时文件转存到指定位置
            file.transferTo(new File(basePath+filName));
        } catch (IOException e){
            e.printStackTrace();
        }
        return R.success("上传成功");
    }

//    定义下载接口
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response){
        try{
//            输入流,通过输入流读取文件内容
            FileInputStream fileInputstream = new FileInputStream(new File(basePath+name));
//            输出流,通过输出流将文件写入浏览器,在浏览器中展示图片
            ServletOutputStream outputStream = response.getOutputStream();

//            返回的文件格式
//            response.setContentType("image/jpeg");
//            判断文件的长度
            int len = 0;
            byte[] bytes = new byte[1024];
            while((len = fileInputstream.read(bytes)) != -1){
                outputStream.write(bytes,0,len);
                outputStream.flush();
            }

//            关闭资源
            outputStream.close();
            fileInputstream.close();

        }catch(Exception e){
            e.printStackTrace();
        }
    }

}
相关推荐
殷色玫瑰11 分钟前
C/C++ 内存管理详解:从内存分布到 new/delete 底层原理
java·linux·c语言·c++
code_slave(码畜)24 分钟前
微服务架构落地:基础服务 —— 报表服务(中篇:元数据、查询引擎、缓存与权限落地)
spring boot·spring cloud·缓存·微服务·架构
ZealSinger1 小时前
Boot4挂起函数丢traceId怎么修
spring boot·kotlin·协程·可观测性
IT_陈寒1 小时前
SpringBoot自动配置坑了我一把,原来是这样绕过去的
前端·人工智能·后端
青山木1 小时前
Hot 100 --- 编辑距离
java·数据结构·算法·leetcode·动态规划
朝朝辞暮i1 小时前
C++ 第 26 课:对象、指针与 ->
java·开发语言·c++
code_slave(码畜)2 小时前
微服务架构落地:基础服务 —— 报表服务(AI 集成篇:AI 增强报表能力)
人工智能·spring boot·spring cloud·微服务·架构
长弓三石2 小时前
把 AgentScope Harness 装进 RuoYi-Vue-Plus:纯 Java AI 平台的集成实践
java·人工智能·agent
要努力啊4692 小时前
用 Codex 加速 Java 开发:从代码生成到测试覆盖的完整实战
后端
dora2 小时前
LangChain4j 新手入门实战教程(Java版)
后端·langchain·agent