@sinoui/http-send-file
TypeScript icon, indicating that this package has built-in type declarations

1.0.2 • Public • Published

@sinoui/http-send-file

npm version downloads

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

安装

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

  • 使用 npm

    npm install --save @sinoui/http-send-file
  • 使用 yarn

    yarn add @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()方法参数说明

  • url (string)

    指定文件上传的 url

  • files (Blob[] | Blob)

    需要上传的文件,可以是单个的或者是数组

  • fileFieldName (string)

    指定表单域的名称,默认为file

  • options (object)

    请求配置,支持所有的Axios 请求配置,除此之外,还包括arrayFormat。其中:

    • arrayFormat

      一组文件对象添加到 FormData 时组织key的方式。默认为repeat

      • repeat: file=file1&file=file2&file=file3

      • indices: file[0]=file1&file[1]=file2&file[2]=file3

    • data

      指定需要的额外数据。必须是可以加入到FormData中的对象,如:

      const extraFormData = {
        userId: '123',
        userName: '张三',
      };

      对象中的属性值只支持原始类型。

    • onUploadProgress

      文件上传进度回调函数

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

Readme

Keywords

none

Package Sidebar

Install

npm i @sinoui/http-send-file

Weekly Downloads

1

Version

1.0.2

License

MIT

Unpacked Size

36.2 kB

Total Files

17

Last publish

Collaborators

  • longniansheng
  • jackingliu
  • tianyanqiu
  • chenaihua
  • maitian0222