小程序/Vant UI 实现文件的上传
第一次接触小程序上传的时候,自己经过一些实验测试并记录下来以供大家学习。
使用vant UI的官网地址:Vant Weapp - 轻量、可靠的小程序 UI 组件库
如何不使用UI框架的前提下或许有些许出入,但不影响整体的实现细节。
引入官网上的代码:
第一次看上面代码的时候会存在些许疑虑,懂的不是十分的透彻。现在也是懵懵懂懂,主要知道实现的功能也没仔细关注实现的细节。afterRead是上传成功的回调函数,fileList是让图片可以回显到上传文件的组件,可以设置固定的URL来实现回显。
以下的代码是我对上面代码的部分修改来调用后台提供的接口。
Page({
data: {
fileList: [],
},
afterRead(event) {
let that = this
const { file } = event.detail;
// 当设置 mutiple 为 true 时, file 为数组格式,否则为对象格式
wx.uploadFile({
url: 'http://127.0.0.3/upload_file.php', //接口的提供地址
filePath: file.url,
name: 'file',
formData: { user: 'test' },
success(res) {
// 上传完成需要更新 fileList
let fileList = []
let path = "http://127.0.0.3/" + res.data
fileList.push({ url: path });
console.log(fileList);
that.setData({ fileList: fileList });
// console.log(res.data);
},
});
},
});
这里的res.data就是我提供的文件名称,用拼接字符串的方法来提供url来给fileList赋值。赋值完成后就可以实现图片的回显了,实现的细节如下图所示:
为了大家能够复原实验,将后台的接口代码展示出来供大家学习。
<?php
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"))
) //文件大小B && ($_FILES["file"]["size"] < 2000000)
{
if ($_FILES["file"]["error"] > 0) //出错
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
}
else //上传文件到临时系统
{
//echo "Upload: " . $_FILES["file"]["name"] . "<br />";
//echo "Type: " . $_FILES["file"]["type"] . "<br />";
//echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
//echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";
if (file_exists("upload/" . $_FILES["file"]["name"])) //文件存在
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else //移动文件到指位置
{
//获得UUID
$uuid = uuid();
$uuid = str_replace('-','',$uuid);
$extension = explode(".",$_FILES["file"]["name"] );
$key = count($extension) - 1;
$suffix = $extension[$key];
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $uuid.".".$suffix);
echo "upload/" . $uuid.".".$suffix; //Stored in: " . "upload/" . $uuid.$suffix
//echo "Stored in: " . "upload/". $uuid.".".$suffix;
}
}
}
else
{
echo "Invalid file"; //文件类型错误
}
function uuid()
{
$chars = md5(uniqid(mt_rand(), true));
$uuid = substr ( $chars, 0, 8 ) . '-'
. substr ( $chars, 8, 4 ) . '-'
. substr ( $chars, 12, 4 ) . '-'
. substr ( $chars, 16, 4 ) . '-'
. substr ( $chars, 20, 12 );
return $uuid ;
}
?>