首页
归档
笔记
树洞
搜索
友言

文章详情

Interesting People Record Interesting.

/ PHP / 文章详情

PHP_thinkphp5上传多张图片

Sonder
2023-01-10
3101字
8分钟
浏览 (2.5k)

.html

复制代码
<html lang="en">

<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <meta http-equiv="X-UA-Compatible" content="ie=edge">
   <title>上传图片</title>
   <script src='https://cdn.jsdelivr.net/npm/vue/dist/vue.js'></script>
   <link rel='stylesheet' href='https://cdn.jsdelivr.net/npm/vant@2.12/lib/index.css'/>
   <script src='https://cdn.jsdelivr.net/npm/vant@2.12/lib/vant.min.js'></script>
   <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>

<body>
   <div id="app">
       <van-uploader v-model="fileList" multiple :after-read="afterRead" max-count="10" />
   </div>
</body>
</html>
<script>
   var vm = new Vue({
       el: '#app',
       data: {
           fileList: [],
       },
       methods: {
           afterRead(file) {
               // 发送 POST 请求
               // console.log(this.fileList);
               let formdata = new FormData();
               this.fileList.forEach(item => {
                   formdata.append('file[]',item.file)
               });
               axios({
                   method: 'post',
                   url: 'http://127.0.0.3/index/index/upload',
                   data: formdata
               }).then((res) => {
                   console.log(res);
               }).catch((err) => {

               });
           },
       }
   });
</script>
image.png

index.php

复制代码
<?php
namespace app\index\controller;
use think\Db;
use think\Controller;
use think\Request;
class Index extends \think\Controller
{
   public function index(){

       return 'index';
   }
   //图片上传
       // 上传图片接口(多张)
   public function upload_img()
   {
       //获取当前域名
       $request = Request::instance();
       $domain = $request->domain();
       $files = request()->file('file');    //image 前段传递对象流数组,接收参数为多个 file[]:(binary)
       if(!$files) {
           return json(['code' => false, 'msg' => '参数不存在!']);
       }
       $urlArray = [];
       foreach($files as $file){
           // 移动到框架应用根目录/public/uploads/ 目录下
           $info = $file->move(ROOT_PATH . 'public' . DS . 'upload');
           $src = date('Ymd') . '/' . $info->getFilename();
           $image = \think\Image::open(ROOT_PATH . 'public' . DS . 'upload/'.$src);
           // 按照原图的比例生成一个最大为600*600的缩略图替换原图
           $image->thumb(600, 600)->save(ROOT_PATH . 'public' . DS . 'upload/'.$src);
           if($info){
               $urlArray[]= $domain."/upload/".$src;
           }else{
               // 上传失败获取错误信息
               return json(['code' => false, 'url' => $file->getError()]);
           }
       }
       return json(['code' => true, 'url' => $urlArray]);
   }
}
image.png

本文转自 https://blog.csdn.net/weixin_44599931/article/details/115393040,如有侵权,请联系删除。

下一篇 / 使用CSS实现微信朋友圈的九宫格图片自适应

🎯 相关文章

💡 推荐文章

🕵️‍♂️ 评论 (0)