加载中…

文件上传

# 前言 本教程是基于 “apifm-wxapi” 模块,教你快速实现小程序开发,所以你可能需要先了解以下知识点: [《创建 HelloWorld 项目》](https://www.yuque.com/apifm/doc/hezlrm) [《使用 “apifm-wxapi” 快速开发小程序》](https://www.yuque.com/apifm/doc/mdldsd) [《免费注册开通后台,获得专属域名》](https://www.yuque.com/apifm/doc/qr6l4m) # 功能说明 为方便演示,本案例仅样式图片文件的上传功能; 实现本地图片(相册、调用相机拍照)上传至服务器; 实现远程图片(填写图片URL地址)下载至服务器; 通过接口实现读取服务器文件管理列表; _变现的可实现简易云盘的功能_ # 小程序实现 ## 效果演示 ![](https://dcdn.it120.cc/yuque/0/2019/png/572726/1572848483939-98386fde-2615-4c29-902e-145e5a04c752.png) ## wxml代码 ```plain 图片上传 上传提示 远程下载图片 ``` ## js代码 ```plain const WXAPI = require('apifm-wxapi') WXAPI.init('gooking') Page({ data: { piclists: undefined // 服务器上的文件列表 }, onLoad: function (options) { }, onShow: function () { this.uploadFileList() }, goRegist() { wx.navigateTo({ url: '/pages/auth/index' }) }, urlChange(e){ this.data.url = e.detail.value }, uploadFileList(){ wx.showLoading({ title: '加载中', }) WXAPI.uploadFileList().then(res => { wx.hideLoading() console.log(res) if (res.code == 0){ this.setData({ piclists: res.data }) } }) }, chooseImage: function (e) { const loginToken = wx.getStorageSync('loginToken') if (!loginToken) { wx.showToast({ title: '请先登录', icon: 'none' }) return } const _this = this; wx.chooseImage({ sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有 sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有 count: 1, // 最多选择几张图片 success: function (res) { // 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片 console.log(res) WXAPI.uploadFile(loginToken.token, res.tempFilePaths[0]).then(_res => { console.log(_res) _this.uploadFileList() }) } }) }, uploadFileFromUrl(){ if (!this.data.url) { wx.showToast({ title: '地址不能空', icon: 'none' }) return } WXAPI.uploadFileFromUrl(this.data.url, '.png').then(res => { console.log(res) this.setData({ url: null }) this.uploadFileList() }) }, previewImage: function (e) { wx.previewImage({ current: e.currentTarget.id, // 当前显示图片的http链接 urls: this.data.files // 需要预览的图片http链接列表 }) } }) ``` > WXAPI.init('gooking')  这句代码是将你的小程序链接到你的后台,其中  gooking 这个是你的专属域名(请查看前言中关于专属域名的章节说明); > # 后台可管理文件(图片) ![](https://dcdn.it120.cc/yuque/0/2019/png/572726/1572848485267-1ec0f945-ec31-44a1-9d10-d85e57345d08.png) # 总结 本案例主要使用了 apifm-wxapi 的以下3个方法: ```plain WXAPI.uploadFile(token, tempFilePath) WXAPI.uploadFileFromUrl(remoteFileUrl, ext) WXAPI.uploadFileList(path) ``` _关于  apifm-wxapi 更多的使用方法:_ [《apifm-wxapi使用说明》](https://github.com/gooking/apifm-wxapi/blob/master/instructions.md) _本案例Demo代码下载:_ [《apifm-wxapi使用Demo程序》](https://github.com/gooking/apifm-wxapi-demo) # 拓展 基于上述方法及后台,亲子动手去尝试实现一个个人相处、简易网盘小程序,与大家一起分享。 期待你的进步! 感谢!