基于 FieReader 实现文件读取
基于 spark-md5 实现文件名生成
前端 ‘content-type’: ‘multipart/form-data’, 上传的文件,服务端解析 form-data 数据
- multiparty 2k
- formidable 7k
- 解析图片和视频,支持 GB 级数据处理
- https://www.npmjs.com/package/formidable
- busboy 3k
- streaming parser
- https://github.com/mscdex/busboy
文件类型(word、excel、image/png、mp4)都需要使用 formData格式上传文件至服务器
文件上传知识点
- 文件上传的经典方案: FormData,Base64
- 拖拽上传
- 文件上传安全验证
- 上传文件大小限制
- 文件格式校验
- 上传文件缩略图展示
- 上传进度条展示
- 文件端点续传的原理和实现
- 大文件切片上传及优化
- 多文件上传及进度条展示
- 上传到 oss,获取文件地址的连接
- 文件操作日志记录
- Content-Type 对应的数据类型
原生 file 上传
文件上传默认类型为 <input name="file" type="file" />
让用户选择一个或多个文件,通过表单提交上传到服务器,
JavaScript 使用File API进行操作
Upload上传
Upload组件上传文件一直提示跨域,服务端配置了允许跨域了
将 withCredentials 属性设置为false
import { Upload, message, Button } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
function App() {
const props = {
name: 'file',
action: 'https://www.mocky.io/v2/5cc8019d300000980a055e76',
headers: {
authorization: 'authorization-text',
},
onChange(info) {
if (info.file.status !== 'uploading') {
console.log(info.file, info.fileList);
}
if (info.file.status === 'done') {
message.success(`${info.file.name} file uploaded successfully`);
} else if (info.file.status === 'error') {
message.error(`${info.file.name} file upload failed.`);
}
},
};
return (
<Upload {...props}>
<Button icon={<UploadOutlined />}>Click to Upload</Button>
</Upload>
)
}
原生Input上传
原生的 input 标签外加 fetch 函数就可以实现最简单的文件上传
参考文档 https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#uploading_a_file
<input type="file" />
const formData = new FormData();
const fileField = document.querySelector("input[type='file']");
formData.append('username', 'lucy');
formData.append('avatar', fileField.files[0]);
fetch('/api/avatar', {
method: 'PUT',
body: formData
})
.then(response => response.json())
.then(response => console.log('Success:', response))
.catch(error => console.error('Error:', error));
multiple多文件上传
<input type="file" multiple/>
const formData = new FormData()
formData.append('file', file)
formData.append('filename', file.name)
const res = await postFormData(formData)
multiparty 解析
import multiparty from 'multiparty'
export function parseFormData(req) {
const optinons = {
uploadDir: '/public/upload',
maxFiledsSize: 10 * 1024 * 1024
}
return new Promise((resolve, reject) => {
const form = new multiparty.Form(optinons)
form.parse(req, (err, fields, files) => {
if (error) {
reject({ fields, files, error })
}
resolve({ fields, files })
})
})
}
customRequest
https://github.com/react-component/upload#customrequest
https://ant.design/components/upload-cn/#customRequest
antd Upload使用总结
https://www.jianshu.com/p/0aa4612af987
https://www.cnblogs.com/qianguyihao/p/13093592.html