@sinoui/http-send-file

npm version downloads

@sinoui/http-send-file 旨在提供一种便捷的方式用于文件上传。

安装

执行下面的命令即可快速安装:

快速使用

html文件

<html>
  <body>
    <input id="file" type="file" />
    <input type="button" value="文件上传" onclick="uploadFile()" />
  </body>
</html>

js文件

import sendFile from '@sinoui/http-send-file';

async function uploadFile() {
  const file = document.getElementById('file').files[0];
  try {
    await sendFile('http://localhost:3000/files', file);
    console.log('上传成功');
  } catch (error) {
    console.error('上传失败');
  }
}

上传一组文件

一组文件对象添加到 FormData 时组织key的方式:indices repeat。

Java 后端可以解析repeat格式的,NodePythonRuby后端可以解析indices格式的。

import sendFile from '@sinoui/http-send-file';

async function uploadFileDemo() {
  await sendFile(url, files, {
    arrayFormat: 'indices',
  });
}

添加额外数据

import sendFile from '@sinoui/http-send-file';

async function uploadFileDemo() {
  await sendFile(url, files, 'usePhotot', {
    data: {
      userId: '123',
      userName: 'zhangsan',
    },
  });
}

文件上传进度

import sendFile from '@sinoui/http-send-file';

const onUploadProgress = (progressEvent: ProgressEvent) => {
  console.log(
    `上传进度:${((progressEvent.loaded / progressEvent.total) * 100) | 0}%`,
  );
};

async function uploadFileDemo() {
  await sendFile(url, files, {
    onUploadProgress,
  });
}

sendFile()方法参数说明

注意: 如果需要稳定上传大文件,推荐使用send-big-file