VUE
应用场景:只能上传一个文件,格式为.xls, .xlsx, .csv,文件上传成功后拖拽框隐藏,用WebSocket 获取实时进度条
<a-upload-dragger
v-if="!fileList.length"
v-model:fileList="fileList"
name="file"
accept=".xls, .xlsx, .csv"
:custom-request="uploadFileRequest"
>
<p class="import-black-tips"><upload-outlined /> 点击或拖拽文件至此上传</p>
</a-upload-dragger>
TS
const wsRef = ref<any>();
const sendData = async (file: any, key: string) => {
// 传输数据
const data = { key, file };
const res = await uploadExcel(data);
if (res?.hasError) {
fileList.value[0].status = 'error'; // 应用场景只有一个文件,故可用[0]取,最好用文件的uid查找
}
};
const uploadFileRequest = async ({ file }: any) => {
// 上传文件
const { result: socketID, hasError } = (await getKey()) || {};
if (hasError) {
message.warning('获取上传标识失败, 请再次尝试');
return;
}
const ws = new WebSocket('ws://' + window.location.host + '/webSocket/xxxxxxxxxxxxx/' + socketID);
wsRef.value = ws;
const currentFile = fileList.value[0];
ws.onopen = function () {
// websocket连接成功
sendData(file, socketID);
};
ws.onmessage = function (evnt) {
const data = JSON.parse(evnt.data) || {};
currentFile.percent = data.progress || 0;
if (data.isFinish) {
currentFile.status = 'success';
} else if (data.isError) {
currentFile.status = 'error';
}
};
ws.onerror = function () {
message.warning('websocket连接失败, 请再次尝试');
currentFile.status = 'error';
};
};
const handleDrop = () => {
// 取消上传文件
wsRef.value.close(); // 后端监听此操作,进行处理
fileList.value = [];
};
dev.ts
代理转发
getServer() {
return {
host: '0.0.0.0',
port: 7500,
open: false,
proxy: {
'/webSocket': {
target: 'http://xxxxxxxxxxx', // 代理转发目标地址
ws: true,
changeOrigin: true,
rewrite: (path: string) => path.replace(/^\/webSocket/, ''), // 重写路径
},
},
};
}