AliOssCloudUtil 工具类
import com.alibaba.druid.support.logging.Log;
import com.alibaba.druid.support.logging.LogFactory;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.*;
import java.io.IOException;
import java.io.InputStream;
public class AliOssCloudUtil {
Log log = LogFactory.getLog(AliOssCloudUtil.class);
String endpoint="oss-cn-beijing.aliyuncs.com";
String accessKeyId ="xxxxxxxx"; //你的acessKeyId
String accessKeySecret ="xxxxxxxx"; //你的accessKeySecret
//空间
private String bucketName = "xxx"; //你的bucketName
//文件存储目录
private String filedir = "file/";
private OSSClient ossClient;
public AliOssCloudUtil() {
ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
}
public String getFiledir() {
return this.filedir;
}
//自定义上传文件夹
public AliOssCloudUtil(String filedir) {
this.filedir = filedir;
ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
}
/**
* 初始化
*/
public void init() {
ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
}
/**
* 销毁
*/
public void destory() {
ossClient.shutdown();
}
/**
* 上传到OSS服务器
*
* @param instream 文件流
* @param fileName 文件名称 包括后缀名
* @return 出错返回"" ,唯一MD5数字签名
*/
public String uploadFile2OSS(InputStream instream, String fileName) {
String ret = "";
// 判断bucket是否已经存在,不存在进行创建
if (!doesBucketExist()) {
createBucket();
}
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);
// 指定上传文件操作时是否覆盖同名Object。
// 不指定x-oss-forbid-overwrite时,默认覆盖同名Object。
// 指定x-oss-forbid-overwrite为false时,表示允许覆盖同名Object。
// 指定x-oss-forbid-overwrite为true时,表示禁止覆盖同名Object,如果同名Object已存在,程序将报错。
objectMetadata.setHeader("x-oss-forbid-overwrite", "false");
String objectName = filedir + fileName;
//上传文件
ossClient.putObject(bucketName, objectName, instream, objectMetadata);
// 封装 url 路径
String url = "http://" + bucketName + "." + endpoint + "/" + objectName;
System.out.println(objectName);
ret = url;
} catch (IOException e) {
log.error(e.getMessage(), e);
} finally {
ossClient.shutdown();
try {
if (instream != null) {
instream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return ret;
}
/**
* 判断文件是否存在。doesObjectExist还有一个参数isOnlyInOSS,
* 如果为true则忽略302重定向或镜像;如果为false,则考虑302重定向或镜像。
* yourObjectName 表示上传文件到OSS时需要指定包含文件后缀在内的完整路径,例如abc/efg/123.jpg。
*
* @return 存在返回true
*/
public boolean doesObjectExist(String objectName) {
boolean exists = ossClient.doesObjectExist(bucketName, filedir + objectName);
return exists;
}
/**
* 判断Bucket是否存在
*
* @return 存在返回true
*/
public boolean doesBucketExist() {
boolean exists = ossClient.doesBucketExist(bucketName);
return exists;
}
/**
* 创建Bucket
*/
public void createBucket() {
CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
// 设置bucket权限为公共读,默认是私有读写
createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
// 设置bucket存储类型为低频访问类型,默认是标准类型
createBucketRequest.setStorageClass(StorageClass.IA);
boolean exists = ossClient.doesBucketExist(bucketName);
if (!exists) {
try {
ossClient.createBucket(createBucketRequest);
// 关闭client
ossClient.shutdown();
} catch (Exception e) {
log.error(e.getMessage());
}
}
}
/**
* Description: 判断OSS服务文件上传时文件的contentType
*
* @param FilenameExtension 文件后缀
* @return String
*/
public static String getcontentType(String FilenameExtension) {
if (FilenameExtension.equalsIgnoreCase(".bmp")) {
return "application/x-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(".xla") ||
FilenameExtension.equalsIgnoreCase(".xlc") ||
FilenameExtension.equalsIgnoreCase(".xlm") ||
FilenameExtension.equalsIgnoreCase(".xls") ||
FilenameExtension.equalsIgnoreCase(".xlt") ||
FilenameExtension.equalsIgnoreCase(".xlw")) {
return "application/vnd.ms-excel";
}
if (FilenameExtension.equalsIgnoreCase(".xml")) {
return "text/xml";
}
if (FilenameExtension.equalsIgnoreCase(".pdf")) {
return "application/pdf";
}
if (FilenameExtension.equalsIgnoreCase(".zip")) {
return "application/zip";
}
if (FilenameExtension.equalsIgnoreCase(".tar")) {
return "application/x-tar";
}
if (FilenameExtension.equalsIgnoreCase(".avi")) {
return "video/avi";
}
if (FilenameExtension.equalsIgnoreCase(".mp4")) {
return "video/mpeg4";
}
if (FilenameExtension.equalsIgnoreCase(".mp3")) {
return "audio/mp3";
}
if (FilenameExtension.equalsIgnoreCase(".mp2")) {
return "audio/mp2";
}
return "application/octet-stream";
}
/**
* @param fileName
* @return
* @Title: getInputStreamByFileUrl
* @Description: 根据文件路径获取InputStream流
* @return: InputStream
*/
public InputStream getInputStreamByFileUrl(String fileName) {
// ossObject包含文件所在的存储空间名称、文件名称、文件元信息以及一个输入流。
OSSObject ossObject = ossClient.getObject(bucketName, fileName);
return ossObject.getObjectContent();
}
}
文件上传类例
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
/**
* @author Wcy
* @Date 2021/4/23 17:06
*/
@RestController
public class unloadFile {
/**
* 文件上传
* @param file
* @return
*/
@PostMapping("/file/upload")
public JSONObject upload(@RequestParam("file") MultipartFile file, HttpServletRequest servletRequest) {
JSONObject res = new JSONObject();
JSONObject resUrl = new JSONObject();
String filename = file.getResource().getFilename();//文件名称
System.out.println(filename);
//这里文件名用了uuid 防止重复,可以根据自己的需要来写
// String name = UUID.randomUUID() + filename.substring(filename.lastIndexOf("."), filename.length());
String name=filename;
// name = name.replace("-", "");
InputStream inputStream = null;
try {
inputStream = file.getInputStream();
} catch (IOException e) {
e.printStackTrace();
System.out.println("上传失败");
}
AliOssCloudUtil util = new AliOssCloudUtil();
//上传成功返回完整路径的url
String url = util.uploadFile2OSS(inputStream, name);
System.out.println("上传成功:"+url);
/**
* 以下为可能用到的保存上传信息
double filesize=file.getSize();
String size=String.format("%.2f",filesize/(1024*1024)).toString();
*/
return res;
}
/**
* 判断文件是否存在
* @param fileName 储存的文件名
* @return
*/
@GetMapping("/file/exists")
public Boolean exists(String fileName) {
AliOssCloudUtil util = new AliOssCloudUtil();
Boolean bool = util.doesObjectExist(fileName);
return bool;
}
/**
* 下载oss对应文件
* @param fileName 储存的文件名
* @return
*/
@PostMapping("/file/downLoad")
public void downloadFile(String fileName, HttpServletResponse response) {
try {
AliOssCloudUtil ossClientUtil = new AliOssCloudUtil();
InputStream is = ossClientUtil.getInputStreamByFileUrl(ossClientUtil.getFiledir() + fileName);
// 配置文件下载
response.setHeader("content-type", "application/octet-stream");
response.setContentType("application/octet-stream");
// 下载文件能正常显示中文
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
OutputStream os = response.getOutputStream();
byte[] b = new byte[1024];
int len = -1;
while ((len = is.read(b)) != -1) {
os.write(b, 0, len);
}
is.close();
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
相关配置
//控制文件上传大小
spring.servlet.multipart.max-file-size=1000MB
spring.servlet.multipart.max-request-size=1000MB
此处评论已关闭