SpringBoot 文件上传、下载、显示

1、代码实现 FileUtils

package com.microplay.util.file;

import com.microplay.util.dateTime.MPDateUtils;
import com.microplay.util.uuid.UuidUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

/**
 * 文件操作相关
 */
@Component
public class FileUtils {

    /**
     * 文件地址,按照年月日存储
     * <p>
     * filePath 文件上传路径
     * uploadFolder 文件夹名称
     */
    private static String filePath;
    private static String fileFolder = "uploadFolder";

    @Autowired
    private ResourceLoader resourceLoader;

    @Autowired
    private static ResourceLoader satticResourceLoader;

    @PostConstruct
    public void init() {
        satticResourceLoader = resourceLoader;
        try {
            filePath = new File("").getCanonicalPath() + "/" + fileFolder + "/";
        } catch (Exception e) {
            throw new RuntimeException("获取文件基本路径失败");
        }
    }

    /**
     * 文件上传 单个
     */
    public static String upload(MultipartFile file) {
        try {
            String fileName = file.getOriginalFilename();
            String suffix = fileName.split("\\.")[1];
            String newFileName = MPDateUtils.getYear() + "/" +
                    MPDateUtils.getMonth() + "/" +
                    MPDateUtils.getDay() + "/" +
                    UuidUtils.getUUID() + "." + suffix;
            String newPath = filePath + newFileName;
            // 判断当前文件夹是否存在
            File oldFile = new File(newPath);
            if (!oldFile.getParentFile().exists()) {
                oldFile.getParentFile().mkdirs();
            }
            File file2 = new File(newPath);
            file.transferTo(file2);
            return newFileName;
        } catch (IOException e) {
            throw new RuntimeException("文件上传失败");
        }
    }

    /**
     * 文件上传 多个
     */
    public static List<String> uploads(List<MultipartFile> files) {
        List<String> result = new ArrayList<>();
        for (MultipartFile file : files) {
            result.add(upload(file));
        }
        return result;
    }

    /**
     * 文件显示
     */
    public static ResponseEntity show(String fileName) {
        try {
            // 由于是读取本机的文件,file是一定要加上的, path是在application配置文件中的路径
            return ResponseEntity.ok(satticResourceLoader.getResource("file:" + filePath + fileName));
        } catch (Exception e) {
            return ResponseEntity.notFound().build();
        }
    }

    /**
     * 文件下载
     */
    public static void download(String fileName, HttpServletResponse response) {
        OutputStream toClient = null;
        try {
            // path是指欲下载的文件的路径。
            File file = new File(filePath + fileName);
            // 取得文件名。
            String filename = file.getName();
            // 取得文件的后缀名。
            String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();
            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(filePath + fileName));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 如果是图片就预览,不是图片就下载
            if (fileName.endsWith("jpg") || fileName.endsWith("png") || fileName.endsWith("gif")) {
                response.setHeader("Content-Type", "image/jpeg");
            } else {
                response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
                response.setContentType("application/octet-stream; charset=utf-8");

            }
            response.addHeader("Content-Length", "" + file.length());
            response.setHeader("Access-Control-Allow-Origin", "*");
            toClient = new BufferedOutputStream(response.getOutputStream());
            toClient.write(buffer);

        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            try {
                toClient.flush();
                toClient.close();
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("文件上传关闭流失败!");
            }
        }
    }

    /**
     * 文件删除
     *
     * @param fileName 文件路径
     * @return false、true
     */
    public static void delete(String fileName) {
        try {
            File file = new File(filePath + fileName);
            file.delete();
        } catch (Exception e) {
            throw new RuntimeException("文件删除失败");
        }
    }

    /**
     * 从网络中下载文件
     *
     * @param filePath 网络文件地址
     */
    public static void downloadByNetwork(HttpServletResponse response, String filePath) {
        InputStream inputStream = null;
        try {
            URL url = new URL(filePath);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            int httpRequestCode = con.getResponseCode();
            if (httpRequestCode != 200) {
                throw new Exception("文件下载错误,错误码:" + httpRequestCode);
            }
            // 将文件读入文件流
            inputStream = con.getInputStream();
            // 下载文件的名称
            String[] fileSplit = filePath.split("/");
            String finalFileName = fileSplit[fileSplit.length - 1];
            // 设置HTTP响应头
            // 重置 响应头
            response.reset();
            // 告知浏览器下载文件,而不是直接打开,浏览器默认为打开
            response.setContentType(URLConnection.getFileNameMap().getContentTypeFor(filePath));
            response.addHeader("Content-Disposition", "attachment;filename=" + finalFileName);
            // 循环取出流中的数据
            byte[] b = new byte[1024];
            int len;
            while ((len = inputStream.read(b)) > 0) {
                response.getOutputStream().write(b, 0, len);
            }

        } catch (Exception e) {
            throw new RuntimeException("从网络中下载文件失败");
        } finally {
            try {
                inputStream.close();
                response.getOutputStream().close();
            } catch (Exception e) {
                throw new RuntimeException("文件流关闭失败");
            }
        }
    }
}

2、控制层

package com.microplay.business.test.controller;

import com.microplay.config.jwt.JwtIgnore;
import com.microplay.util.file.FileUtils;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(value = "file", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class TestController {

    /**
     *
     * @param file
     * @return
     */
    @PostMapping("upload")
    @JwtIgnore
    public String upload(@RequestBody MultipartFile file) {
        return FileUtils.upload(file);
    }

    @PostMapping("uploads")
    @JwtIgnore
    public List<String> uploads(@RequestBody List<MultipartFile> files) {
        List<String> stringList = FileUtils.uploads(files);
        return stringList;
    }

    @PostMapping("delete")
    @JwtIgnore
    public void delete(String filePath) {
        FileUtils.delete(filePath);
    }

    @GetMapping("download")
    @JwtIgnore
    public void download(HttpServletResponse response, String filePath) {
        FileUtils.download(filePath, response);
    }

    /**
     * 显示单张图片
     * @return
     */
    @RequestMapping("show")
    @JwtIgnore
    public ResponseEntity shows(String filePath){
        return FileUtils.show(filePath);
    }

    /**
     * 下载网络资源
     * @param response
     * @param fileUrl
     * @return
     */
    @GetMapping("downloadByNetwork")
    @JwtIgnore
    public void downloadByNetwork(HttpServletResponse response, String fileUrl) {
        Map<String, String> params = new HashMap<String, String>();
        FileUtils.downloadByNetwork(response, fileUrl);
    }

}

3、视频讲解

https://www.bilibili.com/video/BV1kf4y1i761?p=7

 

上一篇:java给pdf添加水印


下一篇:IOS开发基础之单文件上传基础最原始的方式