導入依賴
<dependencies>
<!--阿裡雲oss sdk依賴-->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.10.2</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.9.4</version>
</dependency>
</dependencies>
配置application.yml
#服務端口
server:
port: 8082
spring:
#服務名
application:
name: edu_oss
#環境設定:dev、test、prod
profiles:
active: dev
#阿裡雲oss
aliyun:
oss:
file:
endpoint: # 你的 endpoint
keyid: # 你的 accessKeyId
keysecret: #你的 accessKeySecret
#bucket可以在控制台建立,也可以使用java代碼建立
bucketname: #你的bucket名
filehost: avatar #你的檔案路徑
後端實作檔案上傳
建立常量讀取工具類:ConstantPropertiesUtil.java
用spring的 InitializingBean 的 afterPropertiesSet 來初始化配置資訊,這個方法将在所有的屬性被初始化後調用。
package com.guigu.oss.utils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class ConstantPropertiesUtil implements InitializingBean {
@Value("${aliyun.oss.file.endpoint}")
private String endpoint;
@Value("${aliyun.oss.file.keyid}")
private String keyId;
@Value("${aliyun.oss.file.keysecret}")
private String keySecret;
@Value("${aliyun.oss.file.filehost}")
private String fileHost;
@Value("${aliyun.oss.file.bucketname}")
private String bucketName;
public static String END_POINT;
public static String ACCESS_KEY_ID;
public static String ACCESS_KEY_SECRET;
public static String BUCKET_NAME;
public static String FILE_HOST ;
@Override
public void afterPropertiesSet() throws Exception {
END_POINT = endpoint;
ACCESS_KEY_ID = keyId;
ACCESS_KEY_SECRET = keySecret;
BUCKET_NAME = bucketName;
FILE_HOST = fileHost;
}
}
檔案上傳
建立Service接口:FileService.java
package com.example.oss.service;
import org.springframework.web.multipart.MultipartFile;
public interface FileService {
/**
* 上傳圖檔
* @param file
* @return 圖檔位址
*/
String upload(MultipartFile file);
}
實作:FileServiceImpl.java
參考SDK中的:Java->上傳檔案->簡單上傳->流式上傳->上傳檔案流
阿裡雲文檔
// yourEndpoint填寫Bucket所在地域對應的Endpoint。以華東1(杭州)為例,Endpoint填寫為https://oss-cn-hangzhou.aliyuncs.com。
String endpoint = "yourEndpoint";
// 阿裡雲賬号AccessKey擁有所有API的通路權限,風險很高。強烈建議您建立并使用RAM使用者進行API通路或日常運維,請登入RAM控制台建立RAM使用者。
String accessKeyId = "yourAccessKeyId";
String accessKeySecret = "yourAccessKeySecret";
// 建立OSSClient執行個體。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
// 建立PutObjectRequest對象。
// 填寫Bucket名稱、Object完整路徑和本地檔案的完整路徑。Object完整路徑中不能包含Bucket名稱。
// 如果未指定本地路徑,則預設從示例程式所屬項目對應本地路徑中上傳檔案。
PutObjectRequest putObjectRequest = new PutObjectRequest("examplebucket", "exampleobject.txt", new File("D:\\localpath\\examplefile.txt"));
// 如果需要上傳時設定存儲類型和通路權限,請參考以下示例代碼。
// ObjectMetadata metadata = new ObjectMetadata();
// metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
// metadata.setObjectAcl(CannedAccessControlList.Private);
// putObjectRequest.setMetadata(metadata);
// 上傳檔案。
ossClient.putObject(putObjectRequest);
// 關閉OSSClient。
ossClient.shutdown();
實作的FileServiceImpl
package com.example.oss.service;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.example.oss.util.ConstantPropertiesUtil;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.joda.time.DateTime;
import java.io.InputStream;
import java.util.UUID;
@Service
public class FileServiceImpl implements FileService{
//預設圖檔檔案格式
private static String TYPESTR[] = {".png",".jpg",".bmp",".gif",".jpeg"};
@Override
public String upload(MultipartFile file) {
OSS ossClient = null;
String url = null;
try {
// 建立OSSClient執行個體。
ossClient = new OSSClientBuilder().build(
ConstantPropertiesUtil.END_POINT,
ConstantPropertiesUtil.ACCESS_KEY_ID,
ConstantPropertiesUtil.ACCESS_KEY_SECRET);
//判斷檔案格式
boolean flag = false;
for(String type : TYPESTR){ //循環 TYPESTR 判斷檔案格式
if(StringUtils.endsWithIgnoreCase(file.getOriginalFilename(),type)){
// StringUtils.endsWithIgnoreCase 判斷字元串以什麼為結尾
flag = true;
break;
}
}
if(!flag){
return "圖檔格式不正确";
}
//判斷檔案内容 ImageIO 讀圖檔
BufferedImage image = ImageIO.read(file.getInputStream());
if(image != null){
System.err.println(String.valueOf(image.getHeight()));
System.err.println(String.valueOf(image.getWidth()));
} else{
return "檔案内容不正确";
}
//擷取上傳檔案流的名稱
String filename = file.getOriginalFilename();
//處理檔案名字: lijin.shuai.jpg 僅最後一個為字尾名
String ext = filename.substring(filename.lastIndexOf(".")); //字尾名
String newName = UUID.randomUUID().toString() + ext;// 根據uuid設定名字
String dataPath = new DateTime().toString("yyyy/MM/dd"); //時間路徑
String urlPath = ConstantPropertiesUtil.FILE_HOST + "/" + dataPath + "/" + newName; //存儲路徑
// 上傳檔案流。
InputStream inputStream = file.getInputStream();
ossClient.putObject(ConstantPropertiesUtil.BUCKET_NAME, urlPath, inputStream);
url = "https://"+ConstantPropertiesUtil.BUCKET_NAME + "." + ConstantPropertiesUtil.END_POINT + "/" + urlPath;
} catch (Exception e) {
e.printStackTrace();
} finally {
// 關閉OSSClient。
ossClient.shutdown();
}
return url;
}
}
還需要判斷檔案格式和檔案内容是否符合,防止惡意腳本的上傳
//判斷檔案格式
boolean flag = false;
for(String type : TYPESTR){ //循環 TYPESTR 判斷檔案格式
if(StringUtils.endsWithIgnoreCase(file.getOriginalFilename(),type)){
// StringUtils.endsWithIgnoreCase 判斷字元串以什麼為結尾
flag = true;
break;
}
}
if(!flag){
return “圖檔格式不正确”;
}
//判斷檔案内容 ImageIO 讀圖檔
BufferedImage image = ImageIO.read(file.getInputStream());
if(image != null){
System.err.println(String.valueOf(image.getHeight()));
System.err.println(String.valueOf(image.getWidth()));
} else{
return “檔案内容不正确”;
}