SpringBoot:上传下载资源实现

文件工具类FileUtils

public class FileUtils{
    
    

	//Content-disposition 设置
    public static void setAttaResHeader(HttpServletResponse response, String realFileName) throws UnsupportedEncodingException {
    
    
        String percentEncodedFileName = percentEncode(realFileName);

        StringBuilder contentDispositionValue = new StringBuilder();
        contentDispositionValue.append("attachment; filename=")
                .append(percentEncodedFileName)
                .append(";")
                .append("filename*=")
                .append("utf-8''")
                .append(percentEncodedFileName);

        response.setHeader("Content-disposition", contentDispositionValue.toString());
    }

 	 //URI 百分号编码
    public static String percentEncode(String str) throws UnsupportedEncodingException {
    
    
        String encode = URLEncoder.encode(str, StandardCharsets.UTF_8.toString());
        return encode.replaceAll("\\+", "%20");
    }
	
	//编码文件名
	private final String getCodeFileName(MultipartFile file) {
    
    
        String suffix = getExtension(file);
        Date date = new Date();
        String fileName = DateFormatUtils.format(date, "yyyy/MM/dd") + "/" + IdUtils.fastUUID() + "." + suffix;
        return fileName;
    }

	//获取完整路径
	private final String getPathFileName(String uploadDir, String fileName) throws IOException {
    
    
        int dirLastIndex = sysConfig.getProfile().length() + 1;
        String currDir = uploadDir.substring(dirLastIndex);
        String pathFileName = Constants.RESOURCE_PREFIX + "/" + currDir + "/" + fileName;
        return pathFileName;
    }
	
	//拿到绝对路径
	private final File getAbsoluteFile(String uploadDir, String fileName) throws IOException {
    
    
        File desc = new File(uploadDir + File.separator + fileName);

        if (!desc.exists()) {
    
    
            if (!desc.getParentFile().exists()) {
    
    
                desc.getParentFile().mkdirs();
            }
        }
        return desc;
    }
	
	//上传文件
	public String upload(String baseDir, MultipartFile file) throws IOException {
    
    
        String fileName = getCodeFileName(file);
        File desc = getAbsoluteFile(baseDir, fileName);
        file.transferTo(desc);
        return getPathFileName(baseDir, fileName);
    }
	
	//输出文件
	public static void writeBytes(String filePath, OutputStream os) throws IOException {
    
    
        FileInputStream fis = null;
        try {
    
    
            File file = new File(filePath);
            if (!file.exists()) {
    
    
                throw new FileNotFoundException(filePath);
            }
            fis = new FileInputStream(file);
            byte[] b = new byte[1024];
            int length;
            while ((length = fis.read(b)) > 0) {
    
    
                os.write(b, 0, length);
            }
        } catch (IOException e) {
    
    
            throw e;
        } finally {
    
    
            if (os != null) {
    
    
                try {
    
    
                    os.close();
                } catch (IOException e1) {
    
    
                    e1.printStackTrace();
                }
            }
            if (fis != null) {
    
    
                try {
    
    
                    fis.close();
                } catch (IOException e1) {
    
    
                    e1.printStackTrace();
                }
            }
        }
    }

}

服务配置类ServerConfig

@Component
public class ServerConfig {
    
    
    
    //获取完整url
    public String getUrl() {
    
    
        HttpServletRequest request = ServletUtils.getRequest();
        StringBuffer url = request.getRequestURL();
        String contextPath = request.getServletContext().getContextPath();
        return url.delete(url.length() - request.getRequestURI().length(), url.length()).append(contextPath).toString();
    }
    
}

客户端工具类ServletUtils

public class ServletUtils {
    
    

	public static ServletRequestAttributes getRequestAttributes() {
    
    
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        return (ServletRequestAttributes) attributes;
    }
	
	//获取request
    public static HttpServletRequest getRequest() {
    
    
        return getRequestAttributes().getRequest();
    }
	
	

返回状态类 Result

public class Result extends HashMap<String, Object> {
    
    

    //状态码
    public static final String CODE_TAG = "code";

    //返回信息
    public static final String MSG_TAG = "msg";

    //数据对象
    public static final String DATA_TAG = "data";


    public Result() {
    
    
    }


    public Result(int code, String msg) {
    
    
        super.put(CODE_TAG, code);
        super.put(MSG_TAG, msg);
    }


    public Result(int code, String msg, Object data) {
    
    
        super.put(CODE_TAG, code);
        super.put(MSG_TAG, msg);
        if (StringUtils.isNotNull(data)) {
    
    
            super.put(DATA_TAG, data);
        }
    }


    public static Result success() {
    
    
        return Result.success("操作成功");
    }


    public static Result success(Object data) {
    
    
        return Result.success("操作成功", data);
    }

    
    public static Result success(String msg) {
    
    
        return Result.success(msg, null);
    }


    public static Result success(String msg, Object data) {
    
    
        return new Result(200, msg, data);
    }


    public static Result error() {
    
    
        return Result.error("操作失败");
    }


    public static Result error(String msg) {
    
    
        return Result.error(msg, null);
    }


    public static Result error(String msg, Object data) {
    
    
        return new Result(500, msg, data);
    }

    public static Result error(int code, String msg) {
    
    
        return new Result(code, msg, null);
    }
    
}

资源请求类ResourceReqController

@RestController
public class ResourceReqController{
    
    

    private static final Logger log = LoggerFactory.getLogger(ResourceReqController.class);

    @Autowired
    private ServerConfig serverConfig;


    @GetMapping("/common/download")
    public void fileDownload(String fileName, HttpServletResponse response, HttpServletRequest request) {
    
    
        try {
    
    
            // 做一些文件校验 例如文件名校验
            //TO DO throw new Exception();

            //定义文件名
            String realFileName = System.currentTimeMillis() + fileName;
            //下载路径
            String filePath = sysConfig.getDownloadPath() + fileName;
            //设置Content-Type 二进制流
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            //响应头设置
            FileUtils.setAttaResHeader(response, realFileName);
            //输出文件
            FileUtils.writeBytes(filePath, response.getOutputStream());
        } catch (Exception e) {
    
    
            log.error("下载文件失败", e);
        }
    }

    /**
     * 通用上传请求
     */
    @PostMapping("/common/upload")
    public Result uploadFile(MultipartFile file) throws Exception {
    
    
        try {
    
    
        	// 做一些文件校验 例如文件名长度、文件名类型校验
            //TO DO throw new Exception();
            
            // 上传文件路径 
            String filePath = sysConfig.getUploadPath();
            // 上传文件
            String fileName = FileUtils.upload(filePath, file);
           
            String url = serverConfig.getUrl() + fileName;
            Result res = Result.success();
            res.put("fileName", fileName);
            res.put("url", url);
            return res;
        } catch (Exception e) {
    
    
            return Result.error(e.getMessage());
        }
    }

}

猜你喜欢

转载自blog.csdn.net/MAKEJAVAMAN/article/details/119854071