uni-app+thinkphp: 多图片文件上传(hbuilderx 3.7.3)
一,js代码
<template> <view> <view style="width:750rpx;background: #ff0000;"> <uni-grid :showBorder="false" :column="4" :highlight="true" @change="change"> <uni-grid-item v-for="(item, index) in imgArr" :index="index" :key="index"> <view class="grid-item-box" > <image class="preview" mode="aspectFit" :src="item" ></image> </view> </uni-grid-item> </uni-grid> </view> <button style="width:550rpx;margin-left: 100rpx;margin-top: 30rpx;" type="primary" @tap="chooseImage">选择图片</button> <button style="width:550rpx;margin-left: 100rpx;margin-top: 30rpx;" type="primary" @tap="upload">上传图片</button> </view> </template> <script> export default { data() { return { imgArr:[], } }, methods: { //选择图片 chooseImage(){ uni.chooseImage({ count: 10, sizeType:['copressed'], success:res => { //注意此处的写法,否则可能不能预览 this.imgArr=res.tempFilePaths; } }) }, //上传图片 upload(){ console.log("length:"+this.imgArr.length);
//判断选中的文件数量 if (this.imgArr.length <= 0) { let tip = '未选择图片文件!'; uni.showToast({ title:tip, icon:"error", }) return false; } //遍历上传 for(let i=0;i<this.imgArr.length;i++){ uni.uploadFile({ url: '/api/goods/uploadone', //接口地址 filePath: this.imgArr[i], name: 'file', formData: { 'user': 'test' }, success: (res) => { let data = JSON.parse(res.data); if (data.code == 0){ console.log("上传成功:"+data.data.url); } else { console.log("上传成功:"+data.msg); } } }); } uni.showToast({ title: '上传完成', duration: 1000, }); } } } </script> <style> .preview { background: gray; width:175rpx; height:175rpx; margin-left: 10rpx; margin-top: 10rpx; } </style>
说明:刘宏缔的架构森林是一个专注架构的博客,
网站:https://blog.imgtouch.com
原文: https://blog.imgtouch.com/index.php/2023/06/05/uniapp-thinkphp-duo-tu-pian-wen-jian-shang-chuan-hbuilderx/
对应的源码可以访问这里获取: https://github.com/liuhongdi/
或: https://gitee.com/liuhongdi
说明:作者:刘宏缔 邮箱: 371125307@qq.com
二,php代码
//上传单一文件 public function uploadOne() { //判断是否能获取文件 $file = request()->file('file'); if (is_null($file)) { return Result::ErrorCode(11,'没有文件上传'); } //判断文件是否存在 $path = $file->getPathname(); if (is_file($path)){ $ext = strtolower($file->getOriginalExtension()); if (trim($ext) == '') { return Result::ErrorCode(1012,'文件名有错误'); } $newName = date('YmdHis').rand(1000,9999); $newName = $newName . '.' . $ext; $destDir = "/var/www/html/staffhead"; //移动文件到指定目录,并重命名为新文件名 $file->move($destDir, $newName); //$user = $this->request->param('user','','string'); // var_dump($user); $imgUrl = "http://api.lhdtest.com/staffhead/".$newName; $res = ['url'=>$imgUrl]; return Result::Success($res); } else { //echo "文件不存在:<br/>"; return Result::ErrorCode(1011,'文件不存在'); } }