美文网首页
PHP实现小程序的图片上传接口

PHP实现小程序的图片上传接口

作者: 洗耳恭听_kai | 来源:发表于2018-07-22 15:23 被阅读657次

小程序中代码:

js

Page({
  data: {
    avatarUrl:null
  },
  //事件处理函数
  bindViewTap: function() {

    var that = this;
    wx.chooseImage({
      success: function (res) {
        var tempFilePaths = res.tempFilePaths
        wx.uploadFile({
          url: 'http://127.0.0.1/text/index.php', //仅为示例,非真实的接口地址
          filePath: tempFilePaths[0],
          name: 'file',
          formData: {
            'user': 'test'
          },
          success: function (res) {
            var data = res.data
            console.log(data)
          },
          fail:function (error) {
            console.log(error)
          }
        })
      }
    })
  },

  preview_img: function () {
    wx.previewImage({
      current: this.data.avatarUrl, // 当前显示图片的http链接
      urls: this.data.avatarUrl // 需要预览的图片http链接列表
    })
  }
})

wxml:

<!--index.wxml-->
<view class="container">
  <view class="userinfo">
      <button bindtap='bindViewTap'>选择图片</button>
  </view>

   <view><image src='{{avatarUrl}}' bindtap='preview_img'></image></view>
</view>

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']."/text"."/m_pro/".$username;
     
    //判断该用户文件夹是否已经有这个文件夹  
    if(!file_exists($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");  
}  

相关文章

网友评论

      本文标题:PHP实现小程序的图片上传接口

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