安裝javaJDk
文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-649093.html
依賴 jdk1.8(只用一個(gè)依賴即可)
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.10.2</version>
</dependency>
<dependency>
使用的是Java 9及以上的版本,則需要添加jaxb相關(guān)依賴。
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1.1</version>
</dependency>
<!-- no more than 2.3.3-->
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
<version>2.3.3</version>
</dependency>
程序:
public String uploadFileToOss(MultipartFile multipartFile,String fileCatalog) {
//地域節(jié)點(diǎn)
String endpoint = ".........aliyuncs.com";// 阿里云賬號(hào)AccessKey擁有所有API的訪問(wèn)權(quán)限,風(fēng)險(xiǎn)很高。強(qiáng)烈建議您創(chuàng)建并使用RAM用戶進(jìn)行API訪問(wèn)或日常運(yùn)維,請(qǐng)登錄RAM控制臺(tái)創(chuàng)建RAM用戶。
//AccessKey管理
String accessKeyId = "............";
String accessKeySecret = ".........";
//bucket名稱
String bucketName = ".........-oss";
// 創(chuàng)建OSSClient實(shí)例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
try {
//獲取文件流
InputStream inputStream=multipartFile.getInputStream();
//構(gòu)建日期文件
SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy/MM/dd");
String datePath=dateFormat.format(new Date());
//獲取到文件名
String originName= multipartFile.getOriginalFilename();
//文件名
String fileName = UUID.randomUUID().toString();
//后綴
String suffix=originName.substring(originName.lastIndexOf("."));
//新文件名
String newName=fileName+suffix;
//完整路徑
String fileUrl="............"+fileCatalog+datePath+"/"+newName;
//文件上傳到阿里云服務(wù)器
ossClient.putObject(bucketName,fileUrl,inputStream);
//返回路徑
String filePath="https://"+bucketName+"."+endpoint+"/"+fileUrl;
System.out.println(filePath);
return filePath;
} catch (Exception e) {
e.printStackTrace();
return "fail";
} finally {
//關(guān)閉ossClient
if (ossClient != null) {
ossClient.shutdown();
}
}
}
文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-649093.html
到了這里,關(guān)于阿里云oss對(duì)象存儲(chǔ)上傳照片并返回照片路徑的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!