使用wx.uploadFile方法上传给后端
wx.uploadFile({ url: 'http://127.0.0.1/upload.php', //后端接口 filePath: 本地图片, name: 'file', formData: { 'user': 'bfw' }, success: function (res) { var data = res.data; console.log(data); //do something }, fail: function (error) { console.log(error); } })
如果是uniapp的话
uni.uploadFile({ url: "http://127.0.0.1/upload.php", filePath: 本地图片, name: "file", formData: { "user": "bfw", //其他表单字段,可根据需求添加 }, success: function (res) { console.log(res) uni.showToast({ title: "上传成功" }) }, fail: function (err) { uni.showToast({ title: "上传失败" }) } })
后端php
<?php $file = $_FILES['file']; // 获取文件信息 $fileName = $file['name']; $fileTmpPath = $file['tmp_name']; $fileSize = $file['size']; $fileError = $file['error']; $fileType = $file['type']; // 指定保存文件的目录 $targetDirectory = 'uploads/'; $targetFilePath = $targetDirectory . $fileName; // 检查目标目录是否存在,如果不存在,则创建它 if (!is_dir($targetDirectory)) { mkdir($targetDirectory, 0777, true); } // 移动文件到目标目录 if (move_uploaded_file($fileTmpPath, $targetFilePath)) { echo "文件 {$fileName} 已成功上传。"; } else { echo "文件 {$fileName} 上传失败。"; } ?>
网友回复