你会写下载功能嘛?
如何在本地,写一个下载的功能,不经过后端的接口呢?
vue版本:
(这里我用的是 vue3,vue2 同理)
下面是代码部分:
由于是本地测试,所以需要先上传一个文件,再去进行下载,否则没有下载模板。
如果后续要和后端那边做配合,也可以直接将后端返回的模板载入,进行下载操作。
downLoad.jsx
import { Button, Upload } from "antd";
import { useState } from "react";
export default function Uploadfile() {
const [file, setFile] = useState();
const props = {
name: 'file',
action: 'https://www.mocky.io/v2/5cc8019d300000980a055e76',
headers: {
authorization: 'authorization-text',
},
onChange(info) {
setFile(info.file)
},
};
const click = () => {
const link = document.createElement("a");
link.style.display = "none";
if (file) {
// 如果文件存在,设置下载文件名称
link.download = decodeURIComponent(file.name);
}
if (file) {
// 如果文件存在,设置下载文件
link.href = URL.createObjectURL(file.originFileObj);
}
document.body.appendChild(link);
link.click();
URL.revokeObjectURL(link.href);
document.body.removeChild(link);
};
return (
<div>
<Upload {...props}>
<Button>上传</Button>
</Upload>
<br />
<br />
<br />
<Button type="primary" onClick={click}>
下载
</Button>
</div>
);
}
App.js
import './App.css';
import downLoad from './components/downLoad.jsx'
function App() {
return (
<div>
<downLoad />
</div>
);
}
export default App;
今天的内容到此结束,下期再见!
转载自:https://juejin.cn/post/7208005892302553149