| |
|
|
开发:
C++知识库
Java知识库
JavaScript
Python
PHP知识库
人工智能
区块链
大数据
移动开发
嵌入式
开发工具
数据结构与算法
开发测试
游戏开发
网络协议
系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程 数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁 |
| -> Java知识库 -> 阿里云文件存(oss)储服务端签名后直传 -> 正文阅读 |
|
|
[Java知识库]阿里云文件存(oss)储服务端签名后直传 |
1.导入相应坐标<dependencyManagement>
<dependencies>
<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>
dependencies>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alicloud-oss</artifactId>
</dependency>?
</dependencies>
*springboot所需坐标没有在此处展示 2.在yml文件中配置如下:spring:
cloud:
alicloud:
access-key: 输入自己的ak
secret-key: 输入自己的sk
oss:
endpoint: 输入你服务器的区域地址
bucket: 桶
3.后端接口如下:package com.zg.gulimall.controller;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.zg.common.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;
@RestController
public class OssController {
@Autowired
private OSS 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;
@GetMapping("/oss/policy")
public R policy() {
// 填写Host地址,格式为https://bucketname.endpoint。
String host = "https://"+bucket+"."+endpoint;
// 设置上传回调URL,即回调服务器地址,用于处理应用服务器与OSS之间的通信。OSS会在文件上传完成后,把文件上传信息通过此回调URL发送给应用服务器。
// String callbackUrl = "https://192.168.0.0:8888";
// 设置上传到OSS文件的前缀,可置空此项。置空后,文件将上传至Bucket的根目录下。
String format = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
String dir = format+"/";
try {
long expireTime = 600;
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);
Map<String, String> 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));
return R.ok().put("data", respMap);
} catch (Exception e) {
// Assert.fail(e.getMessage());
System.out.println(e.getMessage());
}
return null;
}
}
4.前端代码如下<template>? ? <div> ? ? <el-upload ? ? ? action="http://gulimall-brand-lz.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 => { ? ? ? ? ? ? console.log("响应的数据",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; ? ? ? ? ? ? console.log("响应的数据222。。。",_self.dataObj); ? ? ? ? ? ? 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> 总结该文主要由学习谷粒商城项目的实践过程,技术难度并不大,阿里云官网有文档可以查阅。 |
|
|
|
|
| 上一篇文章 下一篇文章 查看所有文章 |
|
|
开发:
C++知识库
Java知识库
JavaScript
Python
PHP知识库
人工智能
区块链
大数据
移动开发
嵌入式
开发工具
数据结构与算法
开发测试
游戏开发
网络协议
系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程 数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁 |
| 360图书馆 购物 三丰科技 阅读网 日历 万年历 2025年12日历 | -2025/12/15 15:55:31- |
|
| 网站联系: qq:121756557 email:121756557@qq.com IT数码 |