Vue代码
{{ $t('roster.putfilehere') }}{{ $t('roster.selectfile') }}
这段是下载按钮
{{ $t('roster.downloadTemplate') }}
Vue脚本:downLoadUserRankTemp
Method:{
downLoadUserRankTemp() {
this.$store.dispatch('downLoadTemp', { selType: 'RankLvl' });
},
}
//this.$store.dispatch('downLoadTemp', { selType: 'RankLvl' });
//在Api.js中实现
//import httpV2 from '@/utils/httpV2';
//import Config from '@/utils/config';
//import Cache from '@/utils/cache';
//downLoadTemp({ state, commit }, params) {
// return httpV2.getFile(process.env.VUE_APP_SDP_ADMIN_SECOND + //`/user/DownloadImportTemp`, params, this);
// },
process.env.VUE_APP_SDP_ADMIN_SECOND + `/user/DownloadImportTemp`//请求接口地址
params//参数
httpV2.getFile方法:
/**
* http.js
* 封装axios, 通过store 定义全局loading状态
* 调用方法:
* http.get('/api/enquiry/web/query',{id:1}).then((res)=>{你的操作})
* http.post('/api/enquiry/web/update',{id:1}).then((res)=>{你的操作})
* http.postFormData('/api/enquiry/web/update',{id:1,file:file}).then((res)=>{你的操作})
*/
import axios from 'axios';
// import { state } from '@/store/index.js'
import cache from '@/utils/cache';
import { Message } from 'element-ui';
axios.defaults.baseURL = process.env.VUE_APP_URL;
import Config from '@/utils/config';
// axios.defaults.headers.common.Authorization = cache.getStr("token")
export default {
downLoad(res) {
const fileName = res.headers["content-disposition"].split(";")[2].split("=")[1].replace("UTF-8''", "");
const blob = new Blob([res.data], {
type: "application/vnd.ms-excel;charset=utf-8"
});
const url = window.URL.createObjectURL(blob);
const aLink = document.createElement("a");
aLink.style.display = "none";
aLink.href = url;
aLink.setAttribute("download", decodeURI(fileName));
document.body.appendChild(aLink);
aLink.click();
document.body.removeChild(aLink); //下载完成移除元素
window.URL.revokeObjectURL(url); //释放掉blob对象
},
/**
* @param {String} url [请求的url地址]
* @param {Object} params [请求时携带的参数]
* @param context
* @param token
*/
getFile(url, params, context, token) {
params.language = localStorage.language;
let myTenantid = cache.get(Config.currentTenant) == null ? 1 : cache.get(Config.currentTenant).tenant_id;
let myOrgId = cache.get(Config.currentTenant) == null ? 0 : cache.get(Config.currentTenant).org_id;
context.dispatch('setLoading', true);
return new Promise((resolve, reject) => {
axios.get(url,
{
responseType: 'blob', //返回是个文件
params: params,
headers: {
Authorization: cache.getStr(Config.accessToken),
TenantId: myTenantid,
SdpTenantId: myTenantid,
OrgId: myOrgId
}
//headers:{Authorization: "Bearer eyJhbGciOiJSUzI1NiIsImtpZCI6IkFGRDNDNkMzOUVBQTA3QTZBRTY2Njg2MDFDMTMxM0NERDlFN0I3MzAiLCJ0eXAiOiJKV1QiLCJ4NXQiOiJyOVBHdzU2cUI2YXVabWhnSEJNVHpkbm50ekEifQ.eyJuYmYiOjE2Mjc5NTQ2NjAsImV4cCI6MTYyNzk5MDY2MCwiaXNzIjoiaHR0cHM6Ly90ZXN0LmFjY291bnQuYWlnb3N0YXIuY29tOjM0NDMiLCJhdWQiOlsiaHR0cHM6Ly90ZXN0LmFjY291bnQuYWlnb3N0YXIuY29tOjM0NDMvcmVzb3VyY2VzIiwiYXBpLWFkbWluIl0sImNsaWVudF9pZCI6ImFpZ28uY29tbXVuaXR5RGV0YWlsLnRlc3QiLCJzdWIiOiIxMjUwMjc2MDU3Mzc5MTE1MDA4IiwiYXV0aF90aW1lIjoxNjI3NjI2OTU2LCJpZHAiOiJsb2NhbCIsIm5hbWUiOiJib2IiLCJjb3VudHJ5X2NvZGUiOiJDTiIsInNjb3BlIjpbIm9wZW5pZCIsInByb2ZpbGUiLCJhcGktYWRtaW4iXSwiYW1yIjpbInB3ZCJdfQ.ALO2aa2S3E42zn3PW4r1WLyxw9w5pvB47xokr51ge4nPrJw82SzsiT1cIyJ8aUZgInboAsLM_RoFLlh96Rd0q_oGGQmsG7sjPDsdgOrs1jJrjKGFnnz2bDCDR_hooY3hOh4O4ykv2J8khDJP8bfcuWqoM6nTj8Lwu8H9GCnhhaYezmpiHOxXJfkw-w0yfqRirDCDkRbPar3VQqzXllN1smtzhxyVpGrcZKsUevyRt5yD8bBOevlm4h5JybWLWUtSXsQvQnQvLlYvcbwbILKBHwi1A2yEP8B61WWEY0DMu4DTzJXigZYiP8fSi9tTUW6pUtJcu6a3sPOp5BFrXTMD9w"}
}
).then(res => {
this.downLoad(res);
context.dispatch('setLoading', false);
resolve(res.data);
}).catch(err => {
// console.log(err);
// context.dispatch('setLoading', false);
// Message({
// type: 'error',
// message: err.response.data.message
// });
// if (err.response.status == 401) {
// setTimeout(() => {
// localStorage.clear()
// window.location = '/login';
// }, 1000);
// }
// reject(err);
});
});
},
// 获取租户id列表,无需TenantId、myTenantid、myOrgId
getTenantId(url, params, context, token) {
params.language = localStorage.language;
context.dispatch('setLoading', true);
return new Promise((resolve, reject) => {
axios.get(url,
{
params: params,
headers: {
Authorization: cache.getStr(Config.accessToken),
}
//headers:{Authorization: "Bearer eyJhbGciOiJSUzI1NiIsImtpZCI6IkFGRDNDNkMzOUVBQTA3QTZBRTY2Njg2MDFDMTMxM0NERDlFN0I3MzAiLCJ0eXAiOiJKV1QiLCJ4NXQiOiJyOVBHdzU2cUI2YXVabWhnSEJNVHpkbm50ekEifQ.eyJuYmYiOjE2Mjc5NTQ2NjAsImV4cCI6MTYyNzk5MDY2MCwiaXNzIjoiaHR0cHM6Ly90ZXN0LmFjY291bnQuYWlnb3N0YXIuY29tOjM0NDMiLCJhdWQiOlsiaHR0cHM6Ly90ZXN0LmFjY291bnQuYWlnb3N0YXIuY29tOjM0NDMvcmVzb3VyY2VzIiwiYXBpLWFkbWluIl0sImNsaWVudF9pZCI6ImFpZ28uY29tbXVuaXR5RGV0YWlsLnRlc3QiLCJzdWIiOiIxMjUwMjc2MDU3Mzc5MTE1MDA4IiwiYXV0aF90aW1lIjoxNjI3NjI2OTU2LCJpZHAiOiJsb2NhbCIsIm5hbWUiOiJib2IiLCJjb3VudHJ5X2NvZGUiOiJDTiIsInNjb3BlIjpbIm9wZW5pZCIsInByb2ZpbGUiLCJhcGktYWRtaW4iXSwiYW1yIjpbInB3ZCJdfQ.ALO2aa2S3E42zn3PW4r1WLyxw9w5pvB47xokr51ge4nPrJw82SzsiT1cIyJ8aUZgInboAsLM_RoFLlh96Rd0q_oGGQmsG7sjPDsdgOrs1jJrjKGFnnz2bDCDR_hooY3hOh4O4ykv2J8khDJP8bfcuWqoM6nTj8Lwu8H9GCnhhaYezmpiHOxXJfkw-w0yfqRirDCDkRbPar3VQqzXllN1smtzhxyVpGrcZKsUevyRt5yD8bBOevlm4h5JybWLWUtSXsQvQnQvLlYvcbwbILKBHwi1A2yEP8B61WWEY0DMu4DTzJXigZYiP8fSi9tTUW6pUtJcu6a3sPOp5BFrXTMD9w"}
}
).then(res => {
context.dispatch('setLoading', false);
resolve(res.data);
}).catch(err => {
context.dispatch('setLoading', false);
Message({
type: 'error',
message: err.response.data.message
});
if (err.response.status == 401) {
setTimeout(() => {
localStorage.clear()
window.location = '/login';
}, 1000);
}
reject(err);
});
});
},
/**
* get方法,对应get请求
* @param {String} url [请求的url地址]
* @param {Object} params [请求时携带的参数]
*/
get(url, params, context, token) {
params.language = cache.getStr(Config.localLangage) ? cache.getStr(Config.localLangage).toLowerCase() : "zh-cn";
let myTenantid = cache.get(Config.currentTenant) == null ? 1 : cache.get(Config.currentTenant).tenant_id;
let myOrgId = cache.get(Config.currentTenant) == null ? 0 : cache.get(Config.currentTenant).org_id;
context.dispatch('setLoading', true);
return new Promise((resolve, reject) => {
axios.get(url,
{
params: params,
headers: {
Authorization: cache.getStr(Config.accessToken),
TenantId: myTenantid,
SdpTenantId: myTenantid,
OrgId: myOrgId,
'accept-language': params.language
}
//headers:{Authorization: "Bearer eyJhbGciOiJSUzI1NiIsImtpZCI6IkFGRDNDNkMzOUVBQTA3QTZBRTY2Njg2MDFDMTMxM0NERDlFN0I3MzAiLCJ0eXAiOiJKV1QiLCJ4NXQiOiJyOVBHdzU2cUI2YXVabWhnSEJNVHpkbm50ekEifQ.eyJuYmYiOjE2Mjc5NTQ2NjAsImV4cCI6MTYyNzk5MDY2MCwiaXNzIjoiaHR0cHM6Ly90ZXN0LmFjY291bnQuYWlnb3N0YXIuY29tOjM0NDMiLCJhdWQiOlsiaHR0cHM6Ly90ZXN0LmFjY291bnQuYWlnb3N0YXIuY29tOjM0NDMvcmVzb3VyY2VzIiwiYXBpLWFkbWluIl0sImNsaWVudF9pZCI6ImFpZ28uY29tbXVuaXR5RGV0YWlsLnRlc3QiLCJzdWIiOiIxMjUwMjc2MDU3Mzc5MTE1MDA4IiwiYXV0aF90aW1lIjoxNjI3NjI2OTU2LCJpZHAiOiJsb2NhbCIsIm5hbWUiOiJib2IiLCJjb3VudHJ5X2NvZGUiOiJDTiIsInNjb3BlIjpbIm9wZW5pZCIsInByb2ZpbGUiLCJhcGktYWRtaW4iXSwiYW1yIjpbInB3ZCJdfQ.ALO2aa2S3E42zn3PW4r1WLyxw9w5pvB47xokr51ge4nPrJw82SzsiT1cIyJ8aUZgInboAsLM_RoFLlh96Rd0q_oGGQmsG7sjPDsdgOrs1jJrjKGFnnz2bDCDR_hooY3hOh4O4ykv2J8khDJP8bfcuWqoM6nTj8Lwu8H9GCnhhaYezmpiHOxXJfkw-w0yfqRirDCDkRbPar3VQqzXllN1smtzhxyVpGrcZKsUevyRt5yD8bBOevlm4h5JybWLWUtSXsQvQnQvLlYvcbwbILKBHwi1A2yEP8B61WWEY0DMu4DTzJXigZYiP8fSi9tTUW6pUtJcu6a3sPOp5BFrXTMD9w"}
}
).then(res => {
context.dispatch('setLoading', false);
resolve(res.data);
}).catch(err => {
context.dispatch('setLoading', false);
Message({
type: 'error',
message: err.response.data.message
});
if (err.response.status == 401) {
setTimeout(() => {
localStorage.clear()
window.location = '/login';
}, 1000);
}
reject(err);
});
});
},
patch(url, params, context, token) {
params.language = localStorage.language;
let myTenantid = cache.get(Config.currentTenant) == null ? 1 : cache.get(Config.currentTenant).tenant_id;
let myOrgId = cache.get(Config.currentTenant) == null ? 0 : cache.get(Config.currentTenant).org_id;
context.dispatch('setLoading', true);
return new Promise((resolve, reject) => {
axios.patch(url, params,
{
params: params,
headers: {
Authorization: cache.getStr(Config.accessToken),
TenantId: myTenantid,
SdpTenantId: myTenantid,
OrgId: myOrgId
}
}
).then(res => {
context.dispatch('setLoading', false);
resolve(res.data);
}).catch(err => {
context.dispatch('setLoading', false);
Message({
type: 'error',
message: err.response.data.message
});
if (err.response.status == 401) {
setTimeout(() => {
localStorage.clear()
window.location = '/login';
}, 1000);
}
reject(err);
});
});
},
delete(url, params, context, token) {
params.language = localStorage.language;
let myTenantid = cache.get(Config.currentTenant) == null ? 1 : cache.get(Config.currentTenant).tenant_id;
let myOrgId = cache.get(Config.currentTenant) == null ? 0 : cache.get(Config.currentTenant).org_id;
context.dispatch('setLoading', true);
return new Promise((resolve, reject) => {
axios.delete(url,
{
params: params,
headers: {
Authorization: cache.getStr(Config.accessToken),
TenantId: myTenantid,
SdpTenantId: myTenantid,
OrgId: myOrgId
}
}
).then(res => {
context.dispatch('setLoading', false);
resolve(res.data);
}).catch(err => {
context.dispatch('setLoading', false);
Message({
type: 'error',
message: err.response.data.message
});
if (err.response.status == 401) {
setTimeout(() => {
localStorage.clear()
window.location = '/login';
}, 1000);
}
reject(err);
});
});
},
/**
* post方法,对应post请求
* @param {String} url [请求的url地址]
* @param {Object} params [请求时携带的参数]
*/
put(url, params, context) {
url = decodeURI(encodeURI(url).replace(/%E2%80%8B/g, ''))
params.language = localStorage.language;
let myTenantid = cache.get(Config.currentTenant) == null ? 1 : cache.get(Config.currentTenant).tenant_id;
let myOrgId = cache.get(Config.currentTenant) == null ? 0 : cache.get(Config.currentTenant).org_id;
context.dispatch('setLoading', true);
return new Promise((resolve, reject) => {
axios.put(url, params,
{
headers: {
Authorization: cache.getStr(Config.accessToken),
TenantId: myTenantid,
SdpTenantId: myTenantid,
OrgId: myOrgId
}
}
)
.then(res => {
context.dispatch('setLoading', false);
resolve(res.data);
})
.catch(err => {
context.dispatch('setLoading', false);
Message({
type: 'error',
message: err.response.data.message
});
if (err.response.status == 401) {
setTimeout(() => {
localStorage.clear()
window.location = '/login';
}, 1000);
}
reject(err);
});
});
},
/**
* post方法,对应post请求
* @param {String} url [请求的url地址]
* @param {Object} params [请求时携带的参数]
*/
post(url, params, context) {
url = decodeURI(encodeURI(url).replace(/%E2%80%8B/g, ''))
params.language = localStorage.language;
let myTenantid = cache.get(Config.currentTenant) == null ? 1 : cache.get(Config.currentTenant).tenant_id;
let myOrgId = cache.get(Config.currentTenant) == null ? 0 : cache.get(Config.currentTenant).org_id;
context.dispatch('setLoading', true);
return new Promise((resolve, reject) => {
axios.post(url, params,
{
headers: {
Authorization: cache.getStr(Config.accessToken),
TenantId: myTenantid,
SdpTenantId: myTenantid,
OrgId: myOrgId
}
}
)
.then(res => {
context.dispatch('setLoading', false);
resolve(res.data);
})
.catch(err => {
context.dispatch('setLoading', false);
Message({
type: 'error',
message: err.response.data.message
});
if (err.response.status == 401) {
setTimeout(() => {
localStorage.clear()
window.location = '/login';
}, 1000);
}
reject(err);
});
});
},
/**
* postFormData方法,对应post请求,用来提交文件+数据
* @param {String} url [请求的url地址]
* @param {Object} params [请求时携带的参数]
*/
postFormData(url, params) {
return new Promise((resolve, reject) => {
axios({
headers: {
'Content-Type': 'multipart/form-data'// ;boundary=----WebKitFormBoundaryQ6d2Qh69dv9wad2u
},
transformRequest: [function (data) { // 在请求之前对data传参进行格式转换
const formData = new FormData();
Object.keys(data).forEach(key => {
formData.append(key, data[key]);
});
return formData;
}],
url,
method: 'post',
data: params
}).then(res => {
resolve(res.data);
}).catch(err => {
Message({
type: 'error',
message: err.response.data.Message
});
reject(err);
});
});
},
postFile(url, params, context) {
url = decodeURI(encodeURI(url).replace(/%E2%80%8B/g, ''))
params.language = localStorage.language;
let myTenantid = cache.get(Config.currentTenant) == null ? 1 : cache.get(Config.currentTenant).tenant_id;
let myOrgId = cache.get(Config.currentTenant) == null ? 0 : cache.get(Config.currentTenant).org_id;
context.dispatch('setLoading', true);
return new Promise((resolve, reject) => {
axios.post(url,
params,
{
responseType: 'blob', //返回是个文件
headers: {
Authorization: cache.getStr(Config.accessToken),
TenantId: myTenantid,
SdpTenantId: myTenantid,
OrgId: myOrgId
}
}
).then(res => {
this.download(res);
context.dispatch('setLoading', false);
resolve(res.data);
}).catch(err => {
context.dispatch('setLoading', false);
Message({
type: 'error',
message: err.response.data.message
});
if (err.response.status == 401) {
setTimeout(() => {
localStorage.clear()
window.location = '/login';
}, 1000);
}
reject(err);
});
});
}
};
其中const fileName = res.headers["content-disposition"].split(";")[2].split("=")[1].replace("UTF-8''", "");正常接口获取不到,需要在后端服务配置这个,跨域策略:
在setup.cs中的ConfigureServices方法中
services.AddCors(options =>
{
options.AddPolicy(
_allowSpecificOriginsPolicyName,
policy =>
{
//string[] opl = Configuration.GetSection("OriginPolicyList").Get();
//foreach (var item in opl)
//{
// policy.WithOrigins(item);
//}
policy.AllowAnyHeader().SetIsOriginAllowed(_ => true)
.AllowAnyMethod().WithExposedHeaders("Content-Disposition");//允许浏览器访问额外的自定义头;
});
});
.netcore 接口实现:
///
/// 下载模板
///
///
[HttpGet("DownloadImportTemp")]
[Permission(ModuleCodes.UserList, SimpleOperation.View)]
public IActionResult DownloadImportTemp(string selType)
{
FileStreamResult file = null;
FileStream fileStream;
string filePath = string.Empty;
switch (selType)
{
case "RankLvl":
filePath = _webHostEnvironment.WebRootPath + "/TempFile/UserRankTemp.xlsx";
fileStream = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite);
file = File(fileStream, "application/octet-stream", "导入岗级导入模板(Import Rank Level Template).xlsx");
break;
case "UserType":
filePath = _webHostEnvironment.WebRootPath + "/TempFile/UserTalentTypeTemp.xlsx";
fileStream = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite);
file = File(fileStream, "application/octet-stream", "人才类型导入模板(Import Talent Type Template).xlsx");
break;
}
return file;
}
_webHostEnvironment.WebRootPath是获取项目中wwwroot路径
_webHostEnvironment需要在构造函数注入
private readonly IWebHostEnvironment _webHostEnvironment;
public UserApiController(
IWebHostEnvironment webHostEnvironment,
)
{
_webHostEnvironment = webHostEnvironment;
}