简介
ufile-rest 是一个基于 Node.js 环境下的 npm 包,用于操作优刻得 (UCloud) 对象存储 (UFile) 的 RESTful API 接口。ufile-rest 提供了 UFile 的上传、下载、删除等功能,也可以方便地管理文件的元数据,支持多文件上传和文件秒传。
安装
在项目根目录下运行以下命令:
npm install ufile-rest --save
使用 --save
参数能确保 ufile-rest 包被添加到项目的 package.json
中。
简单示例
初始化
-- -------------------- ---- ------- ----- ----- - ---------------------- ----- ----------- - - ---------- ----------------- ----------- ------------------ ------- -------------- ------------ --------------------------- -- ------------------------ -- ----- ----- - --- -------------------展开代码
这里的 publicKey
和 privateKey
是凭证,可以在这里进行获取。
上传文件
ufile.putFile('/path/to/local/file', '/path/to/remote/file') .then(result => { console.log(result); }) .catch(error => { console.error(error); });
这里的 /path/to/local/file
是本地文件的路径,/path/to/remote/file
是上传到 UFile 上的路径。
如果 /path/to/remote/file
中的路径不存在,ufile-rest 会自动创建它的父路径。
result
是一个对象,包含上传成功后的文件信息,例如:
{ ETag: '"9ad2f6276a704feee41eb4e4f0950a2f"', ResponseContentLength: '0', StatusCode: 200 }
下载文件
ufile.getFile('/path/to/remote/file', '/path/to/local/file') .then(result => { console.log(result); }) .catch(error => { console.error(error); });
这里的 /path/to/remote/file
是 UFile 上的路径,/path/to/local/file
是文件下载到本地的路径。
如果本地文件夹不存在,ufile-rest 会自动创建它。
result
是一个对象,包含下载成功后的文件信息,例如:
{ ResponseContentLength: '16', StatusCode: 200 }
删除文件
ufile.deleteFile('/path/to/remote/file') .then(result => { console.log(result); }) .catch(error => { console.error(error); });
这里的 /path/to/remote/file
是 UFile 上的路径。
result
是一个对象,包含删除成功后的文件信息,例如:
{ ResponseContentLength: '0', StatusCode: 204 }
进阶示例
使用 multipart 方式上传大文件
ufile.putLargeFile('/path/to/local/file', '/path/to/remote/file') .then(result => { console.log(result); }) .catch(error => { console.error(error); });
这里的 /path/to/local/file
是本地文件的路径,/path/to/remote/file
是上传到 UFile 上的路径。
putLargeFile
方法会自动使用 multipart 方式上传大文件,对于小文件,ufile-rest 会自动转变成 putFile
来上传,以保证上传速度。
result
是一个对象,包含上传成功后的文件信息,例如:
{ ETag: '"f85d4b4ef4ca7b0215f925c5ab96b016"', ResponseContentLength: '0', StatusCode: 200 }
获取文件访问 URL
const url = ufile.getFileUrl('/path/to/remote/file'); console.log(url);
这里的 /path/to/remote/file
是 UFile 上的路径。
getFileUrl
方法会返回文件的访问 URL,例如:
http://your-bucket.cn-bj.ufileos.com/path/to/remote/file
设置文件元数据
-- -------------------- ---- ------- ------------------------------------ ----------------------- - --------------- ------------------- -- ------------ -- - -------------------- -- ------------ -- - --------------------- ---展开代码
这里的第三个参数是文件元数据,是一个包含属性和值的键值对。ufile-rest 可以方便地对文件进行元数据管理。
其他操作
ufile-rest 还提供了其他的操作方法,例如批量删除文件、文件列表、文件信息等等。具体可参考官方文档。
结语
UCloud 提供了一套非常好用的对象存储服务 UFile,并为 Node.js 环境提供了丰富的 API 接口。使用 npm 包 ufile-rest 可以很方便地使用 UFile 的功能,而且支持大文件上传和秒传,让你的项目变得更加智能高效。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/6005609781e8991b448dece9