美文网首页
小程序的图片上传wx.uploadFile及后台PHP接收文件并

小程序的图片上传wx.uploadFile及后台PHP接收文件并

作者: zhaoxiaohui520 | 来源:发表于2020-04-15 21:51 被阅读0次

前台代码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");  
}  
 
 
?>

相关文章

网友评论

      本文标题:小程序的图片上传wx.uploadFile及后台PHP接收文件并

      本文链接:https://www.haomeiwen.com/subject/pkqkvhtx.html