一、导出
1、返回值是url:创建个a标签即可
printRecord(params).then((response) => {
if (response.success) {
let a = document.createElement('a');//创建a标签
//从新页面打开,下载的话不需要这个,打开一个图片需要从新页面打开
a.setAttribute("target", "_blank");
a.href = response.data;//文件url
document.body.appendChild(a);
a.click();//触发下载
document.body.removeChild(a)
} else {
message.error(response.message);
}
})
.catch((error) => {
console.log(error);
}).finally(()=>{
this.setState({
nowLoading:false
})
})
2、返回值是文件流:响应类型设置为blob,将文件转化为url,a标签点击下载。
axios({
method: 'get',
url: WEBCONFIG.HOST + `/bapi/api/user-trajectory/biz/user-trajectory/local/export?type=${97}`,
responseType: 'blob',
headers: { 'X-Cfpamf-App-Key': WEBCONFIG.APP_KEY, 'authorization': WEBCONFIG.token }
}).then(response => {
this.download(response, '员工居住地址明细');
}).catch((error) => {
message.error("导出失败,请检查当前查询条件是否能查出数据!");
}).finally(() => {
this.setState({
exportLoading:false
})
})
// 导出
download = (data, name) => {
if (!data) {
return
}
const time = moment().format('YYYYMMDD');
const blob = new Blob([data.data], { type: "application/vnd.ms-excel" });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.style.display = 'none';
link.href = url;
//下载下来的文件的名字
link.setAttribute('download', `${name + time}.xls`);
document.body.appendChild(link);
link.click()
}
3、返回值是文件流。然后是pdf,且想直接打印,只能通过iframe。
注意:后端如果返回的是url,不行,iframe的url会跨域,不能调用计算机的打印程序成功,必须返回的是文件流,自己创建url,且经实测,这个设置url步骤有延迟,1s后才能调用打印程序成功。
<iframe id="printIframe" src='' style={{display: 'none'}}></iframe>
axios({
method:'post',
url: WEBCONFIG.HOST + `/loan/customer/printRecord`,
responseType: 'blob',
headers: {'X-Cfpamf-App-Key':WEBCONFIG.APP_KEY,'authorization':WEBCONFIG.token},
data: params,
}).then(response => {
var blob = new Blob([response.data],{ type: 'application/pdf' });
const url = URL.createObjectURL(blob);
var red = document.getElementById("printIframe");
red.setAttribute("src", url);
setTimeout(() =>{
red.focus();
red.contentWindow.print();
},1000)
}).catch((error) => {
message.error("导出失败,请检查当前查询条件是否能查出数据!");
if(error.toString().indexOf('Request failed with status code 401')){
store.dispatch({
type: 'login/logout',
});
}
}).finally(()=>{
this.setState({
nowLoading:false
})
})
二、导入
1、上传到阿里云
动态获取aliyun参数配置,client.put上传文件,上传后每次得到的都是临时地址,每次得重新请求新的临时地址预览。
举例:上传视频 antd3.0
const OSS = require('ali-oss');
// 获取阿里云上传token
export async function getStsOssConfig(params) {
return request(`${WEBCONFIG.HOST}/bizconfig/common/getStsOssConfig?${stringify(params)}`);
}
const fileTypes = ['png','jpeg','jpg','bmp','gif','xlsx','xls','txt','pdf','doc','docx','ppt','pptx','rar',
'zip','dat','avi','rmvb','wps','jpe','xml','3gp','m3u8','mp4','csv','mp3','m4a','awb','heic']
export function validateFileType(file){
//限制上传文件类型
let idx = file.name.lastIndexOf('.'),res=true;
if(idx>-1){
let filetype = file.name.substr(idx+1,file.name.length-idx);
console.log(filetype,'fileInfo',file)
if(!(fileTypes.includes(filetype.toLowerCase()))){
let list=[]
let content = <span>上传的文件类型必须以下范围中:
{
fileTypes.map((k,idx)=>{
list.push(k)
if((idx+1)%10===0 || idx === fileTypes.length-1){
let str = list.join('、');
list = []
return <span><span>{str}</span><br/></span>
}
})
}
</span>
message.error(content);
res = false;
}
}
return res;
}
export function queryStsOssConfig(param,file,docCode) {
//限制上传文件类型
let flag = validateFileType(file);
if(!flag){
return Promise.resolve()
}
// 前端生成uuid
const s = [];
const hexDigits = "0123456789abcdef";
for (let i = 0; i < 8; i++) {
s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
}
let uuid = s.join("");
if (file.name.indexOf(".") > 0){
const arr = file.name.split(".");
if(docCode){
uuid = (`${docCode}_${getDataByKey(Global.USERID) }_web_${ uuid }_${moment().format('YYYYMMDDHHmmss')}.${arr[arr.length - 1]}`);
}else{
uuid = (`${getDataByKey(Global.USERID) }_web_${ uuid }_${moment().format('YYYYMMDDHHmmss')}.${arr[arr.length - 1]}`);
}
}
const defaultParams = {
key:param,
};
try{
return new Promise((resolve, reject) => {
getStsOssConfig(defaultParams).then((response) =>{
if(response && response.success){
const configData=response.data;
let endpoint2 = configData.endpoint;
const index=endpoint2.lastIndexOf(".");
endpoint2=endpoint2.substring(0,index);
const index2 = endpoint2.lastIndexOf(".");
endpoint2=endpoint2.substring(0,index2);
const client = new OSS({
region: endpoint2,
accessKeyId: configData.accessKeyId,
accessKeySecret: configData.accessKeySecret,
stsToken:configData.securityToken,
bucket: configData.bucket,
timeout:5 * 60 * 1000
});
client.put(uuid, file).then((response2)=>{
resolve({
...response2,
config:response.data
},uuid);
}).catch((error) => {
console.log(error);
message.error('提交失败,请稍候重试');
});
}else{
message.error(response?.message);
}
})
.catch((error) => {
reject(error);
});
});
}catch (e){
console.log(e);
};
}
<Dragger
disabled={this.state.disableList.videoUpload}
accept=".3gp, .mp4, .avi, .mov"
beforeUpload={this.beforeUploadHandle}
onRemove={this.onRemove}
fileList={this.state.fileList}
onPreview={this.onPreview}
>
<p className="ant-upload-drag-icon">
{this.state.uploadVideoloading ? <Icon type="loading" /> : <Icon type="inbox" />}
</p>
<p>将文件拖到此处,或<span style={{ color: '#3399ff' }}>点击上传</span></p>
</Dragger>
<Modal
title="预览"
visible={this.state.previewVideoVisible}
onCancel={this.handleCancel}
footer={null}
width='40%'>
<video height='350' controls style={{ width: '100%' }}>
<source src={this.state.tempVideoUrl} />
</video>
</Modal>
// 获取阿里云图片地址url
getOssUrl = (fileId, file) => {
const self = this;
const params = {
name:fileId,
}
return getSCRMTempUrl(params).then((response) => {
if (response.success) {
// console.log('getSCRMTempUrl');
// console.log(response);
self.setState({
fileList: [file],
tempVideoUrl: response.data,
});
} else {
message.error(response.message);
}
}).catch((error) => {
message.error(Global.NORMAL_ERR);
}).finally(() => {
this.setState({
uploadVideoloading: false
})
})
};
// 上传图片
beforeUploadHandle = (file) => {
// console.log('file');
// console.log(file);
if (file.type !== 'video/mp4' && file.type !== 'video/3gpp' && file.type !== 'video/avi' && file.type !== 'video/quicktime') {
return message.error("只能上传3GP/MP4/AVI/MOV视频文件!")
}
const isLt500M = file.size / 1024 / 1024 < 500;
if (!isLt500M) {
return message.error('上传视频大小不能超过500M!');
}
if (file.size * 1024)
this.setState({
uploadVideoloading: true
})
queryStsOssConfig("SCRM", file).then((response) => {
if (response) {
// console.log('queryStsOssConfig');
// console.log(response);
this.getOssUrl(response.name, file);
this.setState({
fileName: file.name,
fileId: response.name
})
} else {
this.setState({
uploadVideoloading: false
})
message.error("上传失败");
}
}).catch((error) => {
console.log(error);
message.error('提交失败,请稍候重试');
this.setState({
uploadVideoloading: false
})
})
return false;
};
onPreview = (file) => {
this.setState({
previewVideoVisible: true
})
}
onRemove = () => {
this.setState({
fileList: [],
tempVideoUrl: '',
fileName: '',
fileId: ''
});
}