1.打開阿里雲網站:https://www.aliyun.com/
2.注冊阿里雲,最終獲取4個參數bucket 名稱,endpoint ,Accesskey ID , Access key Secert
3.搭建環境,引入maven依賴
<!-- 阿里雲oss依賴 --> <dependency> <groupId>com.aliyun.oss</groupId> <artifactId>aliyun-sdk-oss</artifactId> </dependency> <!-- 日期工具欄依賴 --> <dependency> <groupId>joda-time</groupId> <artifactId>joda-time</artifactId> </dependency>
4.application.properties
#服務端口 server.port=8002 #服務名 spring.application.name=service_oss #環境設置:dev、test、prod spring.profiles.active=dev #阿里雲 OSS #不同的服務器,地址不同 aliyun.oss.file.endpoint=oss-cn-beijing.aliyuncs.com aliyun.oss.file.keyid=LTAI4Fi3Vq4jbugiWKrxnxtt aliyun.oss.file.keysecret=32qRznii5mTJCdyq9OimXMxCTiQJdr #bucket可以在控制台創建,也可以使用java代碼創建 aliyun.oss.file.bucketname=liuyi202044
5.controller層
@RestController @CrossOrigin @RequestMapping("/eduoss/fileoss") public class OssController { @Autowired private OssService ossService; //上傳頭像的方法 @PostMapping public R uploadOssFile(MultipartFile file) { //獲取上傳文件 MultipartFile //返回上傳到oss的路徑 String url = ossService.uploadFileAvatar(file); return R.ok().data("url",url); } }
6.創建一個工具類
//當項目已啟動,spring接口,spring加載之后,執行接口一個方法 @Component public class ConstantPropertiesUtils 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.bucketname}") private String bucketName; //定義公開靜態常量 public static String END_POIND; public static String ACCESS_KEY_ID; public static String ACCESS_KEY_SECRET; public static String BUCKET_NAME; @Override public void afterPropertiesSet() throws Exception { END_POIND = endpoint; ACCESS_KEY_ID = keyId; ACCESS_KEY_SECRET = keySecret; BUCKET_NAME = bucketName; } }
7.service層
@Service public class OssServiceImpl implements OssService { @Override public String uploadFileAvatar(MultipartFile file) { // 工具類獲取值 String endpoint = ConstantPropertiesUtils.END_POIND; String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID; String accessKeySecret = ConstantPropertiesUtils.ACCESS_KEY_SECRET; String bucketName = ConstantPropertiesUtils.BUCKET_NAME; try { // 創建OSS實例。 OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret); //獲取上傳文件輸入流 InputStream inputStream = file.getInputStream(); //獲取文件名稱 String fileName = file.getOriginalFilename(); //1 在文件名稱里面添加隨機唯一的值 String uuid = UUID.randomUUID().toString().replaceAll("-",""); // yuy76t5rew01.jpg fileName = uuid+fileName; //2 把文件按照日期進行分類 //獲取當前日期 // 2019/11/12 String datePath = new DateTime().toString("yyyy/MM/dd"); //拼接 // 2019/11/12/ewtqr313401.jpg fileName = datePath+"/"+fileName; //調用oss方法實現上傳 //第一個參數 Bucket名稱 //第二個參數 上傳到oss文件路徑和文件名稱 aa/bb/1.jpg //第三個參數 上傳文件輸入流 ossClient.putObject(bucketName,fileName , inputStream); // 關閉OSSClient。 ossClient.shutdown(); //把上傳之后文件路徑返回 //需要把上傳到阿里雲oss路徑手動拼接出來 // https://edu-guli-1010.oss-cn-beijing.aliyuncs.com/01.jpg String url = "https://"+bucketName+"."+endpoint+"/"+fileName; return url; }catch(Exception e) { e.printStackTrace(); return null; } } }
前端部分代碼
引入2個組件
<!-- 講師頭像:TODO --> <!-- 講師頭像 --> <el-form-item label="講師頭像"> <!-- 頭銜縮略圖 --> <pan-thumb :image="teacher.avatar"/> <!-- 文件上傳按鈕 --> <el-button type="primary" icon="el-icon-upload" @click="imagecropperShow=true">更換頭像 </el-button> <!-- v-show:是否顯示上傳組件 :key:類似於id,如果一個頁面多個圖片上傳控件,可以做區分 :url:后台上傳的url地址 @close:關閉上傳組件 @crop-upload-success:上傳成功后的回調 <input type="file" name="file"/> --> <image-cropper v-show="imagecropperShow" :width="300" :height="300" :key="imagecropperKey" :url="BASE_API+'/eduoss/fileoss'" field="file" @close="close" @crop-upload-success="cropSuccess"/> </el-form-item> import ImageCropper from '@/components/ImageCropper' import PanThumb from '@/components/PanThumb' export default { components: { ImageCropper, PanThumb }, data() { return { teacher:{ name: '', sort: 0, level: 1, career: '', intro: '', avatar: '' }, //上傳彈框組件是否顯示 imagecropperShow:false, imagecropperKey:0,//上傳組件key值 BASE_API:process.env.BASE_API, //獲取dev.env.js里面地址 saveBtnDisabled:false // 保存按鈕是否禁用, } }, created() { //頁面渲染之前執行 this.init() }, watch: { //監聽 $route(to, from) { //路由變化方式,路由發生變化,方法就會執行 this.init() } }, methods:{ close() { //關閉上傳彈框的方法 this.imagecropperShow=false this.imagecropperKey=this.imagecropperKey+1 }, //上傳成功方法 cropSuccess(data) { this.imagecropperShow=false //上傳之后接口返回圖片地址 this.teacher.avatar = data.url this.imagecropperKey=this.imagecropperKey+1 }, init() { //判斷路徑有id值,做修改 if(this.$route.params && this.$route.params.id) { //從路徑獲取id值 const id = this.$route.params.id //調用根據id查詢的方法 this.getInfo(id) } else { //路徑沒有id值,做添加 //清空表單 this.teacher = {} } }, //根據講師id查詢的方法 getInfo(id) { teacherApi.getTeacherInfo(id) .then(response => { this.teacher = response.data.teacher }) }, saveOrUpdate() { //判斷修改還是添加 //根據teacher是否有id if(!this.teacher.id) { //添加 this.saveTeacher() } else { //修改 this.updateTeacher() } }, //修改講師的方法 updateTeacher() { teacherApi.updateTeacherInfo(this.teacher) .then(response => { //提示信息 this.$message({ type: 'success', message: '修改成功!' }); //回到列表頁面 路由跳轉 this.$router.push({path:'/teacher/table'}) }) }, //添加講師的方法 saveTeacher() { teacherApi.addTeacher(this.teacher) .then(response => {//添加成功 //提示信息 this.$message({ type: 'success', message: '添加成功!' }); //回到列表頁面 路由跳轉 this.$router.push({path:'/teacher/table'}) }) } } } </script>