vue图片上传+预览+回显

vue

  <el-row>
 	   <el-col :span="12">
        <el-form-item label="身份证件照" prop="Identity_photo" required>
              <el-upload action="#" list-type="picture-card" :on-preview="handlePictureCardPreview"
                  :class="{hasChs:form.Identity_photo!= ''}" accept="image/jpeg,image/png,image/jpg"
                  :on-remove="handleRemove" :on-change="handleChange" ref="refUpload" :file-list="fileList"
                  :auto-upload="false">
                  <div slot="tip" class="el-upload__tip">只能上传jpg/png/jpeg文件,且单个不超过10M</div>
                  <i class="el-icon-plus"></i>
              </el-upload>
           
            <el-dialog title="图片预览" :visible.sync="dialogVisible" :append-to-body="true" width="50%"
              :modal="false">
                      <div style="padding: 15px;">
                          <el-image style="display: flex;" :src="dialogImageUrl">
                          </el-image>
                      </div>
                  </el-dialog>

      </el-form-item>
           </el-col>
             </el-row>

属性

 data(){
 	return:{
 	 url: '',
     fileList: [],
      filesData: [
          [],               
      ],
      dialogVisible: false,
      dialogImageUrl: '',
   	  form:{
          Identity_photo: '', //身份证件照               
      },
      load:{
          Identity_photo: '', //身份证件照               
      },
	}
 }

方法

methods:{
	 //图片预览
	 handlePictureCardPreview(file) {
         this.dialogImageUrl = file.url;
         this.dialogVisible = true;
    },
    //删除上传的图片
    handleRemove(file, fileList) {
         this.fileList=[]
         this.form.Identity_photo = ''
         if (file.status == 'ready') {
             const self = this
             let reader = new FileReader()
             reader.readAsDataURL(file.raw)
             reader.onload = function(event) {
                 let img_base64 = reader.result;
                 self.filesData[0].forEach(item => {
                     if (item == img_base64) {
                         //删除指定元素
                         self.filesData[0].splice(0, 1)
                     }
                 })
             }
         }
     },
     //图片改变时触发
      handleChange(file, fileList) {
          // 检查文件类型
            const isImage = file.raw.type.includes("image");
            if (!isImage) {
                this.$message.error("上传文件类型必须是图片!");
                return false
            }
            // 检查文件大小
            if (file.size > (10 * 1024 * 1024)) {
                this.$message.error(`上传文件大小不能超过10Mb`);
                this.$refs['refUpload'].handleRemove(file);
                return false;
            }
            // 检查文件数量
            if (fileList.length > 1) {
                this.$message.error(`上传文件最大数量为1`);
                this.$refs['refUpload'].handleRemove(file);
                return false;
            }
            this.load.Identity_photo=''
            this.fileList.splice(0, 1, file);
            this.form.Identity_photo = '1'
            // 读取文件
            var _self = this;
            var reader = new FileReader();
            reader.readAsDataURL(file.raw);
            reader.onload = function(event) {
                _self.filesData[0].push({
                    file: reader.result,
                    filename: file.name,
                });
            };
            return true;
        },
}

上传

 如果有回显的上传就需要下方操作,如果不需要回显就直接上传可以把this.load.Identity_photo 相关的操作都删掉 因为这边上
 传的 是base64,如果直接拿回显上传会是图片的缓存路径,所以需要有判断如果原来的没改变就用回显过来的base64数据   		
 如果原来的改变了就用新上传的图片base64
   this.$post('/hsa-pss-cw/physician/info/savePhysician', Object.assign({}, this.form, {
       Identity_photo:this.load.Identity_photo=='' ? this.filesData[0][0].file : this.load.Identity_photo 
     })).then(res => {})

回显

//因为保存的是图片的base64,所以回显
 this.fileList.push( {name:'a.jpeg',url:res.data.data.Identity_photo})
 this.load.Identity_photo=res.data.data.Identity_photo

css

el-upload的组件上的:class="{hasChs:form.Identity_photo!= ''}"这一步操作主要是vue的组件原因,
 因为我只需要上传一张图片,做了限制,上传了一张,上传的标识【就是一个加号图标】还在就显的不好看了,
所以如果这个图片属性有值了就把这个【加图标加上这个样式隐藏】
 <style>
    .hasChs /deep/ .el-upload--picture-card {
        display: none;
    }
 </style>
  • 7
    点赞
  • 34
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要实现vue+ajax+php的多图片回显,可以按照以下步骤进行: 1.在前端使用Vue的上组件,设置multiple属性为true,允许用户上多张图片。 2.在上组件的change事件中获取用户选择的图片文件,使用FormData对象将图片文件封装成表单数据。 3.使用axios或其他网络请求库将表单数据发送到服务器端。 4.在服务器端接收到表单数据后,解析出图片文件并保存到服务器的指定文件夹中。 5.将图片文件的URL返回给前端,用于回显图片。 下面是一个简单的示例代码: 前端代码: ```html <template> <div> <input type="file" ref="fileInput" @change="handleUploadChange" multiple> <button @click="uploadImages">上图片</button> <div v-if="imageUrls.length > 0"> <div v-for="imageUrl in imageUrls" :key="imageUrl"> <img :src="imageUrl" style="width: 200px; height: 200px;"> </div> </div> </div> </template> <script> import axios from 'axios' export default { data () { return { imageFiles: [], imageUrls: [] } }, methods: { handleUploadChange () { this.imageFiles = Array.from(this.$refs.fileInput.files) }, uploadImages () { const formData = new FormData() this.imageFiles.forEach(file => { formData.append('images[]', file) }) axios.post('/api/upload_images.php', formData) .then(response => { this.imageUrls = response.data.imageUrls }) .catch(error => { console.log(error) }) } } } </script> ``` 后端代码(使用PHP): ```php <?php if ($_SERVER['REQUEST_METHOD'] === 'POST') { $imageUrls = []; $uploadDir = '/path/to/upload/folder/'; foreach ($_FILES['images']['error'] as $key => $error) { if ($error === UPLOAD_ERR_OK) { $tmpName = $_FILES['images']['tmp_name'][$key]; $fileName = basename($_FILES['images']['name'][$key]); $uploadPath = $uploadDir . $fileName; move_uploaded_file($tmpName, $uploadPath); $imageUrls[] = '/upload/' . $fileName; } } header('Content-Type: application/json'); echo json_encode(['imageUrls' => $imageUrls]); } ``` 在上面的示例代码中,使用了PHP的$_FILES变量来获取上图片文件。通过遍历$_FILES['images']['error']数组,可以判断每个文件是否上成功。如果上成功,将文件移动到指定的上目录中,并将文件的URL保存到$imageUrls数组中。最后,将$imageUrls数组以JSON格式返回给前端,用于回显图片。 需要注意的是,上文件时需要确保服务器端的上目录有写入权限,否则会导致上失败。同时,需要对上的文件进行安全性检查,防止上恶意文件。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值