当前位置: 移动技术网 > IT编程>开发语言>JavaScript > 微信小程序实现图片上传功能实例(前端+PHP后端)

微信小程序实现图片上传功能实例(前端+PHP后端)

2018年01月28日  | 移动技术网IT编程  | 我要评论

前言

几乎每个程序都需要用到图片。下面就来给大家介绍前端+php后端实现微信小程序实现图片上传功能,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍吧。

方法如下:

一、wxml文件

<text>上传图片</text>
<view>
<button bindtap="uploadimg">点击选择上传图</button>
</view>
<image src='{{source}}' style='width:600rpx; height:600rpx' />

二、js文件

page({
 /**
 * 页面的初始数据
 */
 data: {  //初始化为空
 source:''
 },
/**
 * 上传图片
 */
 uploadimg:function(){
 var that = this;
 wx.chooseimage({ //从本地相册选择图片或使用相机拍照
  count: 1, // 默认9
  sizetype: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
  sourcetype: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
  success:function(res){
  //console.log(res)
  //前台显示
  that.setdata({
   source: res.tempfilepaths
  })
  // 返回选定照片的本地文件路径列表,tempfilepath可以作为img标签的src属性显示图片
  var tempfilepaths = res.tempfilepaths
   wx.uploadfile({
   url: 'http://www.website.com/home/api/uploadimg',
   filepath: tempfilepaths[0],
   name: 'file',
   
   success:function(res){
   //打印
   console.log(res.data)
   }
  })
  
  }
 })
 },)}

三、php后端代码

// 上传图片
 public function uploadimg()
 {
   $file = request()->file('file');
  if ($file) {
   $info = $file->move('public/upload/weixin/');
   if ($info) {
    $file = $info->getsavename();
    $res = ['errcode'=>0,'errmsg'=>'图片上传成功','file'=>$file];
    return json($res);
   }
  }  
 }

运行结果:

console打印结果:

此时表示上传成功!

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对移动技术网的支持。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网