Elementui's el-form and el-upload upload files and form data

Form data and file upload four ideas:

1. Files and form data are uploaded to the backend together, that is, an interface on the backend receives files and form data (this is a relatively old method, and the backend interface is also complex, and it is not easy to implement functions such as uploading file progress bars. recommend)

2. Upload the file first, then save the file in the backend (do not write to the database first), return the url of a file to the frontend, after the frontend receives the url and submit it to the backend together with other form data, the backend writes it into the database together (The backend is required to separate the interface for uploading files, recommended)

3. Upload the file first, then save the file at the back end, write it into the database, get the database id, return the database id to the front end, the front end sends the form data and the database id to the back end, and then the back end finds the record according to the database id , when updating the form data to the record

4. Upload the form data first, then save the form data at the back end, write it into the database, and then click the upload file on the front end (and pass the database id of the previously uploaded form data), after the back end receives the file and saves it, update the url into the form data (This method is the easiest to implement, but the user needs two operations to update the form data and files, unlike the second and third methods, which can be updated only after clicking to submit the form)

Upload files using el-upload

Also note that when using el-upload:

​ The request sent by the action attribute is an internally encapsulated ajax request, so it will not pass through your own encapsulated axios, so if you configure it as a proxy, you need to add a proxy prefix to the request yourself. If you use token identity verification, you You also need to add a request header to this request

​ The name attribute of el-upload is the parameter name of the request file sent this time, which needs to be changed to the parameter name required by the backend

The next step is to use the second method mentioned above to upload form data and files together

html part

      <el-form :rules="categoryRules" ref="categoryRuleForm" :model="categoryForm">
        <el-form-item label="分类名称" label-width="120px" prop="category_name">
          <el-input v-model="categoryForm.category_name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="分类图片" label-width="120px" prop="category_pic">
          <el-upload
          list-type="picture-card"
          :limit="1"
          :on-exceed="handleExceed"
          name="category_pic"
          action="/api/category/uploadPic"
          :headers="headerObj"
          :on-remove="handleRemove"
          :on-success="handleCategoryPicSuccess"
          :file-list="fileList"
          :before-upload="beforeCategoryPicUpload"
          >
            <i slot="default" class="el-icon-plus"></i>
            <div slot="file" slot-scope="{file}">
              <img
                class="el-upload-list__item-thumbnail"
                :src="file.url" alt=""
              >
              <span class="el-upload-list__item-actions">
                <span
                  class="el-upload-list__item-preview"
                  @click="handlePictureCardPreview(file)"
                >
                  <i class="el-icon-zoom-in"></i>
                </span>
                <span
                  v-if="!disabled"
                  class="el-upload-list__item-delete"
                  @click="handleDownload(file)"
                >
                  <i class="el-icon-download"></i>
                </span>
                <span
                  v-if="!disabled"
                  class="el-upload-list__item-delete"
                  @click="handleRemove(file)"
                >
                  <i class="el-icon-delete"></i>
                </span>
              </span>
            </div>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
        </el-form-item>
      </el-form>

js part

<script>
import {
    
    getToken} from '@/utils/auth'
import {
    
     getCategoryList, addCategory, updateCategory, deleteCategory, deleteCategoryPic } from '../../api/category'
export default {
    
    
  name: '',
  data () {
    
    
    return {
    
    

      categoryForm: {
    
    
        category_name: '',  // 分类名称
        category_pic: '', // 分类图片
      },

      // el-upload的请求头
      headerObj: {
    
    
        Authorization: `Bearer ${
      
      getToken()}`,  
      },

      fileList: [], // 上传时的图片列表(这里的图片将会显示出缩略图)

      // 大图预览相关
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false
    }
  },
  mounted () {
    
    
  },
  methods: {
    
    
    // 添加分类
    addCategory() {
    
    
          this.addDialogFormVisible = false
          let result = await addCategory({
    
    
            category_name: this.categoryForm.category_name,
            category_pic: this.categoryForm.category_pic,
          })
          if(result.code === 200){
    
    
            this.$message.success(result.message)
            this.getCategoryList()
          }else{
    
    
            this.$message.error(result.message)
          }
    },
    // 上传图片成功
    handleCategoryPicSuccess(res, file) {
    
    
      // 将服务器返回的文件url地址赋值给表单的category_pic,这样就可以在表单提交时将图片地址提交到服务器
      this.categoryForm.category_pic = res.data.category_pic
      this.getCategoryList()
      // 提示信息
      this.$message({
    
    
        message: '图片上传成功',
        type: 'success'
      });
    },
    // 上传图片前
    beforeCategoryPicUpload(file) {
    
    
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt1M = file.size / 1024 / 1024 < 1;

      if (!isJPG) {
    
    
        this.$message.error('上传头像图片只能是 JPG / PNG 格式!');
      }
      if (!isLt1M) {
    
    
        this.$message.error('上传头像图片大小不能超过 1MB!');
      }
      return isJPG && isLt1M;
    },
    // 图片超出限制
    handleExceed(files, fileList) {
    
    
      this.$message.error('当前限制选择 1 张图片!');
    },
    // 点击删除按钮
    async handleRemove(file) {
    
      // 删除图片
      // 删除缩略图图片
      this.fileList.splice(this.fileList.indexOf(file), 1);

      // 发送请求删除服务器图片
      let result = await deleteCategoryPic({
    
    
        category_pic: this.categoryForm.category_pic,
      })
      if(result.code === 200){
    
    
        this.$message.success(result.message)
      }else{
    
    
        this.$message.error(result.message)
      }
    },
    // 点击大图预览按钮
    handlePictureCardPreview(file) {
    
    
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 点击下载按钮
    handleDownload(file) {
    
    
      // 提示
      this.$message({
    
    
        message: '暂未开发',
        type: 'danger'
      });
    }
  }
}
</script>

Guess you like

Origin blog.csdn.net/cocogogogo/article/details/124347225