SpringBoot通过OSS实现文件上传和下载(包括本地文件的上传和下载)

本文介绍了Java面试中可能涉及的OSS(如阿里云OSS)操作,包括文件上传、下载、删除以及URL生成,同时概述了本地文件操作和Spring全家桶、Redis等相关知识。作者分享了面试经验,提醒读者做好准备和提升逻辑思维能力。
摘要由CSDN通过智能技术生成

《一线大厂Java面试题解析+核心总结学习笔记+最新讲解视频+实战项目源码》点击传送门,即可获取!
*/

public static String access_key_id;

/**

  • OSS秘钥(去OSS控制台获取)

*/

public static String access_key_secret;

/**

  • OSS桶名称(这个是自己创建bucket时候的命名)

*/

public static String bucket_name;

/**

  • OSS根目录

*/

public static String root_dir;

@PostConstruct

private void initial() {

file_client_type = fileClientType;

end_point = endPoint;

access_key_id = accessKeyId;

access_key_secret = accessKeySecret;

bucket_name = bucketName;

root_dir = rootDir;

}

}

4、文件工厂类

/**

  • 文件操作客户端生成类

  • @author zhangzhixiang

  • @data 2018/09/14 11:56:43

*/

public class ClientFactory {

private static final Logger logger = LoggerFactory.getLogger(ClientFactory.class);

/**

  • 根据类型获取文件操作客户端

  • @param type

  • @return

*/

public static FileClient createClientByType(String type) {

FileClient client = null;

switch (type) {

case “local”:

client = LocalClient.create();

break;

case “oss”:

client = OssClient.create();

break;

default:

client = null;

logger.info(“the type of fileClient does not exist.please check the type.type={}”, type);

break;

}

return client;

}

}

5、文件接口

/**

  • 本地文件操作类

  • @author zhangzhixiang

  • @data 2018/09/14 11:56:43

*/

public interface FileClient {

/**

  • 获取文件流

  • @author zhangzhixiang

  • @date 2018/10/17 10:59:43

  • @param code

  • @return java.io.InputStream

*/

InputStream getFileStream(String code);

/**

  • 上传文件

  • @param inputStream

  • @param filePath

  • @param ext

  • @author zhangzhixiang

  • @date 2018/10/17 10:59:43

  • @return boolean

*/

String upload(InputStream inputStream, String filePath, String ext) throws Exception;

/**

  • 下载文件

  • @param response

  • @param filePath

  • @param name

  • @author zhangzhixiang

  • @date 2018/10/17 10:59:43

  • @return void

*/

void download(HttpServletResponse response, String filePath, String name) throws Exception;

/**

  • 删除文件

  • @param dirPath

  • @author zhangzhixiang

  • @date 2018/10/17 10:59:43

  • @return void

*/

void delete(String dirPath);

/**

  • 获得url地址

  • @param key

  • @author zhangzhixiang

  • @date 2018/10/17 10:59:43

  • @return java.lang.String

*/

String getUrl(String key);

}

6、常量类定义

/**

  • @Description:简单常亮定义

  • @Author:zhangzhixiang

  • @CreateDate:2018/08/31 11:34:56

  • @Version:1.0

*/

public class SimpleConsts {

public static final Integer INPUT_BUFFER_SIZE = 8192;

}

7、OSS客户端配置

/**

  • @Description:OSS客户端配置

  • @Author:zhangzhixiang

  • @CreateDate:2018/08/31 11:34:56

  • @Version:1.0

*/

public class OssClient implements FileClient {

private static final Logger logger = LoggerFactory.getLogger(OssClient.class);

private final char PATH_SEPARATOR = System.getProperty(“file.separator”).toCharArray()[0];

private static OssClient ossClient;

/**

  • @Description:获取aliOSS对象

  • @Author:zhangzhixiang

*/

private OSS getClient() {

OSS ossClient = null;

try {

ossClient = new OSSClientBuilder().build(BootstrapConsts.end_point, BootstrapConsts.access_key_id, BootstrapConsts.access_key_secret);

} catch(Exception e){

logger.error(“OSSClient bean create error.”,e);

ossClient = null;

}

return ossClient;

}

/**

  • @Description:创建OssClient

  • @Author:zhangzhixiang

*/

public static FileClient create() {

if(null == ossClient) {

synchronized (logger) {

if(null == ossClient) {

ossClient = new OssClient();

}

}

}

return ossClient;

}

/**

  • @Description:根据code获取文件流

  • @Author:zhangzhixiang

*/

@Override

public InputStream getFileStream(String code) {

OSS aliOssClient = getClient();

OSSObject ossObject = aliOssClient.getObject(BootstrapConsts.bucket_name, BootstrapConsts.root_dir + PATH_SEPARATOR + code);

return ossObject.getObjectContent();

}

/**

  • @Description:上传文件

  • @Author:zhangzhixiang

*/

@Override

public String upload(InputStream inputStream, String code, String ext) {

OSS aliOssClient = getClient();

code = UUIDUtils.getUUID();

PutObjectResult putResult = aliOssClient.putObject(BootstrapConsts.bucket_name, BootstrapConsts.root_dir + PATH_SEPARATOR + code + ext, inputStream);

aliOssClient.shutdown();

return StringUtils.isNotEmpty(putResult.getETag()) ? BootstrapConstss.root_dir + PATH_SEPARATOR + code + ext : null;

}

/**

  • @Description:下载文件

  • @Author:zhangzhixiang

*/

@Override

public void download(HttpServletResponse response, String code, String name) {

OSS aliOssClient = getClient();

OSSObject ossObject = aliOssClient.getObject(BootstrapConsts.bucket_name, BootstrapConsts.root_dir + PATH_SEPARATOR + code);

try (InputStream fis = ossObject.getObjectContent(); OutputStream fos = response.getOutputStream(); BufferedOutputStream bos = new BufferedOutputStream(fos)) {

response.setContentType(“application/octet-stream; charset=UTF-8”);

response.setHeader(“Content-disposition”, “attachment;filename=” + new String(name.getBytes(“UTF-8”), “ISO-8859-1”));

int bytesRead = 0;

byte[] buffer = new byte[SimpleConsts.INPUT_BUFFER_SIZE];

while((bytesRead = fis.read(buffer, 0, SimpleConsts.INPUT_BUFFER_SIZE)) != -1) {

bos.write(buffer, 0, bytesRead);

}

bos.flush();

} catch (Exception e){

logger.error(“OssClient–>download throw Exception.name:{},code:{}”, name, code, e);

}

aliOssClient.shutdown();

}

/**

  • @Description:删除文件

  • @Author:zhangzhixiang

*/

@Override

public void delete(String code) {

OSS aliOssClient = getClient();

boolean flag = aliOssClient.doesObjectExist(BootstrapConsts.bucket_name, code);

if(false == flag) {

logger.info(“The object represented by key:{} does not exist in bucket:{}.”, code, BootstrapConsts.bucket_name);

}

aliOssClient.deleteObject(BootstrapConsts.bucket_name, code);

}

/**

  • @Description:获取文件地址

  • @Author:zhangzhixiang

*/

@Override

public String getUrl(String code) {

OSS aliOssClient = getClient();

//设置URL过期时间为10年

Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 10);

//生成URL

URL url = aliOssClient.generatePresignedUrl(BootstrapConsts.bucket_name, code, expiration);

if(url != null) {

return url.toString();

}

return null;

}

/**

  • @Description:生成文件名

  • @Author:zhangzhixiang

*/

private String createFileName(String ext) {

SimpleDateFormat simpleDateFormat = new SimpleDateFormat(“yyyyMMddHHmmss”);

return simpleDateFormat .format(new Date()) + (int)(Math.random() * 900 + 100) + ext;

}

/**

  • @Description:生成OSS文件唯一标识

  • @Author:zhangzhixiang

*/

private String generateKey(String filename) {

StringBuffer buffer = new StringBuffer();

try {

buffer.append(filename);

buffer.append(Math.random());

return EncodeUtil.encodeFromMD5ToBase64(buffer.toString());

} catch(NoSuchAlgorithmException e) {

e.printStackTrace();

} catch(UnsupportedEncodingException e) {

e.printStackTrace();

}

return null;

}

}

8、UUIDUtils类

/**

  • @author zxzhang on 2020/8/1

*/

public class UUIDUtils {

/**

  • 32位默认长度的uuid

  • @param

  • @return java.lang.String

  • @author zxzhang

  • @date 2020/8/1

*/

public static String getUUID() {

return UUID.randomUUID().toString().replace(“-”, “”);

}

/**

  • 获取指定长度uuid

  • @param len

  • @return java.lang.String

  • @author zxzhang

  • @date 2020/8/1

*/

public static String getUUID(int len) {

if (0 >= len) {

return null;

}

String uuid = getUUID();

System.out.println(uuid);

StringBuffer str = new StringBuffer();

for (int i = 0; i < len; i++) {

str.append(uuid.charAt(i));

}

return str.toString();

}

}

9、本地客户端配置

/**

  • @Description:本地客户端配置

  • @Author:zhangzhixiang

  • @CreateDate:2018/10/18 11:47:36

  • @Version:1.0

*/

public class LocalClient implements FileClient {

private static final Logger logger = LoggerFactory.getLogger(LocalClient.class);

private final char PATH_SEPARATOR = System.getProperty(“file.separator”).toCharArray()[0];

private static LocalClient client;

private LocalClient() {}

/**

  • @Description:创建客户端

  • @Author:zhangzhixiang

*/

public static FileClient create() {

if(null == client) {

synchronized (logger) {

if(null == client) {

if(null == client) {

client = new LocalClient();

}

}

}

}

return client;

}

/**

  • @Description:获得文件流

  • @Author:zhangzhixiang

*/

@Override

public InputStream getFileStream(String code) {

return null;

}

/**

  • @Description:上传文件

  • @Author:zhangzhixiang

*/

@Override

public String upload(InputStream inputStream, String filePath, String ext) throws Exception {

File dir = new File(filePath);

FileOutputStream out = null;

try {

if(!dir.exists()) {

dir.mkdirs();

}

filePath = filePath + PATH_SEPARATOR + createFileName(ext);

File file = new File(filePath);

out = new FileOutputStream(file);

int b = 0;

byte[] buffer = new byte[512];

while ((b = inputStream.read(buffer)) != -1) {

out.write(buffer, 0, b);

}

out.flush();

return filePath;

} catch (IOException e) {

logger.info(“LocalClient–>upload throw Exception.filePath:{}”, filePath);

throw e;

} finally {

if(out != null) {

out.close();

}

if(inputStream != null) {

inputStream.close();

}

最后总结我的面试经验

2021年的金三银四一眨眼就到了,对于很多人来说是跳槽的好机会,大厂面试远没有我们想的那么困难,摆好心态,做好准备,你也可以的。

另外,面试中遇到不会的问题不妨尝试讲讲自己的思路,因为有些问题不是考察我们的编程能力,而是逻辑思维表达能力;最后平时要进行自我分析与评价,做好职业规划,不断摸索,提高自己的编程能力和抽象思维能力。

BAT面试经验

实战系列:Spring全家桶+Redis等

其他相关的电子书:源码+调优

面试真题:


《一线大厂Java面试题解析+核心总结学习笔记+最新讲解视频+实战项目源码》点击传送门,即可获取!
lePath;

} catch (IOException e) {

logger.info(“LocalClient–>upload throw Exception.filePath:{}”, filePath);

throw e;

} finally {

if(out != null) {

out.close();

}

if(inputStream != null) {

inputStream.close();

}

最后总结我的面试经验

2021年的金三银四一眨眼就到了,对于很多人来说是跳槽的好机会,大厂面试远没有我们想的那么困难,摆好心态,做好准备,你也可以的。

另外,面试中遇到不会的问题不妨尝试讲讲自己的思路,因为有些问题不是考察我们的编程能力,而是逻辑思维表达能力;最后平时要进行自我分析与评价,做好职业规划,不断摸索,提高自己的编程能力和抽象思维能力。

[外链图片转存中…(img-8K72DMjH-1714759076025)]

BAT面试经验

实战系列:Spring全家桶+Redis等

[外链图片转存中…(img-fj4KrbXU-1714759076026)]

其他相关的电子书:源码+调优

[外链图片转存中…(img-6ycM7cXC-1714759076026)]

面试真题:

[外链图片转存中…(img-hIpFlIt4-1714759076026)]

[外链图片转存中…(img-QePKxm4P-1714759076026)]
《一线大厂Java面试题解析+核心总结学习笔记+最新讲解视频+实战项目源码》点击传送门,即可获取!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值