Commit 8c699885 authored by 田翔's avatar 田翔

fix: 增加文件下载的模板附件

parent b02d09a4
...@@ -181,7 +181,7 @@ const Account = (props, ref) => { ...@@ -181,7 +181,7 @@ const Account = (props, ref) => {
return await new Promise(async (resolve, reject) => { return await new Promise(async (resolve, reject) => {
const blob = await ExportAccountData({ accountName: accountName, ids: keys.join(','), exportAll }); const blob = await ExportAccountData({ accountName: accountName, ids: keys.join(','), exportAll });
const reader = new FileReader(); const reader = new FileReader();
reader.onload = function() { reader.onload = function () {
const text = reader.result; const text = reader.result;
if (text?.includes('code')) { if (text?.includes('code')) {
let obj = JSON.parse(text); let obj = JSON.parse(text);
...@@ -198,7 +198,7 @@ const Account = (props, ref) => { ...@@ -198,7 +198,7 @@ const Account = (props, ref) => {
resolve(); resolve();
} }
}; };
reader.onerror = function(error) { reader.onerror = function (error) {
console.error('Error reading the blob', error); console.error('Error reading the blob', error);
}; };
reader.readAsText(blob, 'UTF-8'); // 指定编码 reader.readAsText(blob, 'UTF-8'); // 指定编码
......
...@@ -1955,6 +1955,11 @@ const fileWidgets = [ ...@@ -1955,6 +1955,11 @@ const fileWidgets = [
hidden: "{{!['音频', '视频'].includes(formData.fileType)}}", hidden: "{{!['音频', '视频'].includes(formData.fileType)}}",
dependencies: ['fileType'] dependencies: ['fileType']
}, },
templateFile: {
title: '模板文件',
type: 'string',
widget: 'TemplateFile',
},
disabled: { disabled: {
title: '只读', title: '只读',
type: 'boolean', type: 'boolean',
......
import React, { useEffect, useMemo, useRef, useState } from 'react' import React, { useEffect, useMemo, useRef, useState } from 'react'
import styles from './index.less' import styles from './index.less'
import { Upload, Button, message, Tabs } from 'antd' import { Upload, Button, message, Tabs } from 'antd'
import { UploadOutlined, FileOutlined } from '@ant-design/icons' import { UploadOutlined, FileOutline, ArrowDownOutlined } from '@ant-design/icons'
import FileViewer from 'react-file-viewer' import FileViewer from 'react-file-viewer'
import Viewer from 'react-viewer' import Viewer from 'react-viewer'
import { uploadFileUrl, downloadFileUrl, downloadFile } from '../../../../apis/process' import { uploadFileUrl, downloadFileUrl, downloadFile } from '../../../../apis/process'
...@@ -69,7 +69,7 @@ const FileUpload = (props) => { ...@@ -69,7 +69,7 @@ const FileUpload = (props) => {
const site = window.globalConfig?.userInfo?.site || window.globalConfig?.userInfo?.LocalSite const site = window.globalConfig?.userInfo?.site || window.globalConfig?.userInfo?.LocalSite
const { addons, value, schema, onChange } = props const { addons, value, schema, onChange } = props
const { disabled, fileType, presetValue, placeholder, preview, download, isUncompressed } = schema const { disabled, fileType, presetValue, placeholder, preview, download, isUncompressed, templateFile, templateFileName } = schema
const [imgVisible, setImgVisible] = useState(false) const [imgVisible, setImgVisible] = useState(false)
const [showList, setShowList] = useState([]) const [showList, setShowList] = useState([])
...@@ -310,6 +310,10 @@ const FileUpload = (props) => { ...@@ -310,6 +310,10 @@ const FileUpload = (props) => {
setShowList(await valueToList(presetValue)) setShowList(await valueToList(presetValue))
} }
const downTemplateFile = () => {
window.open(`${window.origin}${downloadFileUrl}?filePath=${templateFile}${site ? `&_site=${site}` : ''}`)
}
useEffect(() => { useEffect(() => {
if (presetValue && !presetValue.includes('拍照相册')) { if (presetValue && !presetValue.includes('拍照相册')) {
addons?.setValue(addons?.dataPath, presetValue || '') addons?.setValue(addons?.dataPath, presetValue || '')
...@@ -335,6 +339,13 @@ const FileUpload = (props) => { ...@@ -335,6 +339,13 @@ const FileUpload = (props) => {
: (disabled ? null : (placeholder || '+ 上传')) : (disabled ? null : (placeholder || '+ 上传'))
} }
</Upload> </Upload>
{
templateFile ? (
<Button size='small' icon={<ArrowDownOutlined style={{ fontSize: '12px' }} />} onClick={() => downTemplateFile()}>
{templateFileName || '下载模板文件'}
</Button>
) : null
}
<Drag <Drag
width={'70%'} width={'70%'}
title={showFile.name} title={showFile.name}
......
import React, { useEffect, useState } from 'react'
import { Upload, Button, message, Input } from 'antd'
import { UploadOutlined, FileOutlined } from '@ant-design/icons'
import { uploadFileUrl, downloadFileUrl, downloadFile } from '../../../../../apis/process'
import { filenameVerification } from '../../../../../utils'
const TemplateFile = (props) => {
console.log('TemplateFile', props)
const site = window.globalConfig?.userInfo?.site || window.globalConfig?.userInfo?.LocalSite
const { value, onChange, addons } = props
const [showList, setShowList] = useState([])
const valueToList = async (presetValue) => {
let fileList = []
if (presetValue) {
let list = presetValue ? presetValue.split(',') : []
for (let i = 0; i < list.length; i++) {
if (list[i]) { // @Tips: 直接过滤掉名字中有异常字符的文件
let uid = i + '_' + Math.random()
let _obj = {
uid: uid,
name: list[i].split('/').reverse()[0],
type: 'file',
status: 'done',
url: list[i]?.includes('http') ? list[i] : `${window.origin}${downloadFileUrl}?filePath=${list[i]}${site ? `&_site=${site}` : ''}`,
sourcePath: list[i],
originFileObj: { "uid": uid },
"response": { "code": 0, "msg": "Ok", "data": list[i], "stackTrace": null },
"xhr": {},
};
fileList.push(_obj);
}
}
}
return fileList
}
const option = {
name: 'file',
action: `${window.location.origin}${uploadFileUrl}`,
listType: 'picture',
withCredentials: true,
showUploadList: {
showRemoveIcon: true,
showDownloadIcon: true,
},
beforeUpload(file, fileList) {
/** @Tips: 解决提交文件中存在特殊字符的问题 */
let _continueUpload = true;
let _msg = {
type: 'success',
content: '上传成功!',
};
fileList.forEach(item => {
let _msgObject = filenameVerification(item);
if (_msgObject.type === 'error') {
_continueUpload = false;
_msg = {
type: 'error',
content: '上传失败!文件名不符合规则!',
};
}
});
_msg.type === 'error' ? message[_msg.type](_msg.content) : ''
return _continueUpload;
},
onChange: ({ file, fileList, event }) => {
// 检验名字,名字不通过不允许显示
if (filenameVerification(file).type === 'error') return false;
// 返回的链接在file.response内;不设置url,预览图表不可点击
if (file.status === 'done' && file.response.code === 0) {
file.url = `${window.origin}${downloadFileUrl}?filePath=${file.response.data}${site ? `&_site=${site}` : ''}`
file.sourcePath = file.response.data;
message.success('上传成功!')
} else if (file.status === 'done' && file.response.code !== 0) {
file.status = 'error';
message.error('上传失败!')
}
if (Array.isArray(fileList)) {
setShowList(fileList)
} else {
setShowList([])
}
if (file.status === 'done') {
onChange(fileList.map(v => v.sourcePath).join(','))
}
},
onPreview: async (file) => {
if (!preview) return message.info('该附件禁止预览')
let fileType = getFileType(file.name)
setShowFile({ name: file.name, fileType: fileType, filePath: file.url })
if (fileType) {
if (['jpg', 'png', 'svg', 'jpeg'].includes(fileType)) {
let index = images.findIndex(v => v.sourcePath === file.sourcePath)
setActiveIndex(index)
setImgVisible(true)
} else {
if (['xlsx', 'xls'].includes(fileType)) {
downloadFile(file.sourcePath)
.then(response => response.arrayBuffer())
.then(buffer => {
const data = new Uint8Array(buffer);
const workbook = XLSX.read(data, { type: 'array' });
setWorkbook(workbook)
workbook?.SheetNames?.forEach(sheetName => {
const worksheet = workbook.Sheets[sheetName];
// 将工作表转换为 JSON 对象
const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1, defval: '' });
console.log(sheetName, jsonData)
})
})
}
setVisible(true)
}
} else {
message.info('不支持该类型预览')
}
},
onRemove: async (file) => {
let files = value?.split(",") || [];
let list = files.filter(v => v !== file.name);
onChange(list.join(","))
setShowList(await valueToList(list.join(",")))
},
}
const setList = async (value) => {
setShowList(await valueToList(value))
}
const templateNameChange = (e) => {
addons?.setValue('templateFileName', e.target.value)
}
useEffect(() => {
if (value) {
setList(value)
}
}, [])
return (
<div>
<Upload
style={{ width: '100%' }}
maxCount={1}
accept={['.docx', '.xlsx', '.pdf']}
fileList={showList}
className="upload-list-inline"
{...option}
>
<div style={{ display: 'flex' }}>
<Input placeholder='请输入提示语' style={{ width: '210px' }} onClick={(e) => e.stopPropagation()} onChange={templateNameChange} />
<Button type='primary' icon={<UploadOutlined />}>{'上传'}</Button>
</div>
</Upload>
</div>
)
}
export default TemplateFile
\ No newline at end of file
...@@ -15,6 +15,7 @@ import CoordSync from './CoordSync' ...@@ -15,6 +15,7 @@ import CoordSync from './CoordSync'
import SimpleList from './SimpleList' import SimpleList from './SimpleList'
import SqlFilter from './SqlFilter' import SqlFilter from './SqlFilter'
import OtherSource from './OtherSource' import OtherSource from './OtherSource'
import TemplateFile from './TemplateFile'
const groupSource = { const groupSource = {
Dictionary, Dictionary,
...@@ -34,6 +35,7 @@ const groupSource = { ...@@ -34,6 +35,7 @@ const groupSource = {
SimpleList, SimpleList,
SqlFilter, SqlFilter,
OtherSource, OtherSource,
TemplateFile,
} }
export default groupSource export default groupSource
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment