**
## BosUtils工具类
**
public class BosUtils {
private static Logger logger = LoggerFactory.getLogger(BosUtils.class);
private static BosClient client;
private static String bucketName;
private static Integer expireTime;
private static String imgLayout = "@s_0,w_300,q_60,f_png";
private static String imgLayoutRaw = "@s_0,w_720,q_60,f_png";
public static void run(String accessKey, String secretKey, String bucketName, String expireTime) {
BosUtils.bucketName = bucketName;
BosUtils.expireTime = Integer.parseInt(expireTime);
BosClientConfiguration config = new BosClientConfiguration();
config.setMaxConnections(100);
config.setConnectionTimeoutInMillis(50000);
config.setSocketTimeoutInMillis(30000);
config.setCredentials(new DefaultBceCredentials(accessKey, secretKey));
client = new BosClient(config);
logger.info("BOS 启动!");
}
public static byte[] getObjectByte(String objectKey) throws IOException {
BosObject object = client.getObject(bucketName, objectKey);
ObjectMetadata meta = object.getObjectMetadata();
InputStream objectContent = object.getObjectContent();
ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
byte[] buff = new byte[100];
int rc = 0;
while ((rc = objectContent.read(buff, 0, 100)) > 0) {
swapStream.write(buff, 0, rc);
}
objectContent.close();
byte[] in2b = swapStream.toByteArray();
return in2b;
}
public static String generatePresignedUrl(String objectKey, String imgLayout) {
if (imgLayout != null) {
objectKey = objectKey + imgLayout;
}
URL url = client.generatePresignedUrl(bucketName, objectKey, expireTime);
return url.toString();
}
public static String PutObjectFromURL(String fileUrl) {
String key = getKey(null);
try {
URL url = new URL(fileUrl);
java.net.URLConnection conn = url.openConnection();
InputStream is = conn.getInputStream();
client.putObject(bucketName, key, is);
is.close();
} catch (IOException e) {
e.printStackTrace();
return null;
}
return key;
}
private static String getKey(String suffix) {
return CommonUtils.getUUID() + (suffix != null ? "." + suffix : "");
}
public static String PutObjectFromFile(File ufile) {
String key = getKey(null);
PutObjectResponse putObjectFromFileResponse = client.putObject(bucketName, key, ufile);
System.out.println(putObjectFromFileResponse.getETag());
return key;
}
public static String PutObjectFromInputStream(InputStream is, String suffix) {
String key = getKey(suffix);
PutObjectResponse putObjectFromFileResponse = client.putObject(bucketName, key, is);
System.out.println(putObjectFromFileResponse.getETag());
return key;
}
public static String PutObjectFromInputStream(InputStream is, String suffix,String fileName) {
String key = getKey(suffix);
PutObjectResponse putObjectFromFileResponse = null;
ObjectMetadata meta = new ObjectMetadata();
meta.setContentDisposition("attachment;filename=" + new String(fileName.getBytes(), Charset.forName("ISO-8859-1")));
putObjectFromFileResponse = client.putObject(bucketName, key, is, meta);
System.out.println(putObjectFromFileResponse.getETag());
return key;
}
public static String putObjectFromByte(byte[] bytes, String suffix) {
String key = getKey(suffix);
PutObjectResponse putObjectFromFileResponse = client.putObject(bucketName, key, bytes);
return key;
}
public static List<BosVO> getUrlsByBosKeys(String bosKeys, boolean isImage) {
if (StringUtils.isBlank(bosKeys)) {
return new ArrayList<>();
}
List<BosVO> urls = new ArrayList<>();
String[] keys = bosKeys.split(",");
for (int i = 0; i < keys.length; i++) {
String url = null;
BosVO bosUrlVo = new BosVO();
if (isImage) {
url = generatePresignedUrl(keys[i], imgLayoutRaw);
String thumbnailUrl = generatePresignedUrl(keys[i], imgLayout);
bosUrlVo.setThumbnailUrl(thumbnailUrl);
} else {
url = generatePresignedUrl(keys[i], null);
}
bosUrlVo.setKey(keys[i]);
bosUrlVo.setUrl(url);
urls.add(bosUrlVo);
}
return urls;
}
public static List<BosVO> getUrlsByBosList(String lists, boolean isImage) {
if (StringUtils.isBlank(lists)) {
return new ArrayList<>();
}
List<BosVO> urls = new ArrayList<>();
List<BosFileList> list = new ArrayList<BosFileList>();
list = JSONObject.parseArray(lists, BosFileList.class);
for (BosFileList bl : list) {
String url = null;
BosVO bosUrlVo = new BosVO();
if (isImage) {
url = generatePresignedUrl(bl.getBosKeys(), imgLayoutRaw);
String thumbnailUrl = generatePresignedUrl(bl.getBosKeys(), imgLayout);
bosUrlVo.setThumbnailUrl(thumbnailUrl);
} else {
url = generatePresignedUrl(bl.getBosKeys(), null);
}
bosUrlVo.setKey(bl.getBosKeys());
bosUrlVo.setName(bl.getBosNames());
bosUrlVo.setUrl(url);
urls.add(bosUrlVo);
}
return urls;
}
public static BosVO getUrlByBosKey(String bosKey, boolean isImage) {
if (bosKey == null) {
return null;
}
String url = null;
BosVO bosUrlVo = new BosVO();
if (isImage) {
url = generatePresignedUrl(bosKey, imgLayoutRaw);
String thumbnailUrl = generatePresignedUrl(bosKey, imgLayout);
bosUrlVo.setThumbnailUrl(thumbnailUrl);
} else {
url = generatePresignedUrl(bosKey, null);
}
bosUrlVo.setUrl(url);
bosUrlVo.setKey(bosKey);
return bosUrlVo;
}
public static String getUrlByBosKey(String bosKey) {
Assert.notNull(bosKey, "bosKey must be not null!");
return client.generatePresignedUrl(bucketName, bosKey, -1).toString();
}
private static void getBosKeyList(){
String wsAcc = "";
String wsSec = "";
String bucket = "pt-files-test";
BosClientConfiguration config = new BosClientConfiguration();
config.setCredentials(new DefaultBceCredentials(wsAcc, wsSec));
BosClient client = new BosClient(config);
ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucket);
listObjectsRequest.withMaxKeys(500);
boolean isTruncated = true;
StringBuilder content = new StringBuilder();
while (isTruncated) {
ListObjectsResponse listObjectsResponse = client.listObjects(listObjectsRequest);
isTruncated = listObjectsResponse.isTruncated();
if (listObjectsResponse.getNextMarker() != null) {
listObjectsRequest.withMarker(listObjectsResponse.getNextMarker());
}
listObjectsResponse.getContents().forEach(obj -> {
content.append(obj.getKey()+"\t");
content.append("http://"+bucket+".cdn.bcebos.com/"+obj.getKey()+"\tSTANDARD\r\n");
});
}
try {
FileWriter fileWriter = new FileWriter("/data/"+bucket+".txt");
fileWriter.write(content.toString());
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
接口调用
public class FileController {
@Value("${file.upload.acceptTypes}")
String acceptTypes;
@PostMapping("/file/upload")
public ResponseVO fileUpload(MultipartFile file) throws IOException {
Map<String, Object> resultMap = new HashMap<>();
String key = "";
String url = "";
String thumbnailUrl = "";
String name = "";
String suffix = "";
if (file == null || file.equals("") || file.getSize() <= 0) {
return new ResponseVO(400, "上传文件内容为空");
} else {
String originalFilename = file.getOriginalFilename();
suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
name = file.getOriginalFilename().substring(0,file.getOriginalFilename().indexOf("."));
if (acceptTypes.indexOf(suffix) < 0) {
return new ResponseVO(400, "文件格式不支持");
} else {
key = BosUtils.PutObjectFromInputStream(file.getInputStream(),suffix.toLowerCase(),originalFilename);
url = BosUtils.getUrlByBosKey(key);
thumbnailUrl = BosUtils.getUrlByBosKey(key, true).getThumbnailUrl();
file.getInputStream().close();
}
}
resultMap.put("key", key);
resultMap.put("url", url);
resultMap.put("thumbnailUrl", thumbnailUrl);
resultMap.put("name", name);
resultMap.put("type", suffix);
resultMap.put("size", file.getSize());
return new ResponseVO(resultMap);
}
@PostMapping("/file/imageUpload")
public ResponseVO imageUpload(@RequestParam String image) {
String facePicPath = "";
String corpId = "taoding";
String faceId = CommonUtils.getUUID();
String imageType = image.substring(image.indexOf("/") + 1, image.indexOf(";"));
image = image.replace("data:image/" + imageType + ";base64,", "");
byte[] bytes = CommonUtils.getFromBASE64(image);
OutputStream out = null;
String outputPath = facePicPath + File.separator + corpId + File.separator;
File destFile = new File(outputPath);
if (!destFile.exists()) {
destFile.mkdirs();
}
try {
out = new FileOutputStream(outputPath + File.separator + faceId + "." + imageType);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
out.write(bytes);
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
return new ResponseVO(outputPath);
}
@PostMapping("/file/ckEditorUpload")
public Map<String, Object> ueditorUpload(MultipartFile upload) throws IOException {
Map<String, Object> resultMap = new HashMap<>();
String key = "";
String url = "";
String name = "";
if (upload == null || upload.equals("") || upload.getSize() <= 0) {
throw new RuntimeException("上传文件为空");
} else {
String suffix = upload.getOriginalFilename().substring(upload.getOriginalFilename().lastIndexOf(".") + 1);
name = upload.getOriginalFilename();
if (acceptTypes.indexOf(suffix) < 0) {
throw new RuntimeException("上传文件格式不支持");
} else {
key = BosUtils.PutObjectFromInputStream(upload.getInputStream(), suffix,name);
url = BosUtils.getUrlByBosKey(key);
upload.getInputStream().close();
}
}
resultMap.put("uploaded", "1");
resultMap.put("url", url);
return resultMap;
}
}