env.js
module.exports = {
development: {
apiUrl: "http://192.168.212.13:8010",
socketUrl: "http://192.168.212.13:9099"
},
debug: {
apiUrl: "http://192.168.212.13:8010",
socketUrl: "http://192.168.212.13:9099"
},
test: {
apiUrl: "http://192.168.212.63:8010",
socketUrl: "http://192.168.212.63:9099"
},
production: {
apiUrl: "http://183.240.131.12:8010",
socketUrl: "http://183.240.131.12:9099"
}
};
http.js
import Vue from 'vue'
import axios from 'axios';
import QS from 'qs';
import router from '../router'
import apiUrl from './env';
axios.defaults.baseURL = apiUrl[process.env.NODE_ENV].apiUrl
const pending = {}
const CancelToken = axios.CancelToken
const removePending = (key, isRequest = false) => {
if (pending[key] && isRequest) {
pending[key]('取消重复请求')
}
delete pending[key]
}
const getRequestIdentify = (config, isReuest = false) => {
let url = config.url
if (isReuest) {
url = config.baseURL + config.url.substring(1, config.url.length)
}
return config.method === 'get' ? encodeURIComponent(url + JSON.stringify(config.params)) : encodeURIComponent(config.url + JSON.stringify(config.data))
}
let [oldServer, newServer] = [null, null];
const env = process.env.NODE_ENV
let windowLoadingcontrol = null;
let windowAjaxTime = {
start: null,
end: null
};
axios.interceptors.request.use(config => {
windowAjaxTime.start = new Date().getTime();
const token = 1;
if (token) {
config.headers.Authorization = 'Bearer ' + token;
}
return config;
}, error => {
return Promise.error(error);
})
axios.interceptors.response.use(response => {
clearTimeout(windowLoadingcontrol);
windowLoadingcontrol = setTimeout(() => {
}, 300);
const resData = response.data;
if (Number(resData.code) === 200) {
windowAjaxTime.end = new Date().getTime();
response.data.resTime = windowAjaxTime.end - windowAjaxTime.start;
return Promise.resolve(response);
} else {
Vue.prototype.$message.error(resData.message)
return Promise.reject(response);
}
}, (error) => {
if (error.response.status === 401 || error.response.status === 401) {
Vue.prototype.$message.error("账号过期,请重新登录");
removeStore({ name: 'access_token' });
removeStore({ name: 'userInfo' });
router.replace({
path: '/login',
query: {
redirect: router.currentRoute.fullPath
}
});
this.$socket.close();
} else {
Vue.prototype.$message.error(error.response.data.message || "服务出错了,请稍后再试")
}
return Promise.reject(error)
})
function get(url, params) {
const dealObjectValue = (obj) => {
let param = {};
if (obj === null || obj === undefined || obj === "") return param;
for (let key in obj) {
if (Array.isArray(obj[key])) {
const arr = obj[key].find((item) => {
if (item !== null && item !== undefined && item !== "") return item
})
if (arr) {
param[key] = obj[key];
}
} else if (obj[key] instanceof Object) {
param[key] = dealObjectValue(obj[key]);
} else if (obj[key] !== null && obj[key] !== undefined && obj[key] !== "") {
param[key] = obj[key];
}
}
return param;
};
const newParams = dealObjectValue(params);
return new Promise((resolve, reject) => {
axios.get(url, {
params: newParams,
paramsSerializer: function (params) {
return QS.stringify(params, { arrayFormat: 'indices' })
}
})
.then(res => {
resolve(res.data);
})
.catch(err => {
reject(err.data)
})
});
}
function post(url, params, config) {
return new Promise((resolve, reject) => {
let parameters = params;
if (!config) {
parameters = url.indexOf('/core/') >= 0 ? params : QS.stringify(params);
} else if (config === "json") {
config = {
headers: { 'Content-Type': 'application/json;charset=utf-8' }
}
}
axios.post(url, parameters, config)
.then(res => {
resolve(res.data);
})
.catch(err => {
reject(err.data)
})
});
}
function put(url, params, config) {
return new Promise((resolve, reject) => {
let parameters = params;
if (!config) {
parameters = QS.stringify(params);
}
axios.put(url, parameters)
.then(res => {
resolve(res.data);
})
.catch(err => {
reject(err.data)
})
});
}
function del(url, params) {
return new Promise((resolve, reject) => {
axios.delete(url, { params: params })
.then(res => {
resolve(res.data);
})
.catch(err => {
reject(err.data)
})
});
}
function upload(files, url, paramName, otherParam) {
url = url || '/api/file/upload';
paramName = paramName || 'file';
let param = new FormData();
if (Object.prototype.isPrototypeOf(otherParam) && Object.keys(otherParam).length !== 0) {
for (const key in otherParam) {
if (otherParam.hasOwnProperty(key)) {
const element = otherParam[key];
param.append(key, element);
}
}
}
files.map((item) => {
param.append(paramName, item);
})
let config = {
headers: { 'Content-Type': 'multipart/form-data' }
};
return new Promise((resolve, reject) => {
axios.post(url, param, config)
.then(res => {
resolve(res.data);
})
.catch(err => {
reject(err.data)
})
});
}
function download(params, isDownLoad = true) {
let config = {
params: params,
headers: {
'content-disposition': "attachment;filename*=UTF-8",
'Content-Type': 'application/x-download;charset=utf-8'
},
responseType: 'blob'
};
return new Promise((resolve, reject) => {
axios.get("/api/file/download", config)
.then(res => {
if (!res) return;
const disposition = res.headers["content-disposition"];
const fileNameFromHeader = (disposition) => {
var result = null;
if (disposition && /filename=.*/ig.test(disposition)) {
result = disposition.match(/filename=.*/ig);
return decodeURI(escape(result[0].split('=')[1]));
}
return null;
}
const fileName = fileNameFromHeader(disposition);
let url = window.URL.createObjectURL(res.data);
resolve([url, fileName]);
if (!isDownLoad) return;
let link = document.createElement('a');
link.style.display = 'none';
link.href = url;
link.setAttribute('download', fileName);
document.body.appendChild(link);
link.click();
})
.catch(err => {
reject(err.data)
})
});
}
function downloadEx(url, params, fileName, isDownLoad = true) {
let fileType = 'xlsx';
fileName = fileName || '导出文件';
let config = {
params: params,
headers: {
'content-disposition': "attachment;filename=total." + fileType,
'Content-Type': 'application/x-download;charset=utf-8'
},
responseType: 'blob'
};
return new Promise((resolve, reject) => {
axios.get(url, config)
.then(err => {
if (!err) return;
let url = window.URL.createObjectURL(err.data);
resolve(url);
if (!isDownLoad) return;
let link = document.createElement('a');
link.style.display = 'none';
link.href = url;
link.setAttribute('download', `${fileName}.${fileType}`);
document.body.appendChild(link);
link.click();
})
.catch(err => {
reject(err.data)
})
});
}
export default {
get,
post,
put,
del,
upload,
download,
downloadEx,
all: axios.all,
spread: axios.spread
}
roter.js
import Vue from 'vue'
import Router from 'vue-router'
import Home from '@/pages/Home'
import Test from '@/pages/Test'
import Upload from '@/pages/Upload'
Vue.use(Router)
export default new Router({
mode: 'history',
routes: [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/test',
name: 'Test',
component: Test
},
{
path: '/upload',
name: 'Upload',
component: Upload
}
]
})
app.vue
<!--
* @Description:
-->
<template>
<div id="app">
<router-view/>
</div>
</template>
<script>
export default {
name: 'App'
}
</script>
<style>
</style>
main.js
import 'element-ui/lib/theme-chalk/index.css';
import Vue from 'vue'
import App from './App'
import router from './router'
import axios_ from './api/http'
import ElementUI from 'element-ui';
Vue.config.productionTip = false
Vue.prototype.axios = axios_;
Vue.use(ElementUI)
new Vue({
el: '#app',
router,
components: { App },
template: '<App/>'
})
Upload.js
<!--
* @Description:
-->
<!--
* @Description:上传图片
-->
<template>
<div class="upload">
<!-- 图片上传 -->
<div class="cell">
<el-upload :show-file-list="false"
class="avatar-uploader"
action=""
:http-request="uploadImg"
:before-upload="beforeAvatarUpload">
<img v-if="pic1" :src="pic1" class="avatar">
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
<p>图片1</p>
</div>
<div class="cell">
<el-upload :show-file-list="false"
class="avatar-uploader"
action=""
:http-request="uploadImg"
:before-upload="beforeAvatarUpload">
<img v-if="pic1" :src="pic2" class="avatar">
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
<p>图片2</p>
</div>
</div>
</template>
<script>
export default {
name:"Upload",
data() {
return {
pic1:'http://119.45.146.73:8889/pic/white/download?filePath=/home/file/upload/20210331/timg.jpg',
pic2:'',
pic3:'',
pic4:'',
pic5:'',
pic6:'',
pic7:'',
pic8:'',
};
},
methods: {
// 头像上传
async uploadImg(file) {
const avatar = await this.axios.upload([file.file]);
this.pic1 = avatar
this.$message.success('图片1修改成功');
},
beforeAvatarUpload(file) {
const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isJPG) {
this.$message.error('上传头像图片只能是 JPG 或者 PNG 格式!');
}
if (!isLt2M) {
this.$message.error('上传头像图片大小不能超过 2MB!');
}
return isJPG && isLt2M;
},
}
}
</script>
<style>
.avatar-uploader .el-upload {
border: 1px dashed #d9d9d9;
border-radius: 6px;
cursor: pointer;
position: relative;
overflow: hidden;
}
.avatar-uploader .el-upload:hover {
border-color: #409EFF;
}
.avatar-uploader-icon {
font-size: 28px;
color: #8c939d;
width: 178px;
height: 178px;
line-height: 178px;
text-align: center;
}
.avatar {
width: 178px;
height: 178px;
display: block;
}
</style>