文章目錄
- ①. 品牌管理菜單
- ②. 快速顯示開關
- ③. 阿里云上傳概述
- ④. 使用代碼進行文件上傳
- ⑤. 結合Alibaba來管理oss
- ⑥. gulimall-third-party微服務
- ⑦. 服務端簽名后直傳
- ⑧. 結合前端實現文件直傳
①. 品牌管理菜單
-
①. 后臺:系統管理/菜單管理/新增
-
②. 將逆向工程product得到的resources\src\views\modules\product文件拷貝到gulimall/renren-fast-vue/src/views/modules/product目錄下’也就是下面的兩個文件
brand.vue : 顯示的表單
brand-add-or-update.vue:添加和更改功能
-
③. 但是顯示的頁面沒有新增和刪除功能’這是因為權限控制的原因
<el
-button v
-if="isAuth('product:brand:save')" type
="primary" @click="addOrUpdateHandle()">新增
</el
-button
>
<el
-button v
-if="isAuth('product:brand:delete')" type
="danger" @click="deleteHandle()" :disabled
="dataListSelections.length <= 0">批量刪除
</el
-button
>
- ④. 查看“isAuth”的定義位置:將方法的返回值返回true,然后再次刷新頁面(也可以將v-if注釋掉)
- ⑤. 注釋掉檢測語法
build/webpack.base.conf.js 中注釋掉createLintingRule()函數體’不進行lint語法檢查
②. 快速顯示開關
- ①. 實現的效果如下
- ②. 前臺頁面(參照elementui進行顯示)
<el-table-columnprop="showStatus"header-align="center"align="center"label="顯示狀態"width="200"><template slot-scope="scope"><el-switchv-model="scope.row.showStatus"active-color="#13ce66"inactive-color="#ff4949":active-value="1":inactive-value="0"@change="updateBrandStatus(scope.row)"></el-switch></template>
</el-table-column>
updateBrandStatus(data) {console
.log("最新狀態", data
);let { brandId
, showStatus
} = data
;this.$http({url: this.$http
.adornUrl("/product/brand/update"),method: "post",data: this.$http
.adornData({ brandId
, showStatus
}, false)}).then(({ data }) => {this.$message({message: "狀態更新成功",type: "success"});});
},
@RestController
@RequestMapping("product/brand")
public class BrandController {@RequestMapping("/update")public R update(@RequestBody BrandEntity brand
){brandService
.updateById(brand
);return R.ok();}
@Data
@TableName("pms_brand")
public class BrandEntity implements Serializable {private static final long serialVersionUID
= 1L;@TableIdprivate Long brandId
;private String name
;private String logo
;private String descript
;private Integer showStatus
;private String firstLetter
;private Integer sort
;
}
- ④. 在新增或者修改的時候也要將按鈕進行修改
brand-add-or-update.vue
<el-form-item label="顯示狀態" prop="showStatus"><el-switch v-model="dataForm.showStatus"active-color="#13ce66"inactive-color="#ff4949":active-value="1":inactive-value="0"></el-switch>
</el-form-item>
③. 阿里云上傳概述
-
①. 阿里云上使使用對象存儲方式:
-
②. 創建Bucket,我們的Bucket名稱叫 gulimall-tangzhi
-
③. 上傳文件:上傳成功后’取得圖片的URL
這種方式是手動上傳圖片’實際上我們可以在程序中設置自動上傳圖片到阿里云對象存
-
④. 我們后續將采用下面的方式進行圖片的儲存
④. 使用代碼進行文件上傳
-
①. 簡單文件上傳OSS官方文檔
-
②. 添加依賴包,查看官方代碼
<dependency><groupId>com.aliyun.oss
</groupId><artifactId>aliyun-sdk-oss
</artifactId><version>3.8.0
</version>
</dependency>
String endpoint
= "http://oss-cn-hangzhou.aliyuncs.com";
String accessKeyId
= "<yourAccessKeyId>";
String accessKeySecret
= "<yourAccessKeySecret>";
OSS ossClient
= new OSSClientBuilder().build(endpoint
, accessKeyId
, accessKeySecret
);
InputStream inputStream
= new FileInputStream("<yourlocalFile>");
ossClient
.putObject("<yourBucketName>", "<yourObjectName>", inputStream
);
ossClient
.shutdown();
@Testpublic void upload()throws Exception{String endpoint
= "oss-cn-guangzhou.aliyuncs.com";String accessKeyId
= "LTAI5t7E9sokgukBNzP45nX1";String accessKeySecret
= "yKzdbTeQETI4u9okOAPDvSscEa5pVT";OSS ossClient
= new OSSClientBuilder().build(endpoint
, accessKeyId
, accessKeySecret
);InputStream inputStream
= new FileInputStream("C:\\Users\\Administrator\\Desktop\\car.jpg");ossClient
.putObject("gulimall-tangzhi", "car.jpg", inputStream
);ossClient
.shutdown();}
- ③. endpoint指的是什么?
- ④. accessKeyId和accessKeySecret指的是什么?
步驟
(1). accessKeyId和accessKeySecret需要創建一個RAM賬號:
(2). 創建用戶完畢后’會得到一個“AccessKey ID”和“AccessKeySecret”'然后復制這兩個值到代碼的“AccessKey ID”和“AccessKeySecret”。另外還需要添加訪問控制權限:
- ⑤. 我們在項目中使用的是SpringCloud Alibaba來管理oss,后續會進行介紹
⑤. 結合Alibaba來管理oss
Add dependency aliyun-oss-spring-boot-starter in the pom.xml file in your Spring Boot project.Configure accessKeyId, secretAccessKey and region in application.properties.
<dependency><groupId>com.alibaba.cloud
</groupId><artifactId>aliyun-oss-spring-boot-starter
</artifactId>
</dependency>
alibaba
.cloud
.access
-key
=your
-ak
alibaba
.cloud
.secret
-key
=your
-sk
alibaba
.cloud
.oss
.endpoint
=***
-
③. 我們在common工程中引入oss的依賴
-
④. 在product工程中進行測試
spring:cloud:alicloud:access-key: LTAI5t7E9sokgukBNzP45nX1
secret-key: yKzdbTeQETI4u9okOAPDvSscEa5pVT
oss:endpoint: oss
-cn
-guangzhou.aliyuncs.com
@Resource
OSSClient ossClient
;@Test
public void uploadCloudAlibaba()throws Exception{InputStream inputStream
= new FileInputStream("C:\\Users\\Administrator\\Desktop\\car2.jpg");ossClient
.putObject("gulimall-tangzhi", "car2.jpg", inputStream
);
}
- ⑤. 但是這樣來做還是比較麻煩’如果以后的上傳任務都交給gulimall-product來完成’顯然耦合度高。最好單獨新建一個Module來完成文件上傳任務
⑥. gulimall-third-party微服務
- ①. 環境配置如下
因為在common工程中引入了mybatis-plus,我們這個gulimall-third-party服務將其依賴進行排除掉
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0
</modelVersion><parent><groupId>org.springframework.boot
</groupId><artifactId>spring-boot-starter-parent
</artifactId><version>2.1.8.RELEASE
</version><relativePath/> </parent><groupId>com.atguigu.gulimall
</groupId><artifactId>gulimall-third-party
</artifactId><version>0.0.1-SNAPSHOT
</version><name>gulimall-third-party
</name><description>第三方服務
</description><properties><java.version>1.8
</java.version><spring-cloud.version>Greenwich.SR3
</spring-cloud.version></properties><dependencies><dependency><groupId>com.atguigu.gulimall
</groupId><artifactId>gulimall-common
</artifactId><version>0.0.1-SNAPSHOT
</version><exclusions><exclusion><groupId>com.baomidou
</groupId><artifactId>mybatis-plus-boot-starter
</artifactId></exclusion></exclusions></dependency><dependency><groupId>org.springframework.boot
</groupId><artifactId>spring-boot-starter-web
</artifactId></dependency><dependency><groupId>org.springframework.cloud
</groupId><artifactId>spring-cloud-starter-openfeign
</artifactId></dependency><dependency><groupId>com.alibaba.cloud
</groupId><artifactId>spring-cloud-starter-alicloud-oss
</artifactId></dependency><dependency><groupId>org.springframework.boot
</groupId><artifactId>spring-boot-starter-test
</artifactId><scope>test
</scope><exclusions><exclusion><groupId>org.junit.vintage
</groupId><artifactId>junit-vintage-engine
</artifactId></exclusion></exclusions></dependency></dependencies><dependencyManagement><dependencies><dependency><groupId>org.springframework.cloud
</groupId><artifactId>spring-cloud-dependencies
</artifactId><version>${spring-cloud.version}
</version><type>pom
</type><scope>import
</scope></dependency><dependency><groupId>com.alibaba.cloud
</groupId><artifactId>spring-cloud-alibaba-dependencies
</artifactId><version>2.1.0.RELEASE
</version><type>pom
</type><scope>import
</scope></dependency></dependencies></dependencyManagement><build><plugins><plugin><groupId>org.springframework.boot
</groupId><artifactId>spring-boot-maven-plugin
</artifactId></plugin></plugins></build><repositories><repository><id>spring-milestones
</id><name>Spring Milestones
</name><url>https://repo.spring.io/milestone
</url></repository></repositories>
</project>
- ②. bootstrap.properties配置nacos配置中心
spring
.application
.name
=gulimall
-third
-party
spring
.cloud
.nacos
.config
.server
-addr
=127.0.0.1:
8848
spring
.cloud
.nacos
.config
.namespace
=39e31ec7
-194c
-4741-b4f2
-2b65142c2100
spring
.cloud
.nacos
.config
.ext
-config
[0].data-id
=oss
.yml
spring
.cloud
.nacos
.config
.ext
-config
[0].group=DEFAULT_GROUP
spring
.cloud
.nacos
.config
.ext
-config
[0].refresh
=true
spring:cloud:nacos:discovery:server-addr: 127.0.0.1
:8848alicloud:access-key: LTAI5t7E9sokgukBNzP45nX1
secret-key: yKzdbTeQETI4u9okOAPDvSscEa5pVT
oss:endpoint: oss
-cn
-guangzhou.aliyuncs.com
bucket: gulimall
-tangzhi
application:name: gulimall
-third
-party
server:port: 30000
spring:cloud:gateway:routes:- id: third_party_route
uri: lb
://gulimall
-third
-party
predicates:- Path=/api/thirdparty/
**filters:- RewritePath=/api/thirdparty/(
?<segment
>/
?.
*), /$\
{segment
}
- ⑤. 對gulimall-third-party進行功能測試
@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest
public class GulimallThirdPartyApplicationTests {@AutowiredOSSClient ossClient
;@Testpublic void uploadCloudAlibaba()throws Exception{InputStream inputStream
= new FileInputStream("C:\\Users\\Administrator\\Desktop\\car2.jpg");ossClient
.putObject("gulimall-tangzhi", "car3.jpg", inputStream
);}
}
⑦. 服務端簽名后直傳
@RestController
public class OssController {@AutowiredOSS ossClient
;@Value("${spring.cloud.alicloud.oss.endpoint}")private String endpoint
;@Value("${spring.cloud.alicloud.oss.bucket}")private String bucket
;@Value("${spring.cloud.alicloud.access-key}")private String accessId
;@RequestMapping("/oss/policy")public R policy() {String host
= "https://" + bucket
+ "." + endpoint
;
String format
= new SimpleDateFormat("yyyy-MM-dd").format(new Date());String dir
= format
+ "/"; Map<String, String> respMap
= null;try {long expireTime
= 30;long expireEndTime
= System.currentTimeMillis() + expireTime
* 1000;Date expiration
= new Date(expireEndTime
);PolicyConditions policyConds
= new PolicyConditions();policyConds
.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE
, 0, 1048576000);policyConds
.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY
, dir
);String postPolicy
= ossClient
.generatePostPolicy(expiration
, policyConds
);byte[] binaryData
= postPolicy
.getBytes("utf-8");String encodedPolicy
= BinaryUtil.toBase64String(binaryData
);String postSignature
= ossClient
.calculatePostSignature(postPolicy
);respMap
= new LinkedHashMap<String, String>();respMap
.put("accessid", accessId
);respMap
.put("policy", encodedPolicy
);respMap
.put("signature", postSignature
);respMap
.put("dir", dir
);respMap
.put("host", host
);respMap
.put("expire", String.valueOf(expireEndTime
/ 1000));} catch (Exception e
) {System.out
.println(e
.getMessage());}return R.ok().put("data",respMap
);}
}
⑧. 結合前端實現文件直傳
policy.js封裝一個Promise’發送/thirdparty/oss/policy請求。vue項目會自動加上api前綴multiUpload.vue多文件上傳。要改’改方式如下singleUpload.vue單文件上傳。要替換里面的action中的內容。
action=“http://gulimall-tangzhi.oss-cn-guangzhou.aliyuncs.com”
<template> <div><el
-uploadaction
="http://gulimall-tangzhi.oss-cn-guangzhou.aliyuncs.com":data
="dataObj"list
-type
="picture":multiple
="false" :show
-file
-list
="showFileList":file
-list
="fileList":before
-upload
="beforeUpload":on
-remove
="handleRemove":on
-success
="handleUploadSuccess":on
-preview
="handlePreview"><el
-button size
="small" type
="primary">點擊上傳
</el
-button
><div slot
="tip" class="el-upload__tip">只能上傳jpg
/png文件'且不超過
10MB
</div
></el
-upload
><el
-dialog
:visible
.sync
="dialogVisible"><img width
="100%" :src
="fileList[0].url" alt
=""></el
-dialog
></div
>
</template
>
<script>import {policy
} from '
./policy'
import { getUUID
} from '@
/utils'export
default {name
: 'singleUpload'
,props
: {value
: String},computed
: {imageUrl() {return this.value
;},imageName() {if (this.value
!= null && this.value
!== ''
) {return this.value
.substr(this.value
.lastIndexOf("/") + 1);} else {return null;}},fileList() {return [{name
: this.imageName
,url
: this.imageUrl
}]},showFileList
: {get
: function
() {return this.value
!== null && this.value
!== ''
&& this.value
!==undefined
;},set
: function
(newValue
) {}}},data() {return {dataObj
: {policy
: ''
,signature
: ''
,key
: ''
,ossaccessKeyId
: ''
,dir
: ''
,host
: ''
,},dialogVisible
: false};},methods
: {emitInput(val
) {this.$
emit('input', val
)},handleRemove(file
, fileList
) {this.emitInput(''
);},handlePreview(file
) {this.dialogVisible
= true;},beforeUpload(file
) {let _self
= this;return new Promise((resolve
, reject
) => {policy().then(response
=> {_self
.dataObj
.policy
= response
.data
.policy
;_self
.dataObj
.signature
= response
.data
.signature
;_self
.dataObj
.ossaccessKeyId
= response
.data
.accessid
;_self
.dataObj
.key
= response
.data
.dir
+getUUID()+'_$
{filename
}'
;_self
.dataObj
.dir
= response
.data
.dir
;_self
.dataObj
.host
= response
.data
.host
;resolve(true)}).catch(err
=> {reject(false)})})},handleUploadSuccess(res
, file
) {console
.log("上傳成功...")this.showFileList
= true;this.fileList
.pop();this.fileList
.push({name
: file
.name
, url
: this.dataObj
.host
+ '/' + this.dataObj
.key
.replace("${filename}",file
.name
) });this.emitInput(this.fileList
[0].url
);}}}
</script
>
<style>
</style
>
<template><div><el
-uploadaction
="http://gulimall-tangzhi.oss-cn-guangzhou.aliyuncs.com":data
="dataObj"list
-type
="picture-card":file
-list
="fileList":before
-upload
="beforeUpload":on
-remove
="handleRemove":on
-success
="handleUploadSuccess":on
-preview
="handlePreview":limit
="maxCount":on
-exceed
="handleExceed"><i
class="el-icon-plus"></i
></el
-upload
><el
-dialog
:visible
.sync
="dialogVisible"><img width
="100%" :src
="dialogImageUrl" alt
/></el
-dialog
></div
>
</template
>
<script>
import { policy
} from
"./policy";
import { getUUID
} from
"@/utils";
export
default {name
: "multiUpload",props
: {value
: Array,maxCount
: {type
: Number,default: 30}},data() {return {dataObj
: {policy
: "",signature
: "",key
: "",ossaccessKeyId
: "",dir
: "",host
: "",uuid
: ""},dialogVisible
: false,dialogImageUrl
: null};},computed
: {fileList() {let fileList
= [];for (let i
= 0; i
< this.value
.length
; i
++) {fileList
.push({ url
: this.value
[i
] });}return fileList
;}},mounted() {},methods
: {emitInput(fileList
) {let value
= [];for (let i
= 0; i
< fileList
.length
; i
++) {value
.push(fileList
[i
].url
);}this.$
emit("input", value
);},handleRemove(file
, fileList
) {this.emitInput(fileList
);},handlePreview(file
) {this.dialogVisible
= true;this.dialogImageUrl
= file
.url
;},beforeUpload(file
) {let _self
= this;return new Promise((resolve
, reject
) => {policy().then(response
=> {console
.log("這是什么${filename}");_self
.dataObj
.policy
= response
.data
.policy
;_self
.dataObj
.signature
= response
.data
.signature
;_self
.dataObj
.ossaccessKeyId
= response
.data
.accessid
;_self
.dataObj
.key
=response
.data
.dir
+ "/" + getUUID() + "_${filename}";_self
.dataObj
.dir
= response
.data
.dir
;_self
.dataObj
.host
= response
.data
.host
;resolve(true);}).catch(err
=> {console
.log("出錯了...", err
);reject(false);});});},handleUploadSuccess(res
, file
) {this.fileList
.push({name
: file
.name
,url
:this.dataObj
.host
+"/" +this.dataObj
.key
.replace("${filename}", file
.name
)});this.emitInput(this.fileList
);},handleExceed(files
, fileList
) {this.$
message({message
: "最多只能上傳" + this.maxCount
+ "張圖片",type
: "warning",duration
: 1000});}}
};
</script
>
<style></style
>
import http from '@
/utils
/httpRequest
.js'
export function
policy() {return new Promise((resolve
,reject
)=>{http({url
: http
.adornUrl("/thirdparty/oss/policy"),method
: "get",params
: http
.adornParams({})}).then(({ data
}) => {resolve(data
);})});
}
<el
-table
-column prop
="logo" header
-align
="center" align
="center" label
="品牌logo地址"><template slot
-scope
="scope"><!-- 自定義表格
+自定義圖片
--><img
:src
="scope.row.logo" style
="width: 100px; height: 80px" /></template
>
</el
-table
-column
>
總結
以上是生活随笔為你收集整理的商城项目09_品牌管理菜单、快速显示开关、阿里云进行文件上传、结合Alibaba管理OSS、服务端签名后直传的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。