1. 程式人生 > >小程式的圖片上傳wx.uploadFile及後臺PHP接收檔案並存儲到伺服器

小程式的圖片上傳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);  
    }  

    //$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");  
}  


?>