1.0.2 • Published 5 years ago
@sinoui/http-send-file v1.0.2
@sinoui/http-send-file
@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
格式的,Node
、Python
、Ruby
后端可以解析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
。其中:
注意:如果需要稳定上传大文件,推荐使用send-big-file。