将本地资源上传到服务器。客户端发起一个 HTTPS POST 请求,其中 content-type 为 multipart/form-data。

以上传图片为例

示例代码:

wx.chooseImage({  success(res) {    const tempFilePaths = res.tempFilePaths    wx.uploadFile({      url: 'https://example.weixin.qq.com/upload', // 仅为示例,非真实的接口地址      filePath: tempFilePaths[0],      name: 'file',      formData: {        user: 'test'      },      success(res) {        const data = res.data        // do something      }    })  }})

后台接口处理接受数据

//图片上传七牛云接口public function UploadFile(){   $param = request()-param();    $file=request()-file('file');       $controller='index';       $accKey='you key';       $secret='you sercret';       $space='qqcard';       $do='10088.cn';       $img = new Upload();       $url = $img-uploadImg($file,$controller,$accKey,$secret,$space,$do);       $filePath = $image-getRealPath();       return json(['url'=$url]);}

七牛云封装上传类

namespace Qiniu;require_once 'autoload.php';use QiniuAuth as Auth;use QiniuStorageBucketManager;use QiniuStorageUploadManager;class Upload{    /**     * 七牛云图片上传封装类     * @param $image //图片名称     * @param $controller //控制器名称     * @param $accKey //七牛云accessKey     * @param $secret //七牛云secretKey     * @param $space  //七牛云上传空间     * @param $do    //七牛云空间绑定的域名     * @return array|string //1.成功返回图片存储的全路径;2.返回错误信息     */    public function uploadImg($image,$controller,$accKey,$secret,$space,$do){        $file = $image;        // 要上传图片的本地路径        $filePath = $file-getRealPath();        $ext = pathinfo($file-getInfo('name'), PATHINFO_EXTENSION);  //后缀        //获取当前控制器名称        $controllerName = $controller;        // 上传到七牛后保存的文件名        $key =substr(md5($file-getRealPath()) , 0, 5). date('YmdHis') . rand(0, 9999) . '.' . $ext;        // 需要填写你的 Access Key 和 Secret Key        $accessKey = $accKey;        $secretKey = $secret;        // 构建鉴权对象        $auth = new Auth($accessKey, $secretKey);        // 要上传的空间        $bucket = $space;        $domain = $do;        $token = $auth-uploadToken($bucket);        // 初始化 UploadManager 对象并进行文件的上传        $uploadMgr = new UploadManager();        // 调用 UploadManager 的 putFile 方法进行文件的上传        list($ret, $err) = $uploadMgr-putFile($token, $key, $filePath);        if ($err !== null) {            return ["err"=1,"msg"=$err];        } else {            //返回图片的完整URL            return "http://"."{$do}"."/".$key;        }    }}

 

TAG标签: 微信小程序七牛云上传图片

http://www.xiaochengxub.com/read-102771.html