SpringBoot整合阿里雲OSS儲存服務
阿新 • • 發佈:2018-11-01
摘要:OSS可用於圖片、音視訊、日誌等海量檔案的儲存。各種終端裝置、Web網站程式、移動應用可以直接向OSS寫入或讀取資料,非常方便。本篇文章介紹如何在java的SpringBoot專案中,整個使用OSS服務,spring 專案也可以參考。
主要步驟如下:
前提是開通了阿里雲OSS服務,然後;
1.引入依賴
2.獲取關鍵引數,如endpoint,accessKeyId等,這個進入阿里雲OSS控制檯即可獲取
3.建一個檔案上傳工具類
4.呼叫工具類,上傳檔案
1.pom.xml
<!--aliyunOSS--> <dependency> <groupId>com.aliyun.oss</groupId> <artifactId>aliyun-sdk-oss</artifactId> <version>2.4.0</version> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency>
2.配置檔案
注意:為了以後的拓展性,程式碼和配置解耦,我這裡會專門建一個配置檔案,然後在使用時直接從配置類中獲取,而不是寫死在java程式碼中。所以2,3兩步不是必須的,作用只是規範的使用相關配置引數,若覺得麻煩,學習時,可直接在java程式碼中寫死。application.properties 這裡是我定義的一些必要常量
#OSS java4all.file.endpoint=oss-cn-shanghai.aliyuncs.com 不同的伺服器,地址不同 java4all.file.keyid=去OSS控制檯獲取 java4all.file.keysecret=去OSS控制檯獲取 java4all.file.bucketname1=java4all-file 這個自己建立bucket時的命名,控制檯建立也行,程式碼建立也行 java4all.file.filehost=blog 檔案路徑,我這裡是blog
3.ConstantProperties.java
這是我定義的常量類,讀取配置檔案application.properties中的配置,定義為常量,方便使用
package com.java4all.config; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; /** * Created by lightClouds917 * Date 2018/1/16 * Description:配置檔案配置項 */ @Component public class ConstantProperties{ @Value("${java4all.file.endpoint}") private String java4all_file_endpoint; @Value("${java4all.file.keyid}") private String java4all_file_keyid; @Value("${java4all.file.keysecret}") private String java4all_file_keysecret; @Value("${java4all.file.filehost}") private String java4all_file_filehost; @Value("${java4all.file.bucketname1}") private String java4all_file_bucketname1; public static String JAVA4ALL_END_POINT; public static String JAVA4ALL_ACCESS_KEY_ID; public static String JAVA4ALL_ACCESS_KEY_SECRET; public static String JAVA4ALL_BUCKET_NAME1; public static String JAVA4ALL_FILE_HOST; @PostConstruct private void initial(){ JAVA4ALL_END_POINT = java4all_file_endpoint; JAVA4ALL_ACCESS_KEY_ID = java4all_file_keyid; JAVA4ALL_ACCESS_KEY_SECRET = java4all_file_keysecret; JAVA4ALL_FILE_HOST = java4all_file_filehost; JAVA4ALL_BUCKET_NAME1 = java4all_file_bucketname1; } }
上傳阿里雲工具類:
package com.example.demo.common;
import java.io.*;
import java.net.URL;
import java.util.Date;
import java.util.Random;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import org.springframework.context.annotation.Bean;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
/**
* Created by Administrator on 2018/1/27 0027.
*/
public class OSSClientUtil {
Log log = LogFactory.getLog(OSSClientUtil.class);
// endpoint以杭州為例,其它region請按實際情況填寫
protected static String endpoint = "http://oss-cn-shanghai.aliyuncs.com";
protected static String accessKeyId = "你的accessKeyId";
protected static String accessKeySecret = "你的accessKeySecret";
protected static String bucketName = "weishang-fc";
//檔案儲存目錄
private String filedir = "imgupload/";
private OSSClient ossClient;
public OSSClientUtil() {
ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
}
/**
* 初始化
*/
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("圖片上傳失敗01");
}
}
public String uploadImg2Oss(MultipartFile file) throws Exception {
if (file.getSize() > 1024 * 1024) {
throw new Exception("上傳圖片大小不能超過1M!");
}
String originalFilename = file.getOriginalFilename();
String substring = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
Random random = new Random();
String name = random.nextInt(10000) + System.currentTimeMillis() + substring;
try {
InputStream inputStream = file.getInputStream();
this.uploadFile2OSS(inputStream, name);
return name;
} catch (Exception e) {
throw new Exception("圖片上傳失敗02");
}
}
/**
* 獲得圖片路徑
*
* @param fileUrl
* @return
*/
public String getImgUrl(String fileUrl) {
if (!StringUtils.isEmpty(fileUrl)) {
String[] split = fileUrl.split("/");
return this.getUrl(this.filedir + split[split.length - 1]);
}
return null;
}
/**
* 上傳到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);
//上傳檔案
PutObjectResult putResult = ossClient.putObject(bucketName, filedir + fileName, instream, objectMetadata);
ret = putResult.getETag();
} catch (IOException e) {
log.error(e.getMessage(), e);
} 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(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);
// 生成URL
URL url = ossClient.generatePresignedUrl(bucketName, key, expiration);
if (url != null) {
return url.toString();
}
return null;
}
}
service:(這個根據需要,也可以省略直接在controller裡面寫)
@Service
public class UpDownServiceImpl {
private OSSClientUtil ossClient=new OSSClientUtil();
public String updateHead(MultipartFile file, long userId) throws Exception {
if (file == null || file.getSize() <= 0) {
throw new Exception("頭像不能為空");
}
String name = ossClient.uploadImg2Oss(file);
String imgUrl = ossClient.getImgUrl(name);
//userDao.updateHead(userId, imgUrl);//只是本地上傳使用的
return imgUrl;
}
}
controller:
@Controller
@RequestMapping("/user")
public class UserController {
//處理檔案上傳
@RequestMapping(value="/testuploadimg", method = RequestMethod.POST)
@ResponseBody
/*public String uploadImg(@RequestParam("file") MultipartFile file,
HttpServletRequest request) {*/
public Map<String, Object> headImgUpload(HttpServletRequest request,@RequestParam("file")MultipartFile file) {
Map<String, Object> value = new HashMap<String, Object>();
value.put("success", true);
value.put("errorCode", 0);
value.put("errorMsg", "");
try {
String head = upDownServiceImpl.updateHead(file, 4);//此處是呼叫上傳服務介面,4是需要更新的userId 測試資料。
value.put("data", head);
} catch (IOException e) {
e.printStackTrace();
value.put("success", false);
value.put("errorCode", 200);
value.put("errorMsg", "圖片上傳失敗");
} catch (Exception e) {
e.printStackTrace();
}
return value;
}
}
前端頁面:
<!--檔案上傳-->
<div style="border: solid 1px">
<form enctype="multipart/form-data" method="post" th:action= "@{/user/testuploadimg}">圖片<input type="file" name="file"/>
<input type="submit" value="上傳"/>
</form>
</div>
我自己搗鼓了半天的小坑:
bucket.oss-cn-hangzhou.aliyuncs.com 不要填類似這樣的
應該直接填Endpoint,如:
oss-cn-shanghai.aliyuncs.com
我一直寫成:
// endpoint以杭州為例,其它region請按實際情況填寫
protected static String endpoint = "http://weishang-fc.oss-cn-shanghai.aliyuncs.com";
protected static String accessKeyId = "xx";
protected static String accessKeySecret = "xx";
protected static String bucketName = "weishang-fc";
正確應該是這樣:
// endpoint以杭州為例,其它region請按實際情況填寫
protected static String endpoint = "http://oss-cn-shanghai.aliyuncs.com";
protected static String accessKeyId = "xx";
protected static String accessKeySecret = "xx";
protected static String bucketName = "weishang-fc";
這裡只是簡單的單個圖片/檔案的上傳,記錄下來,方便下次使用。