背景:目前各个公司常用的静态文件服务器是OSS,不管是哪一家云厂商,都会有OSS资源服务提供,在项目中通常会议基础组件的形式存在,很少人会关注,下面就以阿里云为例来介绍一下OSS的使用。
1,引入OSS插件
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.8.0</version>
</dependency>
2,使用OSS上传文件
package com.aaa.store.utils;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.UUID;import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.util.UriUtils;import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;import lombok.extern.slf4j.Slf4j;
/**
* 阿里云OSS工具类
*/
@Slf4j
public class OSSClientUtils {
/**
* bucket中的文件夹,存放销售出库导入文件相关资源
*/
public static String IMEI_DIR = "imei";/**
* bucket中的文件夹,存放其他中相关资源
*/
public static String OTHER_DIR = "other/";/**
* 暂存文件的路径
*/
public static String TEMP_PATH = "tmp/";/**
* 通用文件的路径
*/
public static String COMMON_PATH = "common/";/**
* bucket中的文件夹,存放人脸相关资源
*/
public static String FACE_DIR = "face";/**
* bucket中的文件夹,存放店铺相关资源
*/
public static String SHOP_DIR = "shop";/**
* bucket中的文件夹,存放样机相关资源
*/
public static String DEMO_MODEL_DIR = "demoModel";
/**
* bucket中的文件夹,存放资产相关资源
*/
public static String ASSET_DIR = "asset";/**
* bucket中的文件夹,存放销量上报发票相关资源
*/
public static String RECEIPT_DIR = "receipt";
/**
* bucket中的文件夹,存放印度国包发票相关资源
*/
public static String INVOICE_DIR = "invoice";/**
* 客户管理
*/
public static String CUSTOMER_DIR = "customer";
/**
* bucket中的文件夹,存放Banner相关资源
*/
public static String BANNER_DIR = "banner";
/**
* bucket中的文件夹,存放FTP相关资源
*/
public static String FTP_DIR = "ftp";private final static String DEFAULT_CHARSET = "utf-8";
private final static int DEFAULT_TIME_OUT = 60000;/**
* 上传文件到OSS
* @param file
* @param ossClient
* @param bucketName
* @param bucketDirName
* @return
* @throws Exception
*/
public static String uploadFile2Oss(MultipartFile file,OSSClient ossClient,String bucketName,String bucketDirName) throws Exception {
String originalFileName = file.getOriginalFilename();
String fileName = UUID.randomUUID()+originalFileName.substring(originalFileName.lastIndexOf("."),originalFileName.length());
try {
InputStream inputStream = file.getInputStream();
String dirName = getBucketDirName(bucketDirName);
return uploadStream2OSS(inputStream,ossClient,bucketName,dirName,fileName);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}/**
* 上传到OSS服务器 如果同名文件会覆盖服务器上的
* @param instream 文件流
* @param ossClient
* @param bucketName
* @param dirName
* @param fileName
* @return
*/
public static String uploadStream2OSS(InputStream instream,OSSClient ossClient,String bucketName, String dirName,String fileName) {
try {
log.info("===== enter uploadStream2OSS, fileName:" + fileName);
String file = URLEncoder.encode(fileName, "UTF-8");
//创建上传Object的Metadata
ObjectMetadata objectMetadata = new ObjectMetadata();
objectMetadata.setContentLength(instream.available());
objectMetadata.setCacheControl("no-cache");
objectMetadata.setHeader("Pragma", "no-cache");
objectMetadata.setHeader("Content-Disposition", "filename*=utf-8''" + file);
objectMetadata.setContentType(getContentType(fileName.substring(fileName.lastIndexOf(".") + 1)));
objectMetadata.setContentDisposition("attachment;filename*=utf-8''" + file);
objectMetadata.setContentEncoding(StandardCharsets.UTF_8.name());
//上传文件
String key = dirName + fileName;
ossClient.putObject(bucketName, key, instream, objectMetadata);
return getUrl(key, ossClient, bucketName);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (instream != null) {
instream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}public static String getBucketDirName(String bucketDirName){
SimpleDateFormat sdf = new SimpleDateFormat("yyMM");
return bucketDirName+"/"+sdf.format(new Date())+"/";
}/**
* Description: 判断OSS服务文件上传时文件的contentType
* @param filenameExtension 文件后缀
* @return String
*/
public static String getContentType(String filenameExtension) {
String contentType = "";
switch(filenameExtension.toUpperCase()) {
case "BMP": contentType = "image/bmp";break;
case "GIF": contentType = "image/gif";break;
case "JPEG":
case "JPG":
contentType = "image/jpg";
break;
case "PNG": contentType = "image/png";break;
case "HTML": contentType = "text/html";break;
case "TXT": contentType = "text/plain";break;
case "VSD": contentType = "application/vnd.visio";break;
case "PPTX":
case "PPT": contentType = "application/vnd.ms-powerpoint";break;
case "DOCX": contentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";break;
case "DOC": contentType = "application/msword";break;
case "XLSX": contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";break;
case "XLS": contentType = "application/vnd.ms-excel";break;
case "XML": contentType = "text/xml";break;
case "PDF": contentType = "application/pdf";break;
default:contentType="file";
}
return contentType;
}/**
* 获得url链接
* @param key
* @return
*/
public static String getUrl(String key,OSSClient ossClient,String bucketName) {
// 设置URL过期时间为50年
Date expiration = DateUtils.add(new Date(), Calendar.YEAR, 50);
// 生成URL
URL url = ossClient.generatePresignedUrl(bucketName, key, expiration);
if (url != null) {
String finalUrl = url.toString();
finalUrl = finalUrl.replace("http:", "https:");
return finalUrl;
}
return null;
}/**
* 上传文件到OSS
* @param file
* @param ossClient
* @param bucketName
* @param bucketDirName
* @return
* @throws Exception
*/
public static String uploadFile2Oss(File file, OSSClient ossClient, String bucketName, String bucketDirName) throws Exception{
InputStream inputStream = null;
String fileName = file.getName();
try {
inputStream = new FileInputStream(file);
String dirName = getBucketDirName(bucketDirName);
return uploadStream2OSS(inputStream,ossClient,bucketName,dirName,fileName);
} catch (Exception e) {
e.printStackTrace();
}finally{
if(inputStream != null){
inputStream.close();
}
}
return null;
}/**
* 读取网络文件并返回字节数组
* @param urlStr
* @return
*/
public static byte[] readFileByUrl(String urlStr) {
InputStream is = null;
ByteArrayOutputStream os = null;
byte[] buff = new byte[1024];
int len = 0;
try {
URL url = new URL(UriUtils.encodePath(urlStr, DEFAULT_CHARSET));
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Content-Type", "plain/text;charset=" + DEFAULT_CHARSET);
conn.setRequestProperty("charset", DEFAULT_CHARSET);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("GET");
conn.setReadTimeout(DEFAULT_TIME_OUT);
conn.connect();
is = conn.getInputStream();
os = new ByteArrayOutputStream();
while ((len = is.read(buff)) != -1) {
os.write(buff, 0, len);
}
return os.toByteArray();
} catch (IOException e) {
log.error("发起请求出现异常:", e);
return null;
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
log.error("【关闭流异常】");
}
}
if (os != null) {
try {
os.close();
} catch (IOException e) {
log.error("【关闭流异常】");
}
}
}
}public static byte[] readFileByUrlNo(String urlStr) {
InputStream is = null;
ByteArrayOutputStream os = null;
byte[] buff = new byte[1024];
int len = 0;
try {
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Content-Type", "plain/text;charset=" + DEFAULT_CHARSET);
conn.setRequestProperty("charset", DEFAULT_CHARSET);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("GET");
conn.setReadTimeout(DEFAULT_TIME_OUT);
conn.connect();
is = conn.getInputStream();
os = new ByteArrayOutputStream();
while ((len = is.read(buff)) != -1) {
os.write(buff, 0, len);
}
return os.toByteArray();
} catch (IOException e) {
log.error("发起请求出现异常:", e);
return null;
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
log.error("【关闭流异常】");
}
}
if (os != null) {
try {
os.close();
} catch (IOException e) {
log.error("【关闭流异常】");
}
}
}
}/**
* 根据不同的路径获取不同的上传文件夹路径
*/
public static String getDirByType(Integer type) {
if (type == null)
return OTHER_DIR;
switch (type) {
case 1 :
return FACE_DIR;
case 2:
return SHOP_DIR;
case 3:
return RECEIPT_DIR;
case 4:
return DEMO_MODEL_DIR;
case 5:
return ASSET_DIR;
case 6:
return BANNER_DIR;
case 7:
return INVOICE_DIR;
case 8:
return CUSTOMER_DIR;
default:
return OTHER_DIR;
}
}/**
* 根据文件url获取输入流
* @param fileUrl
* @return
*/
public static InputStream getInputStream(String fileUrl) {
byte[] content = OSSClientUtils.readFileByUrlNo(fileUrl);
return ByteToInputStreamUtil.byte2Input(content);
}
/**
* 删除文件
* @param ossClient
* @param bucketName
* @param url 文件路径
* @return
*/
public static boolean removeFileFromOss(OSSClient ossClient, String bucketName,String url) {
try {
ossClient.deleteObject(bucketName, url);
ossClient.shutdown();
return true;
}catch(Exception e) {
return false;
}
}
}文章来源:https://www.toymoban.com/news/detail-783145.html
码字不易,给个点赞关注呗 文章来源地址https://www.toymoban.com/news/detail-783145.html
到了这里,关于不允许你还不会OSS文件操作,看完一篇就够了的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!