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;
    }
}

springboot文件上传和下载接口的简单思路_第1张图片
springboot文件上传和下载接口的简单思路_第2张图片

文件下载

文件下载的话,只需要在接口中传入文件的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地址的。(不过接口写的没问题哈)

你可能感兴趣的:(springboot随笔,spring,boot,后端,java)