关于小程序上传图片到服务器

最近学习小程序编程,上传图片到服务器一直不成功,网上查了不少资料方知是少了服务器端的接收代码。现在把代码贴出来供大家参考:
upanddown.wxml文件:

<!--pages/upanddown/upanddown.wxml-->
<view class="FileUploadContainer">
  <view class="title">Upload File</view>
  <button bindtap="click">点击访问</button>
  <!--文件上传-->
  <view class="demo-box">
    <image wx:if="{{src}}" src="{{src}}" mode="aspectFit"></image>
    <button bindtap="chooseImage">To choose File</button>
    <button type="primary" bindtap="UploadFile">Upload</button>
  </view>
  <!--文件下载-->
  <view>
    <button type="primary" bindtap="DownloadFile">Download</button>
    <image mode="aspectFit" wx:if="{{img}}" src="{{img}}" bindtap="previewImage"></image>
    <button type="primary" bindtap="reset">Reset</button>
  </view>
</view>

upanddown.js文件:

// pages/upanddown/upanddown.js
Page({

    /**
     * 页面的初始数据
     */
    data: {
        src:'',//上传图片路径
        img:''
    },

    /**
   * 查看是否能连接到服务器
   */
  click:function(){
    wx.request({
      url: 'http://localhostt/',
      data:{
        message:"message from wechat"
      },
      method:'GET',
      success:(res)=>{
        if(res.statusCode==200){
          console.log(res.data)
        }
        if(res.statusCode==404){
          wx.showToast({
            title: '找不到请求对象',
            icon:'none'
          })
          console.log("找不到请求对象")
        }
      },
      fail:(res)=>{
        wx.showToast({
            title: '找不到请求对象',
            icon:'none'
          })
        console.log("请求失败")
      }
    })
  },
  chooseImage:function(){
    var that=this;
    wx.chooseImage({
      count: 1,
      sizeType: ['original','compressed'],//指定是原图还是压缩图,默认二者都有
      sourceType: ['album','camera'],//指定是相册还是相机,默认二者都有
     success:(res)=>{
       let src=res.tempFilePaths[0];
       console.log(src);
       that.setData({
         src:src
       })
     }
    })
  },
  UploadFile:function(){
    var that=this;
    let src=this.data.src;
    console.log(src);
    if(src==''){
      wx.showToast({
        title: 'Plase choose file',
        icon:'none'
      })
    }
    else{
      var uploadTask=wx.uploadFile({
        filePath: src,
        name: 'file',
        url: 'http://localhost/imgupload.php',
        formData:{
          'filename':'fmw081418108.jpg'
        },
        success:function(res){
          console.log('[上传文件] 成功:', res)
          wx.showToast({
            title: res.data,
          })
        },
        fail: function (res) {
          console.log('上传失败');
          }
      })
      uploadTask.onProgressUpdate((res)=>{
        console.log('上传进度',res.progress)
        console.log('已经上传的数据长度',res.totalBytesSent)
        console.log('与其需要上传的数据总长度',res.totalBytesExpectedToSend)
      })
    }
  },
  previewImage:function(){
    wx.previewImage({
      current:this.data.img,
      urls:this.data.img
    })
  },
  DownloadFile:function(){
    var that=this;
    var filename="3.png";
    var downloadTask = wx.downloadFile({
      url: 'http://localhost/3.png',
      success:(res)=>{
        if(res.statusCode==200){
          console.log("下载成功");
          wx.playVoice({
            filePath: res.tempFilePath
          });
          let img=res.tempFilePath;
          console.log(res);
          that.setData({
            img:img
          })
        }
        else{
          console.log("下载失败",res.statusCode);
        }
      }
    })
    downloadTask.onProgressUpdate((res) => {
      console.log('下载进度', res.progress)
      console.log('已经下载的数据长度', res.totalBytesWritten)
      console.log('预期需要下载的数据总长度', res.totalBytesExpectedToWrite)
    })
  },
})

服务器端的imgupload.php文件

<?php

$imgurl="https://localhost/";

// 允许上传的图片后缀

$allowedExts = array("gif", "jpeg", "jpg", "png");

$temp = explode(".", $_FILES["file"]["name"]);

// echo $_FILES["file"]["size"];

$extension = end($temp);     // 获取文件后缀名

if ((($_FILES["file"]["type"] == "image/gif")

        || ($_FILES["file"]["type"] == "image/jpeg")

        || ($_FILES["file"]["type"] == "image/jpg")

        || ($_FILES["file"]["type"] == "image/pjpeg")

        || ($_FILES["file"]["type"] == "image/x-png")

        || ($_FILES["file"]["type"] == "image/png"))

    && ($_FILES["file"]["size"] < 20480000)   // 小于 20M,这个自己限制

    && in_array($extension, $allowedExts))

{

    $imgpath=$_GET['imgpath'];  //获取传来的图片分类,用于在服务器上分类存放

    $code = $_FILES['file'];//获取小程序传来的图片

    $uploaded_file=$_FILES['file']['tmp_name'];

    $user_path=$_SERVER['DOCUMENT_ROOT'].$imgpath;  //放到服务器下指定的文件夹

    if(file_exists($user_path)){

    }else{

        mkdir($user_path,0777);

    }

    $size=$_FILES["file"]["size"];

    $date=date('Ymd'); //得到当前时间

    $newfilename='3.'.$extension; //得到一个新的文件名,可根据自己需求设定,sham用的时间加上图片文件大小来命名

    $move_to_file=$user_path."/".$newfilename;

    $file_true_name=$imgurl.$imgpath."/".$newfilename;

    //echo $file_true_name;

    $filename = json_encode($file_true_name);//把数据转换为JSON数据.

    // echo $move_to_file;

    move_uploaded_file($uploaded_file,iconv("utf-8","gb2312",$move_to_file));



//下面的代码是用来生成缩略图的

    $thump = $user_path."/thumb/";   //这个缩略图文件夹地址自己设置,这个是在原图文件夹里面增加1个子目录thumb用于存放缩略图

    if(file_exists($thump)){

    }else{

        mkdir($thump,0777);

    }

    $imgs = $newfilename;

    $imgss=$user_path."/".$imgs;

    $img_arr = getimagesize($imgss);

    $pecent = $img_arr[0]/$img_arr[1];

    $width = 200;    //这里是缩略图的尺寸,自行设置

    $height = 200/$pecent;

//下面是根据不同图片后缀,执行不同的图片生成代码

    if($_FILES["file"]["type"] == "image/png"){

        $img_in = imagecreatefrompng($imgss);

    }elseif($_FILES["file"]["type"] == "image/jpg" || $_FILES["file"]["type"] == "image/jpeg" || $_FILES["file"]["type"] == "image/pjpeg"){

        $img_in = imagecreatefromjpeg($imgss);

    }elseif($_FILES["file"]["type"] == "image/gif"){

        $img_in = imagecreatefromgif($imgss);

    }



    $img_out = imagecreatetruecolor($width, $height);

    imagecopyresampled($img_out, $img_in, 0, 0, 0, 0, $width, $height, $img_arr[0], $img_arr[1]);

    imagejpeg($img_out,$thump.$imgs,100);

    imagedestroy($img_out);

    imagedestroy($img_in);

    //这里最后输出缩略图的网址,让小程序读取到,用于放入input用来传到数据库中

    echo $imgurl.$imgpath."/thumb/".$newfilename;

}else

{

    echo "上传错误";

}

?>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值