基于 FieReader 实现文件读取
基于 spark-md5 实现文件名生成

前端 ‘content-type’: ‘multipart/form-data’, 上传的文件,服务端解析 form-data 数据

文件类型(word、excel、image/png、mp4)都需要使用 formData格式上传文件至服务器

文件上传知识点

  1. 文件上传的经典方案: FormData,Base64
  2. 拖拽上传
  3. 文件上传安全验证
    1. 上传文件大小限制
    2. 文件格式校验
  4. 上传文件缩略图展示
  5. 上传进度条展示
  6. 文件端点续传的原理和实现
  7. 大文件切片上传及优化
  8. 多文件上传及进度条展示
  9. 上传到 oss,获取文件地址的连接
  10. 文件操作日志记录
  11. Content-Type 对应的数据类型

原生 file 上传

image.png
文件上传默认类型为 <input name="file" type="file" />
让用户选择一个或多个文件,通过表单提交上传到服务器,
JavaScript 使用File API进行操作

Upload上传

Upload组件上传文件一直提示跨域,服务端配置了允许跨域了
将 withCredentials 属性设置为false

  1. import { Upload, message, Button } from 'antd';
  2. import { UploadOutlined } from '@ant-design/icons';
  3. function App() {
  4. const props = {
  5. name: 'file',
  6. action: 'https://www.mocky.io/v2/5cc8019d300000980a055e76',
  7. headers: {
  8. authorization: 'authorization-text',
  9. },
  10. onChange(info) {
  11. if (info.file.status !== 'uploading') {
  12. console.log(info.file, info.fileList);
  13. }
  14. if (info.file.status === 'done') {
  15. message.success(`${info.file.name} file uploaded successfully`);
  16. } else if (info.file.status === 'error') {
  17. message.error(`${info.file.name} file upload failed.`);
  18. }
  19. },
  20. };
  21. return (
  22. <Upload {...props}>
  23. <Button icon={<UploadOutlined />}>Click to Upload</Button>
  24. </Upload>
  25. )
  26. }

原生Input上传

原生的 input 标签外加 fetch 函数就可以实现最简单的文件上传
参考文档 https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#uploading_a_file

  1. <input type="file" />
  2. const formData = new FormData();
  3. const fileField = document.querySelector("input[type='file']");
  4. formData.append('username', 'lucy');
  5. formData.append('avatar', fileField.files[0]);
  6. fetch('/api/avatar', {
  7. method: 'PUT',
  8. body: formData
  9. })
  10. .then(response => response.json())
  11. .then(response => console.log('Success:', response))
  12. .catch(error => console.error('Error:', error));

multiple多文件上传

  1. <input type="file" multiple/>
  2. const formData = new FormData()
  3. formData.append('file', file)
  4. formData.append('filename', file.name)
  5. const res = await postFormData(formData)

multiparty 解析

  1. import multiparty from 'multiparty'
  2. export function parseFormData(req) {
  3. const optinons = {
  4. uploadDir: '/public/upload',
  5. maxFiledsSize: 10 * 1024 * 1024
  6. }
  7. return new Promise((resolve, reject) => {
  8. const form = new multiparty.Form(optinons)
  9. form.parse(req, (err, fields, files) => {
  10. if (error) {
  11. reject({ fields, files, error })
  12. }
  13. resolve({ fields, files })
  14. })
  15. })
  16. }

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