小程序的图片上传wx.uploadFile及后台PHP接收文件并存储到服务器

前台代码wxml:

 

<button bindtap='chooseImg'>选择图片</button>//图片选择
<view><image src='{{img_l}}' bindtap='preview_img'></image></view>//图片预览

<button bindtap='up_img'>上传</button>//上传

 

page({
     data:{
  img_l:''
  },
 chooseImg:function(){
    var _this = this;
    wx.chooseImage({
      
      count: 2, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths;
        console.log(res)
      _this.setData({
        img_l:res.tempFilePaths
      })
        console.log(res)
      
      }
    })
  },
 up_img:function() {
   var _this = this;
    wx.uploadFile({
      url: 'http://127.0.0.1/m_pro/upload.php', //接口
      filePath: _this.data.img_l[0],
      name: 'file',
      formData: {
        'user': 'test'
      },
      success: function (res) {
        var data = res.data;
        console.log(data);
        //do something
      },
      fail: function (error) {
        console.log(error);
      }
    })
  },
  preview_img:function(){
    wx.previewImage({
      current: this.data.img_l, // 当前显示图片的http链接
      urls: this.data.img_l // 需要预览的图片http链接列表
    })
  }
})

 

 

 

 

 

后台php:

<?php
 date_default_timezone_set("Asia/Shanghai"); //设置时区
$code = $_FILES['file'];//获取小程序传来的图片
if(is_uploaded_file($_FILES['file']['tmp_name'])) {  
    //把文件转存到你希望的目录(不要使用copy函数)  
    $uploaded_file=$_FILES['file']['tmp_name'];  
    $username = "min_img";
    //我们给每个用户动态的创建一个文件夹  
    $user_path=$_SERVER['DOCUMENT_ROOT']."/m_pro/".$username;  
    //判断该用户文件夹是否已经有这个文件夹  
    if(!file_exists($user_path)) {  
        //mkdir($user_path); 
        mkdir($user_path,0777,true); 
    }  

    //$move_to_file=$user_path."/".$_FILES['file']['name'];  
    $file_true_name=$_FILES['file']['name'];  
    $move_to_file=$user_path."/".time().rand(1,1000)."-".date("Y-m-d").substr($file_true_name,strrpos($file_true_name,"."));//strrops($file_true,".")查找“.”在字符串中最后一次出现的位置  
    //echo "$uploaded_file   $move_to_file";  
    if(move_uploaded_file($uploaded_file,iconv("utf-8","gb2312",$move_to_file))) {  
        echo $_FILES['file']['name']."--上传成功".date("Y-m-d H:i:sa"); 
 
    } else {  
        echo "上传失败".date("Y-m-d H:i:sa"); 

    }  
} else {  
    echo "上传失败".date("Y-m-d H:i:sa");  
}  


?>

 

 

 

 

 

 

 

  • 17
    点赞
  • 66
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 14
    评论
评论 14
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

随便起的名字也被占用

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值