vue3----ThinkPHP5文件上传案例

251 阅读1分钟

这是一个前端使用v3,后端使用THinkPHP的一个毕设,做到图片上传的功能就记录一下

前端代码

把文件以formData的形式传递过去,代码赋值,可直接使用

<template>
  <el-upload
    v-model:file-list="fileList"
    list-type="picture-card"
    :on-preview="handlePictureCardPreview"
    :before-upload="beforeUpload"
    :on-remove="handleRemove"
    style="text-align: center"
  >
    <div style="display: flex; flex-direction: column; align-items: center">
      <span style="margin-bottom: 10px">上传图片</span>
      <el-icon :size="20"><Plus /></el-icon>
    </div>
  </el-upload>

  <el-dialog v-model="dialogVisible">
    <img w-full :src="dialogImageUrl" alt="Preview Image" />
  </el-dialog>
</template>

<script setup>
import { ref } from 'vue'
import axios from 'axios'
const fileList = ref([])
const dialogImageUrl = ref('')
const beforeUpload = (file) => {
  const formData = new FormData()
  //传递两个参数
  formData.append('file', file)
  formData.append('proId', props.proId)
  axios
    .post('http://tp5:8005/index/ProImgCon/uploadImageFile', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    .then((res) => {
    })
    .catch(() => {
    })
}
const handleRemove = (uploadFile) => {}
const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url
  dialogVisible.value = true
}
</script>


后端代码

为了接个毕设,临时学的

public function uploadImageUser()
{   
    //接收两个参数,request不用引入,直接使用
    $file = request()->file('file');
    $id = request()->post('id');
    if (empty($file)) {
            return json(['code' => 1,"msg" => '请选择上传文件']);
        }
        else{
            // 移动到框架应用根目录/uploads/ 目录下
            $file_name=$file->getInfo()['name'];
            $tmp=strrchr($file_name,'.');
            $file_new_name=time().$tmp;
            //拼接图片路径,这个地方要注意一下,很有可能访问不到,到时候加或者减index路径,试试
            $info = $file->move(Env::get('root_path') . 'public' . DIRECTORY_SEPARATOR . 'static' . DIRECTORY_SEPARATOR . 'img', $file_new_name);
            if($info){
                $url = request()->domain() . '/static/img/' . $file_new_name;
                $res = ClientUserModel::get($id);
                $res->location = $url;
                $res->save();
                return  json(['code' => 200,"msg" => '修改成功','url'=>$url]);
            }else{
                $code = [
                    "msg"=>"头像修改",
                    'code' => 500 ,
                ];
                return json($code);
            }
        }