1、template中的内容
<el-upload
class="avatar-uploader"
action=""
:show-file-list="false"
:on-success="handleAvatarSuccess"
:http-request="Uploadfile"
>
<img
v-if="pictureUrl.trim() != ''"
:src="pictureUrl"
class="avatar"
/>
<i v-else class="el-icon-plus avatar-uploader-icon" />
</el-upload>
2、引入
<script src="http://gosspublic.alicdn.com/aliyun-oss-sdk-4.4.4.min.js"></script>
在第二个script中引入
import axios from "axios";
data中定义了在methods中使用,不定义也可下面直接let定义
sendData: null,
ossUrl: "",
accessUrl: "",
pictureUrl: "",
在methods中写
methods{
//自己编写的函数用于生成文件名,防止上传的文件重名 可以写也可以不写
getUUID() {
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
return (
c === "x" ? (Math.random() * 16) | 0 : "r&0x3" | "0x8"
).toString(16);
});
},
Uploadfile(param) {
console.log(param);
let file = param.file; // 得到文件的内容
console.log(file);
//填写获取签名的地址
const getPolicyApiUrl =
"http://dev.graphchain.top:1002/aliyun/oss/authority"; //获取oss签名的地址 这是后端的那个接口地址
// 获取oss签名
axios({
method: "get",
url: getPolicyApiUrl,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"Access-Control-Allow-Origin": "*",
},
}).then((response) => {
if (response.status == 200) {
let policyData = response.data;
console.log(policyData);
/**
ossUrl 换成自己的Bucket的外网地址,
例如 https://human-resource-manage.oss-cn-shenzhen.aliyuncs.com
*/
this.ossUrl =
"http://" + policyData.bucketName + "." + policyData.endpoint; //填写自己OSS服务器的地址
// this.from.iconFilename=this.getUUID()+ file.name // 上面写的getUUID这个方法 这一步可以可不写,我这是因为后端需要我传名字
// console.log( this.from.iconFilename)
let fileName = this.getUUID() + "." + file.name.split(".").pop();
console.log(fileName);
this.accessUrl = policyData.dirName + "/" + fileName; //设置上传的访问路径
this.sendData = new FormData(); // 上传文件的data参数
this.sendData.append("OSSAccessKeyId", policyData.accessKeyId);
this.sendData.append("policy", policyData.policy);
this.sendData.append("signature", policyData.signature);
// this.sendData.append("keys", policyData.dirName);
this.sendData.append("key", this.accessUrl); //上传的文件路径
this.sendData.append("success_action_status", 200); // 指定返回的状态码
// this.sendData.append("type", "this.");
this.sendData.append("file", file);
this.sendData.append("callback", policyData.callback);
this.sendData.append("name", fileName);
// console.log(sendData);
console.log(this.sendData);
//这是img的路径
// this.pictureUrl =
// this.ossUrl + "/" + policyData.dirName + "/" + file.name;
// console.log( this.pictureUrl)
this.from.iconFilename = fileName;
console.log(this.from.iconFilename);
axios.post(this.ossUrl, this.sendData).then((res) => {
this.pictureUrl = this.ossUrl + "/" + this.accessUrl; //获得到的url需要将其存数据库中
console.log(
"上传到阿里云的图片地址:" + this.ossUrl + "/" + this.accessUrl
);
});
}
});
},
}
如果遇到跨越问题看自己的地址是否和其他接口地址一致,可以连一下本地和线上试一下