小程序前台页面:
//图片上传 --添加图片
afterRead(event) {
var that = this;
const { file } = event.detail;
//console.log(file.path);
// 当设置 mutiple 为 true 时, file 为数组格式,否则为对象格式
wx.uploadFile({
url: \'http://www.xcxshoplars.com/api/upload_image\', // 仅为示例,非真实的接口地址
filePath: file.path,
name: \'file\',
formData: { user: \'test\' },
success(res) {
console.log(res.data);
var datas = JSON.parse(res.data);
var image = "http://www.xcxshoplars.com"+datas.data; //后台传过来的地址地址
var fileLists = [];
fileLists = that.data.fileList
let imagesInfo = { url: image}
fileLists.push(imagesInfo)
that.setData({
fileList:fileLists
});
}
});
},
//图片上传-点击删除
deleteImages(event){
var image_index = event.detail.index
var fileList_new = this.data.fileList;
fileList_new.splice(image_index,1);
this.setData({
fileList: fileList_new
})
// console.log(event.detail.index);
},
data: {
fileList: [
// { url: \'https://img.yzcdn.cn/vant/leaf.jpg\', name: \'图片1\' },
// // Uploader 根据文件后缀来判断是否为图片文件
// // 如果图片 URL 中不包含类型信息,可以添加 isImage 标记来声明
// {
// url: \'http://iph.href.lu/60x60?text=default\',
// name: \'图片2\',
// isImage: true
// }
]
},
小程序后台页面(post接收):
class FeedbackController extends Controller
{
public function image(Request $request)
{
$file=$request->file(\'file\');
//值如:uploads/images/avatars/201709/21/
$folder_name = "/uploads/images/avatars/" . date("Ym/d", time());
$upload_path = public_path() . \'/\' . $folder_name;
// 获取文件的后缀名,因图片从剪贴板里黏贴时后缀名为空,所以此处确保后缀一直存在
$extension = strtolower($file->getClientOriginalExtension()) ?: \'png\';
// 拼接文件名,加前缀是为了增加辨析度,前缀可以是相关数据模型的 ID
// 值如:1_1493521050_7BVc9v9ujP.png
$filename = time() . \'_\' . Str::random(10) . \'.\' . $extension;
// 将图片移动到我们的目标存储路径中
$file->move($upload_path, $filename);
$data = [
\'img_src\'=>$folder_name.\'/\'.$filename, //图片地址
\'create_time\'=>date(\'Y-m-d H:i:s\'),
];
DB::table(\'feedback\')->insert($data);
return response()->json([\'status\'=>\'400\',\'msg\'=>\'失败\',\'data\'=>$data[\'img_src\']]);
}
}
上传七牛空间:
//七牛云配置文件,在七牛云控制台个人中心可以查看,这些配置可以写在 .env里面 const Ak =\'你自己的AK\'; const SK=\'你自己的sk\'; const DOMAIN=\'图片的专属域名\'; const BUCKEY=\'你增加的那个存储空间\';
//图片上传七牛空间 public function image_qiniu(Request $request){ $file=$request->file(\'file\'); $auth = new Auth(self::Ak,self::SK); //生成上传图片的token $extension = strtolower($file->getClientOriginalExtension()) ?: \'png\'; $token = $auth->uploadToken(self::BUCKEY); $key = time().rand(0,9999).".".$extension; $uploadMgr = new UploadManager(); list($ret,$err) = $uploadMgr->putFile($token,$key,$file); if($ret){ //这里返回的是一个bucket的域名,在前面添加http://后就可以正常看到图片 $data = self::DOMAIN.\'/\'.$key; return response()->json([\'status\'=>\'400\',\'msg\'=>\'失败\',\'data\'=>$data]); }else{ return null; }