Java实现阿⾥云oss⽂预览上传和下载第⼀步:引⼊maven依赖
<dependency>
<groupId>org.apachemons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
<!--阿⾥云oss-->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>2.8.2</version>
</dependency> 
第⼆步:阿⾥云oss⼯具类
import com.aliyun.oss.OSSClient;
import com.del.*;
import org.apachemons.logging.Log;
import org.apachemons.logging.LogFactory;
import java.io.*;
/**
* 阿⾥云 OSS⽂件类
*/
public class AliOssCloudUtil {
Log log = Log(AliOssCloudUtil.class);
/
**
* ⽤户的存储空间所在数据中⼼的访问域名
*/
private String endpoint = "oss-cn-hangzhou.aliyuncs";
/**
* OSS签名key
*/
private String accessKeyId = "LTAI5tSJSDtUaXXXX";
/**
* OSS签名密钥
*/
private static final String accessKeySecret = "AQLmguaT1BFsOi5oe07iMUXXXXX";
/**
* 存储空间名称
*/
private static final String bucketName = "oss-uav-oss";
//⽂件存储⽬录
private String filedir = "uav/";
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 = "" + bucketName + "." + endpoint + "/" + objectName;
ret = url;
} catch (IOException e) {
<(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
*/下载apache
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 {
// 关闭client
ossClient.shutdown();
} catch (Exception e) {
<(e.getMessage());
}
}
}
/**
* Description: 判断OSS服务⽂件上传时⽂件的contentType
*
* @param FilenameExtension ⽂件后缀
* @return String
*/
public static String getcontentType(String FilenameExtension) {
if (".bmp".equalsIgnoreCase(FilenameExtension)) {
return "image/bmp";
}
if (".gif".equalsIgnoreCase(FilenameExtension)) {
return "image/gif";
}
if (".jpeg".equalsIgnoreCase(FilenameExtension)
|| ".jpg".equalsIgnoreCase(FilenameExtension)
|| ".png".equalsIgnoreCase(FilenameExtension)) {
return "image/jpg";
}
if (".html".equalsIgnoreCase(FilenameExtension)) {
return "text/html";
}
if (".txt".equalsIgnoreCase(FilenameExtension)) {
return "text/plain";
}
if (".vsd".equalsIgnoreCase(FilenameExtension)) {
return "application/vnd.visio";
}
if (".ppt".equalsIgnoreCase(FilenameExtension) || "pptx".equalsIgnoreCase(FilenameExtension)) {            return "application/vnd.ms-powerpoint";
}
if (".doc".equalsIgnoreCase(FilenameExtension) || "docx".equalsIgnoreCase(FilenameExtension)) {            return "application/msword";
}
if (".xml".equalsIgnoreCase(FilenameExtension)) {
return "text/xml";
}
if (".mp4".equalsIgnoreCase(FilenameExtension)) {
return "video/mp4";
}
if (".mp3".equalsIgnoreCase(FilenameExtension)) {
return "audio/mp3";
}
return "text/html";
}
/**
* @Description: 根据⽂件路径获取InputStream流
*/
public InputStream getInputStreamByFileUrl(String fileName) {
// ossObject包含⽂件所在的存储空间名称、⽂件名称、⽂件元信息以及⼀个输⼊流。
OSSObject ossObject = Object(bucketName, fileName);
ObjectContent();
}
}
第三步:上传下载⽂件
public class FlightFileController {
@ResponseBody
@PostMapping("/upload")
public Response upload(@RequestParam("file") MultipartFile file) {
String filename = Resource().getFilename();
//⽂件名
String pattern = "yyyy-MM-dd";
String dir = DateFormatUtils.format(new Date(), pattern);
String name = "";
if (getFileType(filename) == 0) {
name = Value() + "/" + dir + "/" + filename;
} else {
name = Value() + "/" + dir + "/" + filename;
}
InputStream inputStream = null;
try {
inputStream = InputStream();
} catch (IOException e) {
e.printStackTrace();
log.info("上传失败");
}
AliOssCloudUtil util = new AliOssCloudUtil();
//上传成功返回可直接查看⽂件的url
String url = util.uploadFile2OSS(inputStream, name);
return Response.success(url);
}
public int getFileType(String fileName) {
int i = 0;
FileNameMap fileNameMap = FileNameMap();
String contentTypeFor = ContentTypeFor(fileName);
//下⾯是进⼀判断是视频和图⽚的区别
if (contentTypeFor != null) {// 当为图⽚时不为空,是视频时为空
i = 1;
}
return i;
}
@PostMapping("/downLoad")
public void downloadFile(String fileName, HttpServletResponse response) {
try {
AliOssCloudUtil ossClientUtil = new AliOssCloudUtil();
InputStream is = Filedir() + fileName);
// 配置⽂件下载
response.setHeader("content-type", "application/octet-stream");
response.setContentType("application/octet-stream");
// 下载⽂件能正常显⽰中⽂
response.setHeader("Content-Disposition", "attachment;filename=" + de(fileName, "UTF-8"));            OutputStream os = OutputStream();
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();
}
}
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。