有需求联系

Information

- 信息浏览 -

微信小程序单图片上传代码(PHP)

2023-09-07 335

wxml代码

<view>

  <button bindtap="bindUpload">上传图片</button>

</view>

<view>

<image src="{{imgsrc}}" mode="widthFix"/>

</view>


JS代码

Page({

  data: {

    imgsrc:""

  },

  bindUpload: function() {

    var _this=this

    wx.chooseImage({

      count: 1, // 默认9

      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有

      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有

      success: function(res) {

        wx.uploadFile({

          //php 服务器地址

          url: 'http://127.0.0.1/api.php',

          filePath: res.tempFilePaths[0],

          name: 'file',

          // 其他字段(可选)

          formData: {

            user: 'test',

            name:'other data'

          },

          success: function(res) {

            console.log(res.data)

            let result=JSON.parse(res.data)

            _this.setData({

              imgsrc:result.imgsrc

            })

          }

        })

      },

    })

  }


})


后端PHP代码

<?php

// 随图片上传的其他字段数据 (可选)

$user = $_REQUEST['user'];

$name = $_REQUEST['name'];


// 单图片上传

if (!empty($_FILES['file'])) {

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

    // 获取文件后缀名

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

    $extension = end($temp);


    // 判断当前目录下的 upload 目录是否存在该文件夹

    $new_file = "upload/" . date('Ym', time()) . "/";

    if (!file_exists($new_file)) {

        //检查是否有该文件夹,如果没有就创建,并给予最高权限

        mkdir($new_file, 0700);

    }


    // 生成唯一的文件名

    $imageName = uniqid() . '.' . $extension;

    // 文件保存地址

    $uploadPic = $new_file . $imageName;


    // 允许上传的图片后缀

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

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

    // 图片最大允许5M=5242880字节 && 允许的格式

    if ($allowedSize < 5242880 && in_array($extension, $allowedExts)) {

        // 将图片文件移动到本地

        move_uploaded_file($image, $uploadPic);

        $imgsrc = "http://127.0.0.1/" . $uploadPic;

        // 返回处理后的图片路径

        $res = [

            "imgsrc" => $imgsrc,

            "code" => "OK",

            "user" => $user,

            "name" => $name

        ];

        echo json_encode($res);

    }

}



Copyright © 2024 镇江小蚂蚁信息科技有限公司 All Rights Reserved.