vue+element-ui怎么把表单数据和图片一起提交到后端呢?能获取图片大小和名称么?

vue+element-ui怎么把表单数据和图片一起提交到后端呢?能获取图片大小和名称么?

3个回答

直接上代码吧,满意希望给我采纳,谢谢


  <el-dialog :title="'添加'" :visible.sync="formVisibleAdd" :close-on-click-modal="false" width="30%" @close="closeDialogAdd">
    <el-form :model="addForm" label-width="100px" :rules="rules" ref="addForm">
      <el-form-item label="名称" prop="name">
        <el-input v-model="addForm.name" placeholder="请输入名称" />
      </el-form-item>

      <el-form-item label="编号" prop="code">
        <el-input type="text" v-model="addForm.code" placeholder="请输入编号" />
      </el-form-item>

      <el-form-item label="图片">
        <el-upload class="upload-demo" accept="image/jpeg,image/jpg,image/png" :auto-upload="false" ref="upload" action="" :on-change="uploadSectionFile" :on-remove="removeImage" list-type="picture">
          <el-button size="small" type="primary" v-show="isUploadShowHide">点击上传</el-button>
          <div slot="tip" class="el-upload__tip" v-show="isUploadShowHide" style="margin-top: -40px;idth: 300px;margin-left: 100px;text-align: left;color: red;">只能上传jpg/png文件,且不超过500kb</div>
        </el-upload>

      </el-form-item>

    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="closeDialogAdd">取消</el-button>
      <el-button type="primary" @click.native="handleSubmitAdd" :loading="formLoading">提交</el-button>
    </div>
  </el-dialog>


let handleSubmitAdd = function() {

  if (this.formLoading) {
    return
  }

  this.$refs.addForm.validate(valid => {
    if (!valid) {
      return
    }
    this.formLoading = true

    var formData = new FormData;
    formData.append('name', this.addForm.name);
    formData.append('code', this.addForm.code);
    formData.append('file', this.uploadFile);

    let config = {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    };

    this.$axios.post('http://localhost:8090/xx/xx/insert', formData, config)
      .then((res) => {
        if (res.data.code === 0) {

          this.formLoading = false
          this.$refs.upload.clearFiles();
          this.formVisibleAdd = false

        }
      })
      .catch((res) => {
      })
  })

}


@PostMapping(value = "insert", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public CommResult insertTableTeam(HttpServletRequest request, 
                                                                            @RequestParam(value = "name", required = false) String name,
                                                                            @RequestParam(value = "code", required = false) String code,
                                      @RequestParam(value = "file", required = false) MultipartFile file) {


        String rootPath = request.getSession().getServletContext().getRealPath("/");
        if (file != null) {
            String fileName = file.getOriginalFilename();
            if (fileName != null && fileName.trim().length() > 0) {
                String newFileName = FileUtil.uploadFile(rootPath, fileName, file);

            }
        }
                //TODO 添加
        return "success";
    }
qq_41618510
水越帆 回复mingnianshimanian: 话说你的上传工具包是咋写的啊
7 个月之前 回复
qq_41618510
水越帆 回复mingnianshimanian: 提交的时候,后来我通过另一种方法实现了,但是后台入不了库,url=/materialManage/materialPictureAndText, method=POST, IP=127.0.0.1, execution=execution(String cn.weik.controller.MaterialController.insertTableTeam(HttpServletRequest,String,String,MultipartFile)), args=null, operator={}数据分明都过去了
7 个月之前 回复
u013254183
Iamoldwang 回复水越帆: 哪里报错,报什么错呢?
7 个月之前 回复
qq_41618510
水越帆 回复mingnianshimanian: 关键是那个action为空我这报错。。
7 个月之前 回复
u013254183
Iamoldwang 回复水越帆: 我把axios放到网上了,你直接下载吧https://download.csdn.net/download/u013254183/11266792
7 个月之前 回复
qq_41618510
水越帆 回复mingnianshimanian: 我下面贴了一个我的可以帮我看一下吗万分感谢!
7 个月之前 回复
u013254183
Iamoldwang 回复水越帆: 那就是封装的axios方法,你自己也可以封装一下,网上很多
7 个月之前 回复
qq_41618510
水越帆 回复mingnianshimanian: 你好,前端那个this.$axios.post我这里识别不了。。 axios({ headers: {'Content-Type': 'multipart/form-data'}, method: 'POST', url: url, data: { imgTitle: self.configForm.imgTitle, imgText: self.configForm.imgText, img: this.upload() }, timeout: Config.timeout })
7 个月之前 回复
qq_41618510
水越帆 回复mingnianshimanian: 那个工具包是什么啊
7 个月之前 回复
u013254183
Iamoldwang 回复水越帆: 对呀,图片存路径就好了,然后你上传文件到指定的路径就行了
7 个月之前 回复
qq_41618510
水越帆 你好请问后台入库的时候是图片和表单一起入库吗~
7 个月之前 回复

可以获取呀
给不同的参数就好了

<el-dialog title="添加图文" :visible.sync="dialogVisible">
  <el-form :model="configForm" ref="configForm" label-width="100px"
           :rules="rules"
           v-loading="loading2"
           enctype="multipart/form-data">
    <h3 class="title modal-headline">添加图文</h3>
    <el-form-item label=" 图文标题" prop="imgTitle">
      <el-input v-model="configForm.imgTitle"
                type="text"
                auto-complete="off" placeholder="请输入标题"></el-input>
    </el-form-item>
    <el-form-item label="添加文字" prop="imgText">
      <el-input v-model="configForm.imgText"
                type="textarea"
                auto-complete="off" placeholder="请输入文字内容"></el-input>
    </el-form-item>
    <el-form-item label="添加图片" prop="img">
      <el-upload
        class="upload-demo"
        accept="image/jpeg,image/jpg,image/png"
        action=""
        :on-preview="handlePreview"
        :on-remove="handleRemove"
        :before-remove="beforeRemove"
        multiple
        :limit="1"
        :on-exceed="handleExceed"
        :file-list="fileList"
        :auto-upload="false">
        <el-button type="success" size="small">选择文件</el-button>
      </el-upload>
    </el-form-item>
  </el-form>
  <div slot="footer" class="dialog-footer">
    <el-button type="primary"
               @click="submitImg('configForm')" >确 定</el-button>
    <el-button @click="dialogVisible = false">取 消</el-button>
  </div>
</el-dialog>


          submitImg (formName) {
    let self = this
    this.$confirm('此操作将无法撤回, 是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      self.$refs[formName].validate((valid) => {
        if (valid) {
          let url = Config.context + '/materialManage/materialPictureAndText'
          if (url) {
            axios({
              headers: {'Content-Type': 'multipart/form-data'},
              method: 'POST',
              url: url,
              data: {
                imgTitle: self.configForm.imgTitle,
                imgText: self.configForm.imgText,
                img: this.upload()
              },
              timeout: Config.timeout
            }).then((response) => {
              console.log(response)
            })
          }
        } else {
          return false
        }
      })
    }).catch(() => {
      this.$message({
        type: 'info',
        message: '已取消更新'
      })
    })
  }

            @PostMapping(value = "materialPictureAndText", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public String insertTableTeam(HttpServletRequest request,
                                  @RequestParam(value = "imgTitle", required = false) String imgTitle,
                                  @RequestParam(value = "imgText", required = false) String imgText,
                                  @RequestParam(value = "file", required = false) MultipartFile file) {

    String fileName = file.getOriginalFilename();
    String filePath = request.getSession().getServletContext().getRealPath(path);
    log.error("filename1:" + fileName);
    log.error("filePath1:" + filePath);

    try {
        FileUtils.upload(file.getBytes(), filePath, fileName);
    } catch (Exception e) {
        e.printStackTrace();
    }
    // 拼接图片url
    String imgHost = "http://127.0.0.1:" + port;
    String imgUploadPath = path;
    String imgName = fileName;
    String imgPath = imgHost + imgUploadPath + imgName;
    materialPictureAndTextService.addPictureAndText(imgTitle,imgText,imgPath);
    //TODO 添加
    return "success";
}

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问