1:利用http-request自定义上传去覆盖默认上传事件。
2:由于上传的格式是FormData格式,首先需要在请求拦截的地方配置,改掉请求头部分。需要后台配置,不然显示跨域。
axios.interceptors.request.use(
config => {
// 在这里加if语句判断,配置Content-Type 和 Access-Control-Allow-Origin
if (
config.headers &&
config.headers["Content-Type"] === "multipart/form-data"
) {
config.headers = {
"Content-Type": "multipart/form-data",
Authorization: token,
device: "wap",
Language: "zh-CN",
"Access-Control-Allow-Origin": "*"
};
} else {
if (typeof config.data !== "string") {
config.data = JSON.stringify(config.data);
}
config.headers = {
"Content-Type": "application/json",
Authorization: token,
device: "wap",
Language: "zh-CN"
};
}
return config;
},
error => {
return Promise.reject(error);
}
);
3:覆盖默认上传事件后,首先获取阿里的签名认证,再往接口里上传文件
aliaCustomReq(e) {
//这里获取阿里的签名认证
this.$get("ailiUrl").then(res => {
const serve = res;
// 传给后端的文件格式类型
const formData = new FormData();
let now = new Date().getTime();
//这一步是给fileList赋值,在做这个需求的时候,onchange拿到的参数不全,不建议用,建议在这里去赋值操作
let newFile = {};
for (let item in e.file) {
newFile[item] = e.file[item];
}
formData.append("key", serve.dir + now + "_" + e.file.name);
formData.append("OSSAccessKeyId", serve.accessid);
formData.append("policy", serve.policy);
formData.append("Signature", serve.signature);
formData.append("callback", serve.callback);
formData.append("success_action_status", "200");
formData.append("file", e.file);
//传递参数,改变请求头
this.$post(serve.host, formData, {
"Content-Type": "multipart/form-data"
}).then(data => {
if (data) {
newFile.url = data["host"] + "/" + data["filename"];
if (!this.fileList) {
this.fileList = [];
}
this.fileList.push(newFile);
}
});
});
}
4.下载功能 npm install ali-oss --save-dev 下载官网的包
AliPreview(file) {
this.$get("aliUrl").then(res => {
// 引入ali-oss文件
let OSS = require("ali-oss");
//https://help.aliyun.com/document_detail/111371.html 阿里云官方文档
let client = new OSS({
region: res.region,
accessKeyId: res.accessid,
accessKeySecret: res.accessKey,
bucket: res.bucket
});
let objName = file.url
.replace(res.host + "/", "")
.replace(res.customName + "/", "");
if (objName.includes("?")) {
objName = objName.substring(0, objName.indexOf("?"));
}
let url = client.signatureUrl(objName, {
response: {
"content-disposition": `attachment; filename=${file.name}`
}
});
url = url.replace(res.host, res.customName);
console.log(url, "下载地址");
//此处为手机预览 pc预览用window.open
window.location.href = url;
});
}
5.限制上传文件格式的话可在before-upload钩子函数里操作,