feat: update upload method

This commit is contained in:
JimQing 2020-09-12 16:53:52 +08:00 committed by yanglbme
parent f75a197d74
commit 2abf62cec9
4 changed files with 99 additions and 42 deletions

View File

@ -11,7 +11,9 @@
"test:unit": "vue-cli-service test:unit" "test:unit": "vue-cli-service test:unit"
}, },
"dependencies": { "dependencies": {
"ali-oss": "^6.10.0",
"axios": "^0.19.1", "axios": "^0.19.1",
"buffer-from": "^1.1.1",
"codemirror": "^5.50.2", "codemirror": "^5.50.2",
"core-js": "^3.4.4", "core-js": "^3.4.4",
"element-ui": "^2.13.0", "element-ui": "^2.13.0",

View File

@ -5,28 +5,72 @@ import {
} from 'uuid'; } from 'uuid';
function fileUpload(content, filename) { function fileUpload(content, filename) {
const fileUploadType = store.state.imgHost;
const activeKey = fileUploadType !== 'default' && localStorage.getItem(`${fileUploadType}Config`)
? fileUploadType : 'default';
switch (activeKey) {
case 'aliOSS':
return aliOSSUploadFile(content, filename);
case 'default':
return githubUploadFile(content, filename);
case 'github':
return githubUploadFile(content, filename);
default:
break;
}
}
/**
* github 图片上传
* @param {*} content
* @param {*} filename
*/
function githubUploadFile(content, filename) {
const githubResourceUrl = 'raw.githubusercontent.com/filess/images/master/';
const cdnResourceUrl = 'cdn.jsdelivr.net/gh/filess/images/';
const { const {
method, method,
token, headers,
url url
} = store.getters['imageApi/config']; } = store.getters['imageApi/config'];
const uuid = uuidv4(); const dateFilename = new Date().getTime() + '-' + uuidv4() + '.' + filename.split('.')[1];
const dateFilename = new Date().getTime() + '-' + uuid + '.' + filename.split('.')[1];
const uploadUrl = url + dateFilename; const uploadUrl = url + dateFilename;
return fetch({ return fetch({
url: uploadUrl, url: uploadUrl,
method, method,
headers: { headers,
'Authorization': 'token ' + token
},
data: { data: {
message: 'Upload image by https://doocs.github.io/md', message: 'Upload image by https://doocs.github.io/md',
content: content content: content
} }
}) }).then(res=> {
const imageUrl = res.content.download_url.replace(githubResourceUrl, cdnResourceUrl);
return imageUrl;
});
} }
function aliOSSUploadFile(content, filename) {
debugger;
const config = store.getters['imageApi/config'];
const dateFilename = new Date().getTime() + '-' + uuidv4() + '.' + filename.split('.')[1];
const dir = config.dir + '/' + dateFilename;
const Buffer = require('buffer-from')
const buffer = Buffer(content, 'base64');
const OSS = require('ali-oss');
try {
const client = new OSS(config);
return client.put(dir, buffer).then(res=> {
console.log('aliOSSUoladFile', res);
return res.url;
})
} catch (e) {
return Promise.reject(e);
}
}
export default { export default {
fileUpload fileUpload

View File

@ -1,24 +1,20 @@
import fileApi from '../../api/file'; import fileApi from '../../api/file';
const githubResourceUrl = 'raw.githubusercontent.com/filess/images/master/';
const cdnResourceUrl = 'cdn.jsdelivr.net/gh/filess/images/';
export function uploadImgFile(file) { export function uploadImgFile(file) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const checkImageResult = isImageIllegal(file); const checkImageResult = isImageIllegal(file);
if (checkImageResult) { if (checkImageResult) {
reject(checkImageResult); reject(checkImageResult);
return; return;
} }
const imgFile = new FileReader(); const base64Reader = new FileReader();
imgFile.readAsDataURL(file); base64Reader.readAsDataURL(file);
imgFile.onload = function () { base64Reader.onload = function () {
const base64Content = this.result.split(',').pop(); const base64Content = this.result.split(',').pop();
fileApi.fileUpload(base64Content, file.name).then(res => { fileApi.fileUpload(base64Content, file.name).then(res => {
const imageUrl = res.content.download_url.replace(githubResourceUrl, cdnResourceUrl); resolve(res);
resolve(imageUrl);
}).catch(err => { }).catch(err => {
reject(err.message) reject(err.message)
}) })

View File

@ -15,39 +15,54 @@ const state = {
'a4b581732e1c1507458doocsmdc5b223b27dae5e2e16a55' 'a4b581732e1c1507458doocsmdc5b223b27dae5e2e16a55'
] ]
}, },
aliOSS: {
bucket: '<Your BucketName>',
// region以杭州为例oss-cn-hangzhou其他region按实际情况填写。
region: '<Your Region>',
// 阿里云主账号AccessKey拥有所有API的访问权限风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维请登录RAM控制台创建RAM账号。
accessKeyId: '<Your AccessKeyId>',
accessKeySecret: '<Your AccessKeySecret>',
},
qiniuCloud: {} qiniuCloud: {}
}; };
const getters = { const getters = {
config(state) { config(state) {
let token, username, repo, method; const date = new Date();
const dir = date.getFullYear() + '/' + (date.getMonth() + 1).toString().padStart(2, '0') + '/' + date.getDate().toString().padStart(2, '0');
const activeKey = state.imgHost !== 'default' && localStorage.getItem(`${state.imgHost}Config`) ? state.imgHost : 'default'; const activeKey = state.imgHost !== 'default' && localStorage.getItem(`${state.imgHost}Config`) ? state.imgHost : 'default';
switch (activeKey) { switch (activeKey) {
case 'github': case 'aliOSS':
const githubConfg = JSON.parse(localStorage.getItem("githubConfig")); return {
const repoUrl = githubConfg.repo.replace("https://github.com/", "").replace("http://github.com/", "").replace("github.com/", "").split("/"); ...state.aliOSS,
token = githubConfg.accessToken; dir
username = repoUrl[0]; };
repo = repoUrl[1];
method = 'put';
break;
case 'qiniuCloud': case 'qiniuCloud':
break; return {
default: };
token = state.default.accessToken[Math.floor(Math.random() * state.default.accessToken.length)].replace('doocsmd', ''); case 'github':
username = state.default.username; const githubConfig = JSON.parse(localStorage.getItem("githubConfig"));
repo = state.default.repo; const repoUrl = githubConfig.repo.replace("https://github.com/", "").replace("http://github.com/", "").replace("github.com/", "").split("/");
method = state.default.method; const username = repoUrl[0];
break; const repo = repoUrl[1];
}
const date = new Date();
const dir = date.getFullYear() + '/' + (date.getMonth() + 1).toString().padStart(2, '0') + '/' + date.getDate().toString().padStart(2, '0');
const url = `https://api.github.com/repos/${username}/${repo}/contents/${dir}/`;
return { return {
method, method: 'put',
token, headers: {
url 'Authorization': 'token ' + githubConfig.accessToken
},
url: `https://api.github.com/repos/${username}/${repo}/contents/${dir}/`
};
default:
const token = state.default.accessToken[Math.floor(Math.random() * state.default.accessToken.length)].replace('doocsmd', '');
return {
method: state.default.method,
headers: {
'Authorization': 'token ' + token
},
url: `https://api.github.com/repos/${state.default.username}/${state.default.repo}/contents/${dir}/`
};
} }
} }
}; };