日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

商城项目09_品牌管理菜单、快速显示开关、阿里云进行文件上传、结合Alibaba管理OSS、服务端签名后直传

發布時間:2024/3/12 编程问答 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 商城项目09_品牌管理菜单、快速显示开关、阿里云进行文件上传、结合Alibaba管理OSS、服务端签名后直传 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

文章目錄

  • ①. 品牌管理菜單
  • ②. 快速顯示開關
  • ③. 阿里云上傳概述
  • ④. 使用代碼進行文件上傳
  • ⑤. 結合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;/* 品牌id */@TableIdprivate Long brandId;/*** 品牌名 */private String name;/*** 品牌logo地址 */private String logo;/*** 介紹 */private String descript;/*** 顯示狀態[0-不顯示;1-顯示]*/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> // Endpoint以杭州為例'其它Region請按實際情況填寫。 String endpoint = "http://oss-cn-hangzhou.aliyuncs.com"; // 云賬號AccessKey有所有API訪問權限'建議遵循阿里云安全最佳實踐'創建并使用RAM子賬號進行API訪問或日常運維'請登錄 https://ram.console.aliyun.com 創建。 String accessKeyId = "<yourAccessKeyId>"; String accessKeySecret = "<yourAccessKeySecret>";// 創建OSSClient實例。 OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);// 上傳文件流。 InputStream inputStream = new FileInputStream("<yourlocalFile>"); ossClient.putObject("<yourBucketName>", "<yourObjectName>", inputStream);// 關閉OSSClient。 ossClient.shutdown(); @Testpublic void upload()throws Exception{// yourEndpoint填寫Bucket所在地域對應的Endpoint。以華東1(杭州)為例'Endpoint填寫為https://oss-cn-hangzhou.aliyuncs.com。String endpoint = "oss-cn-guangzhou.aliyuncs.com";// 阿里云賬號AccessKey擁有所有API的訪問權限'風險很高。強烈建議您創建并使用RAM用戶進行API訪問或日常運維'請登錄RAM控制臺創建RAM用戶。String accessKeyId = "LTAI5t7E9sokgukBNzP45nX1";String accessKeySecret = "yKzdbTeQETI4u9okOAPDvSscEa5pVT";// 創建OSSClient實例。OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);// 填寫本地文件的完整路徑。如果未指定本地路徑'則默認從示例程序所屬項目對應本地路徑中上傳文件流。InputStream inputStream = new FileInputStream("C:\\Users\\Administrator\\Desktop\\car.jpg");// 依次填寫Bucket名稱(例如examplebucket)和Object完整路徑(例如exampledir/exampleobject.txt)。Object完整路徑中不能包含Bucket名稱。ossClient.putObject("gulimall-tangzhi", "car.jpg", inputStream);// 關閉OSSClient。ossClient.shutdown();}

  • ③. endpoint指的是什么?
  • ④. accessKeyId和accessKeySecret指的是什么?

步驟
(1). accessKeyId和accessKeySecret需要創建一個RAM賬號:

(2). 創建用戶完畢后’會得到一個“AccessKey ID”和“AccessKeySecret”'然后復制這兩個值到代碼的“AccessKey ID”和“AccessKeySecret”。另外還需要添加訪問控制權限:

  • ⑤. 我們在項目中使用的是SpringCloud Alibaba來管理oss,后續會進行介紹

⑤. 結合Alibaba來管理oss

  • ①. 使用SpringCloud 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> // application.properties alibaba.cloud.access-key=your-ak alibaba.cloud.secret-key=your-sk alibaba.cloud.oss.endpoint=***
    • ③. 我們在common工程中引入oss的依賴

    • ④. 在product工程中進行測試

    # DataSource Config spring:cloud:alicloud:access-key: LTAI5t7E9sokgukBNzP45nX1secret-key: yKzdbTeQETI4u9okOAPDvSscEa5pVToss: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");// 依次填寫Bucket名稱(例如examplebucket)和Object完整路徑(例如exampledir/exampleobject.txt)。Object完整路徑中不能包含Bucket名稱。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/> <!-- lookup parent from repository --></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
    • ③. application.yaml
    spring:cloud:nacos:discovery:server-addr: 127.0.0.1:8848alicloud:access-key: LTAI5t7E9sokgukBNzP45nX1secret-key: yKzdbTeQETI4u9okOAPDvSscEa5pVToss:endpoint: oss-cn-guangzhou.aliyuncs.combucket: gulimall-tangzhiapplication:name: gulimall-third-party server:port: 30000
    • ④. 網關的設置
    spring:cloud:gateway:routes:- id: third_party_routeuri: lb://gulimall-third-partypredicates:- 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");// 依次填寫Bucket名稱(例如examplebucket)和Object完整路徑(例如exampledir/exampleobject.txt)。Object完整路徑中不能包含Bucket名稱。ossClient.putObject("gulimall-tangzhi", "car3.jpg", inputStream);} }

    ⑦. 服務端簽名后直傳

    • ①. 服務端簽名后直傳

    • ②. 背景
      采用JavaScript客戶端直接簽名(參見JavaScript客戶端簽名直傳)時’AccessKey ID和AcessKey Secret會暴露在前端頁面’因此存在嚴重的安全隱患。因此’OSS提供了服務端簽名后直傳的方案。

    • ③. 流程介紹

    • ④. 編寫核心controller
      http://localhost:88/api/thirdparty/oss/policy

    @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() {//https://gulimall-hello.oss-cn-beijing.aliyuncs.com/hahaha.jpgString host = "https://" + bucket + "." + endpoint; // host的格式為 bucketname.endpoint// callbackUrl為 上傳回調服務器的URL'請將下面的IP和Port配置為您自己的真實信息。 // String callbackUrl = "http://88.88.88.88:8888";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));// respMap.put("expire", formatISO8601Date(expiration));} catch (Exception e) {// Assert.fail(e.getMessage());System.out.println(e.getMessage());}return R.ok().put("data",respMap);} }

    ⑧. 結合前端實現文件直傳

    • ①. 這里提供了三個js文件,直接導入項目即可
  • 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: '',// callback:'',},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.dir + "/" + file.name; 替換${filename}為真正的文件名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);})}); }
    • ②. 點擊文件上傳,出現了跨域,在oss官方文檔有強調說明,一定要設置跨越

    • ③. 顯示圖片

    <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、服务端签名后直传的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。