最近接到一个需求,对当前项目增加问题反馈功能,应对公司审计 。传统的vue上传组件,多张图片会提交多个请求到后台,这种显然不可取,我们要实现的就是

一次请求后台同时将多张图片和表单提交到后台。主要策略就是 : 1. 图片组件上传不提交   2 。使用FormData来将 图片和表单提交到后台。

前端代码如下 : 

 <el-form-item label="图片上传">
          <el-upload
            action='/rest/problemFeed/addProblemFeed'
            ref="upload"
            :data="ruleForm"
            :name="fileName"
            list-type="picture-card"
            accept="image/jpeg,image/jpg,image/png"
            :on-preview="handlePictureCardPreview"
            :auto-upload="false"
             multiple
             :file-list="files"
            :headers="importHeaders"
            :on-remove="handleRemove"
            :on-change="handleChange"
            :class="{ hideImg: hideUpload }"
          >
            <i slot="default" class="el-icon-plus"></i>
            <el-dialog :visible.sync="imgVisible" :append-to-body="true">
              <img width="100%" :src="dialogImageUrl" alt="" />
            </el-dialog>
          </el-upload>
        </el-form-item>
data() {
    return {
      moduleCode: "",
      hideUpload: false,
      modulePages: [],
      issueTypes: issueTypes, //问题类型
      browserTypes: browserTypes, //浏览器类型
      systemTypes: systemTypes, //系统类型
      ruleForm: {
        moduleCode: "",
        moduleName: "",
        problemType: "1",
        browserType: "1",
        systemType: "1",
        feedContent: "",
        feedTime: "",
      },
      files:[],
      fileName : "files",
      fileData : {},
      importHeaders: {
        enctype: "multipart/form-data",
      },
      rules: {
        feedContent: [
          { required: true, message: "请输入简要说明", trigger: "blur" },
        ],
        files: [
          { required: true, message: "请至少上传一张照片", trigger: "blur" },
        ]
      },
      dialogVisible: this.value,
      imgVisible: false,
      dialogImageUrl: "",
      actionUrl: config.admin_url + '/rest/problemFeed/addProblemFeed'
    };
  }

核心是这里的 :通过表单提交FormData组装数据,文件一定要是 :    this.fileData.append("files", this.files[i].raw, this.files[i].raw.name)

 submitForm(formName) {
      this.ruleForm.moduleName =  this.getNameFromCode(this.ruleForm.moduleCode, this.modulePages)
      this.$refs[formName].validate((valid) => {
        if (valid) {
          //this.$refs.upload.submit();
          this.fileData = new FormData()
          this.fileData.append('moduleCode', this.ruleForm.moduleCode);
          this.fileData.append('moduleName', this.ruleForm.moduleName);
          this.fileData.append('problemType', this.ruleForm.problemType);
          this.fileData.append('systemType', this.ruleForm.systemType);
          this.fileData.append('browserType', this.ruleForm.browserType);
          this.fileData.append('feedContent', this.ruleForm.feedContent);
          for(let i =0; i < this.files.length; i++) {
            this.fileData.append("files", this.files[i].raw, this.files[i].raw.name)
          }
          addFeedback(this.fileData).then((res) => {
            this.dialogVisible = false;
            this.files = []
          });
        }
      });

后台接收请求如下 : 

/**
	 * 
	 *   新增反馈
	 * @param req
	 * @param request  headers = "Content-Type=multipart/form-data"
	 * @return
	 */
	@RequestMapping(value = "/addProblemFeed", method = RequestMethod.POST,headers = "Content-Type=multipart/form-data")
	@ResponseBody
	@CLogger(event = "dds_problem_feed_add", index = 0)
	public RestResult<String> addProblemFeed(@RequestParam(value="moduleCode") String moduleCode,
			@RequestParam(value="moduleName") String moduleName,@RequestParam(value="problemType") String problemType,
			@RequestParam(value="systemType") String systemType,@RequestParam(value="browserType") String browserType,
			@RequestParam(value="feedContent") String feedContent,
	HttpServletRequest request) {
		String userName = RequestUtil.parseUserName(request);
		try {
			 	
				ProblemFeedAddReq req = new ProblemFeedAddReq(userName,moduleCode, moduleName, problemType, systemType, browserType, feedContent, new Date());
			    MultiPartRequestWrapper mpRequest = (MultiPartRequestWrapper) request;
			    
			    UploadedFile[] fileArray = mpRequest.getFiles("files");
			    List<File> rFiles =  Lists.newArrayList();
				for (int i = 0; i < fileArray.length; i++) {
					rFiles.add((File)fileArray[i].getContent());
				}
			    
				String cityCode = RequestHeadersUtils.cityCode();
				Result<String> result = problemFeedService.addProblemFeed(req ,userName,cityCode,rFiles);
				
				if( !result.isSuccess()) {
					return buildErrorResult(RestStatus.BIZ_ERROR, result.getObj());
				}
				return buildSuccessResult(result.getObj());
		} catch (Exception e) {
			logger.error("addProblemFeed  error:" + JSON.toJSONString(e));
			return buildErrorResult(RestStatus.BIZ_ERROR, "新增失败:" + e.getMessage());
		}
	}

GitHub 加速计划 / vu / vue
207.54 K
33.66 K
下载
vuejs/vue: 是一个用于构建用户界面的 JavaScript 框架,具有简洁的语法和丰富的组件库,可以用于开发单页面应用程序和多页面应用程序。
最近提交(Master分支:2 个月前 )
73486cb5 * chore: fix link broken Signed-off-by: snoppy <michaleli@foxmail.com> * Update packages/template-compiler/README.md [skip ci] --------- Signed-off-by: snoppy <michaleli@foxmail.com> Co-authored-by: Eduardo San Martin Morote <posva@users.noreply.github.com> 4 个月前
e428d891 Updated Browser Compatibility reference. The previous currently returns HTTP 404. 5 个月前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐