您的位置:首页 > 移动开发 > 微信开发

小程序的图片上传wx.uploadFile及后台PHP接收文件并存储到服务器

2018-01-30 14:03 1101 查看
前台代码wxml:

<button bindtap='chooseImg'>选择图片</button>//图片选择
<view><image src='{{img_l}}' bindtap='preview_img'></image></view>//图片预览

<button bindtap='up_img'>上传</button>//上传

page({
data:{
img_l:''
},
chooseImg:function(){
var _this = this;
wx.chooseImage({

count: 2, // 默认9
sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
success: function (res) {
// 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片
var tempFilePaths = res.tempFilePaths;
console.log(res)
_this.setData({
img_l:res.tempFilePaths
})
console.log(res)

}
})
},
up_img:function() {
var _this = this;
wx.uploadFile({
url: 'http://127.0.0.1/m_pro/upload.php', //接口
filePath: _this.data.img_l[0],
name: 'file',
formData: {
'user': 'test'
},
success: function (res) {
var data = res.data;
console.log(data);
//do something
},
fail: function (error) {
console.log(error);
}
})
},
preview_img:function(){
wx.previewImage({
current: this.data.img_l, // 当前显示图片的http链接
urls: this.data.img_l // 需要预览的图片http链接列表
})
}
})

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

//$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");
}

?>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐