工具类:OSSClientUtil
public class OSSClientUtil {
private String endpoint = "http://oss-cn-hangzhou.aliyuncs.com/";
// accessKey
private String accessKeyId = "LTAI4FWE********";
//accessKeySecret
private String accessKeySecret = "0vnAVGXpPZFOr3****************";
// Bucket名称
private String bucketName = "bucketName";
// 文件存储目录
private String filedir = "";
private OSSClient ossClient;
public OSSClientUtil() {
//注意: 专有云、专有域环境必须要使用ClientConfiguration的对象传入参数,不然会报错。
// 创建ClientConfiguration实例,按照您的需要修改默认参数。
ClientConfiguration conf = new ClientConfiguration();
// 关闭CNAME选项。
conf.setSupportCname(false);
ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret,conf);
}
/**
* 初始化
*/
public void init() {
ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
}
/**
* 销毁
*/
public void destory() {
ossClient.shutdown();
}
/**
* 上传图片
*
* @param url
*/
public void uploadImg2Oss(String url) throws Exception {
File fileOnServer = new File(url);
FileInputStream fin;
try {
fin = new FileInputStream(fileOnServer);
String[] split = url.split("/");
this.uploadFile2OSS(fin, split[split.length - 1]);
} catch (FileNotFoundException e) {
throw new Exception("图片上传失败");
}
}
public String uploadImg2Oss(MultipartFile file) throws Exception {
if (file.getSize() > 2 * 1024 * 1024) {
throw new Exception("上传图片大小不能超过2M!");
}
String originalFilename = file.getOriginalFilename();
System.out.println(originalFilename);
String substring = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
Random random = new Random();
String name = random.nextInt(10000) + System.currentTimeMillis() + substring;
try {
InputStream inputStream = file.getInputStream();
//System.out.println("文件名称="+name);
this.uploadFile2OSS(inputStream, name);
return name;
} catch (Exception e) {
throw new Exception("图片上传失败");
}
}
/**
* 上传到OSS服务器 如果同名文件会覆盖服务器上的
* @param instream 文件流
* @param fileName 文件名称 包括后缀名
* @return 出错返回"" ,唯一MD5数字签名
*/
public String uploadFile2OSS(InputStream instream, String fileName) {
String ret = "";
try {
// 创建上传Object的Metadata
ObjectMetadata objectMetadata = new ObjectMetadata();
objectMetadata.setContentLength(instream.available());
objectMetadata.setCacheControl("no-cache");
objectMetadata.setHeader("Pragma", "no-cache");
objectMetadata.setContentType(getcontentType(fileName.substring(fileName.lastIndexOf("."))));
objectMetadata.setContentDisposition("inline;filename=" + fileName);
//System.out.println("开始上传文件");
// 上传文件
PutObjectResult putResult = ossClient.putObject(bucketName, fileName, instream, objectMetadata);
//PutObjectResult putResult = ossClient.putObject(bucketName, fileName, instream, objectMetadata);
//System.out.println("上传成功");
ret = putResult.getETag();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (instream != null) {
instream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return ret;
}
/**
* Description: 判断OSS服务文件上传时文件的contentType
*
* @param filenameExtension 文件后缀
* @return String
*/
public static String getcontentType(String filenameExtension) {
if (filenameExtension.equalsIgnoreCase("bmp")) {
return "image/bmp";
}
if (filenameExtension.equalsIgnoreCase("gif")) {
return "image/gif";
}
if (filenameExtension.equalsIgnoreCase("jpeg") || filenameExtension.equalsIgnoreCase("jpg")
|| filenameExtension.equalsIgnoreCase("png")) {
return "image/jpeg";
}
if (filenameExtension.equalsIgnoreCase("html")) {
return "text/html";
}
if (filenameExtension.equalsIgnoreCase("txt")) {
return "text/plain";
}
if (filenameExtension.equalsIgnoreCase("vsd")) {
return "application/vnd.visio";
}
if (filenameExtension.equalsIgnoreCase("pptx") || filenameExtension.equalsIgnoreCase("ppt")) {
return "application/vnd.ms-powerpoint";
}
if (filenameExtension.equalsIgnoreCase("docx") || filenameExtension.equalsIgnoreCase("doc")) {
return "application/msword";
}
if (filenameExtension.equalsIgnoreCase("xml")) {
return "text/xml";
}
return "image/jpeg";
}
/**
* 获得url链接
*
* @param key
* @return
*/
public String getUrl(String key) {
// 设置URL过期时间为10年 3600l* 1000*24*365*10
Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 10);
// 生成URL
URL url = ossClient.generatePresignedUrl(bucketName, key, expiration);
if (url != null) {
System.out.println("url="+url.toString());
return url.toString();
}
return null;
}
public boolean deleteFile(String filePath) {
boolean exist = ossClient.doesObjectExist(bucketName, filePath);
if (!exist) {
System.out.println("文件不存在,filePath=" + filePath);
return false;
}
System.out.println("删除文件,filePath=" + filePath);
ossClient.deleteObject(bucketName, filePath);
// ossClient.shutdown();
return true;
}
/**
* 获取流文件
* @param response
* @param request
* @param fileId
* @param fileName
*/
public void getFile(HttpServletResponse response, HttpServletRequest request,String fileId,String fileName) {
try {
int i=fileName.lastIndexOf("\\");
fileName=fileName.substring(i+1);
//获取fileid对应的阿里云上的文件对象
OSSObject ossObject = ossClient.getObject(bucketName, fileId);//bucketName需要自己设置
// 读去Object内容 返回
BufferedInputStream in=new BufferedInputStream(ossObject.getObjectContent());
BufferedOutputStream out=new BufferedOutputStream(response.getOutputStream());
//通知浏览器以附件形式下载
response.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(fileName,"utf-8"));
byte[] car=new byte[1024];
int L=0;
while((L=in.read(car))!=-1){
out.write(car, 0,L);
}
if(out!=null){
out.flush();
out.close();
}
if(in!=null){
in.close();
}
ossClient.shutdown();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获得图片路径
*
* @param fileUrl
* @return
*/
public String getImgUrl(String fileUrl) {
System.out.println("fileUrl="+fileUrl);
if (!StringUtils.isEmpty(fileUrl)) {
String[] split = fileUrl.split("/");
return this.getUrl(this.filedir + split[split.length - 1]);
}
return null;
}
}
文件上传
OSSClientUtil ossClient = new OSSClientUtil();
String name = ossClient.uploadImg2Oss(file);
文件下载
OSSClientUtil ossClient = new OSSClientUtil();
ossClient.getFile(response,request,attach.getAttachName(),attach.getFileName());
文件删除
OSSClientUtil ossClient = new OSSClientUtil();
ossClient.deleteFile(attachPhotoLocation.getAttachName());
读取图片流
OSSClientUtil ossClient = new OSSClientUtil();
String imgUrl = ossClient.getImgUrl(file.getAttachName());
URL url = new URL(imgUrl);
URLConnection conn = url.openConnection();
InputStream inStream = conn.getInputStream();
response.setContentType("image/jpg"); // 设置返回的文件类型
response.setHeader("Access-Control-Allow-Origin", "*");// 设置该图片允许跨域访问
//compile "commons-io:commons-io:2.3"
//import org.apache.commons.io.IOUtils;
IOUtils.copy(inStream, response.getOutputStream());
本文介绍了一个用于操作阿里云OSS的工具类OSSClientUtil,详细解析了类中实现的文件上传、下载、删除及获取URL等功能。通过示例展示了如何使用此工具类进行文件的上传、下载和删除操作。
229

被折叠的 条评论
为什么被折叠?



