亲宝软件园·资讯

展开

vue文件上传

Echo丶洛尘 人气:0

前端

一、uploadList.vue

① 首先在页面中添加一个放置图片的位置,来展示图片

	<el-table-column
	  prop="upload"
	  label="高校证明材料">
	  <template slot-scope="scope" v-if="scope.row.upload">
	    <el-image
	      style="height: 30%;width:30%;margin-left:22%;"
	      :src="src"
	      v-for="(src, index) in scope.row.upload.split(',')" :key="index"
	      :preview-src-list="scope.row.upload.split(',')">
	    </el-image>
	  </template>
	</el-table-column>

② 在data中添加相关属性

data () {
	return{
		searchForm:{
			upload: ''
		},
		loading: false,
        src: '' // 上传图片
}

二、testForm.vue

① 在表单中添加下列代码

<el-col :span="12">
		    <el-form-item label="上传图片" prop="upload">
		      <el-upload
		        list-type="picture-card"
		        :action="`${this.$http.BASE_URL}/sys/file/webupload/upload?uploadPath=/upload`"
		        :headers="{token: $cookie.get('token')}"
				:before-upload="beforeUpload"
		        :on-preview="(file, fileList) => {
		            $alert(`<img style='width:100%' src=' ${(file.response && file.response.url) || file.url}'/>`,  {
		              dangerouslyUseHTMLString: true,
		              showConfirmButton: false,
		              closeOnClickModal: true,
		              customClass: 'showPic'
		            });
		        }"
		        :on-success="(response, file, fileList) => {
		           inputForm.collegeMaterials = fileList.map(item => (item.response && item.response.url) || item.url).join('|')
		        }"
		        :on-remove="(file, fileList) => {
		          $http.post(`/sys/file/webupload/deleteByUrl?url=${(file.response && file.response.url) || file.url}`).then(({data}) => {
		            $message.success(data.msg)
		          })
		          inputForm.collegeMaterials = fileList.map(item => item.url).join('|')
		        }"
		        :before-remove="(file, fileList) => {
		          return $confirm(`确定删除 ${file.name}?`)
		        }"
		        multiple
		        :limit="1"
		        :on-exceed="(files, fileList) =>{
		          $message.warning(`当前限制选择 1 个图片,本次选择了 ${files.length} 个文件,共选择了 ${files.length + fileList.length} 个图片`)
		        }"
		        :file-list="picArra">
		        <i class="el-icon-plus"></i>
		      </el-upload>
		      <el-dialog :visible.sync="dialogVisible">
		        <img width="100%" :src="dialogImageUrl" alt="">
		      </el-dialog>
		  </el-form-item>
		</el-col>

② 在data中添加相关属性

 data () {
      return {
        picArra: [],
        dialogImageUrl: '',
        dialogVisible: false,
        disabled: false,
        inputForm: {
        upload: '',
        }
      }
 }

③ 在method中替换原始的 this.$nextTick

        this.visible = true
        this.loading = false
        // 重置图片路径,否则会加载上一次添加的图片
        this.picArra = []
        this.$nextTick(() => {
          this.$refs.inputForm.resetFields()
          if (method === 'edit' || method === 'view') { // 修改或者查看
            this.loading = true
            this.$http({
            // upload为controller层的注解路径,替换一下即可
              url: `/upload/queryById?id=${this.inputForm.id}`,
              method: 'get'
            }).then(({data}) => {
              this.inputForm = this.recover(this.inputForm, data.college)
              this.inputForm.upload.split('|').forEach((item) => {
                if (item.trim().length > 0) {
                  this.picArra.push({name: decodeURIComponent(item.substring(item.lastIndexOf('/') + 1)), url: item})
                }
              })
              this.loading = false
            })
          }
        }),
                // 查看图片
      handlePictureCardPreview (file) {
        this.dialogImageUrl = file.url
        this.dialogVisible = true
      },
      continueDoSubmit () {
        this.$refs['inputForm'].validate((valid) => {
          if (valid) {
            this.$emit('addRow', this.oldInputForm, JSON.parse(JSON.stringify(this.inputForm)))
            this.$refs['inputForm'].resetFields()
          }
        })
      },
      // 判断上传图片的格式
      beforeUpload (file) {
        if (file) {
          const suffix = file.name.split('.')[1]
          const size = file.size / 1024 / 1024 < 2
          if (['png', 'jpeg', 'jpg'].indexOf(suffix) < 0) {
            this.$message.error('上传图片只支持 png、jpeg、jpg 格式!')
            this.$refs.upload.clearFiles()
            return false
          }
          if (!size) {
            this.$message.error('上传文件大小不能超过 2MB!')
            return false
          }
          return file
        }
      }

后端

后端只需要将相应的字段添加好即可,controller层不需要改动。

加载全部内容

相关教程
猜你喜欢
用户评论