使用el-upload组件上传图片,传递给后端的时候,后端报错,传过来的为null

前端使用el-upload来实现上传图片,前端需要把图片传给后端,测试的时候发现前端能够上传到浏览器中,但是后端接受的是一个(MultipartFile file)的参数,后端会将这个从前端拿到的文件,上传至七牛云服务器,最后返回的是图片的在线地址;

但是我服务端接受到从前端传过来的数据却是null?
这是后端的报错,就是接受过来的数据是null
image.png
这是前端代码:

<el-col :span="12" v-if="display == true">
        <el-form ref="form" :model="form" label-width="100px" size="small">
          <el-form-item label="图像" prop="pic" class="changeImg">
            <el-upload
              class="avatar-uploader"
              action="http://38617112yi.zicp.vip/upload/images"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              name="image"
            >
              <img v-if="imageUrl" :src="imageUrl" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="昵称">
            <el-input v-model="form.title"></el-input>
          </el-form-item>
          <el-form-item label="学校">
            <el-input v-model="form.school"></el-input>
          </el-form-item>
          <!-- <el-form-item label="真实姓名">
            <el-input
              v-model="form.name"
              placeholder="请输入你的真实姓名"
            ></el-input>
          </el-form-item> -->
          <el-form-item label="性别">
            <el-radio-group v-model="form.sex">
              <el-radio label="男"></el-radio>
              <el-radio label="女"></el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- <el-form-item label="毕业年份">
            <el-date-picker
              type="date"
              placeholder="选择日期"
              v-model="form.date"
              style="width: 100%"
            ></el-date-picker>
          </el-form-item> -->
          <el-form-item label="个性签名">
            <el-input
              type="textarea"
              v-model="form.signature"
              placeholder="懒的连签名都没有...."
            ></el-input>
          </el-form-item>

          <el-button
            style="margin-top: 20px"
            size="max"
            type="primary"
            @click="submit()"
            >提交</el-button
          >
        </el-form>
      </el-col>
      <el-col :span="12" v-else>
        <div></div>
      </el-col>
    </el-row>
  </div>
</template>
<script>
export default {
  name: "Content",
  data() {
    return {
      display: false,
      imgSrc: require("@/assets/img1.webp"),
      form: {
        pic: "",
        title: "",
        name: "",
        sex: "",
        date: "",
        signature: "",
        school: "",
      },
      imageUrl: "",
      userObj: {},
      userId: ''
    };
  },
  mounted() {
    this.getUserInfo()
  },
  methods: {
    getUserInfo() {

      var _self = this;
      var url = "http://38617112yi.zicp.vip/userInfo";
      _self.$axios
        .get(url)
        .then((res) => {
          if (res.status == 200) {
            
              console.log('用户信息',res.data)
              //let args = res.data.data;
              // let list = []
              // args.forEach(item => {
              //   list.push(item.userId)
              // });
              //_self.followList = res.data.data;
              _self.userObj = res.data.data;
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    changeStatus() {
      this.display = true;
    },
    submitForm() {
      console.log("提交修改内容");
      this.display = false;
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    submit() {
      let config = {
        timeout: 30000,
        headers: {
          "Content-Type": "multipart/form-data", //设置headers
        },
      };
      const formData = new FormData();
      var that = this;
      // 首先判断是否上传了图片,如果上传了图片,将图片存入到formData中
      console.log(this.imageUrl);

      console.log("debug this dataList" + this.dataList);
      if (this.dataList) {
        that.dataList.forEach((item, index) => {
          // console.log(item)
          formData.append(index, item);
        });
      }
      console.log(formData.get(0));
      that.$axios
        .post(
          'http://38617112yi.zicp.vip/upload/images', //请求后端的url
          formData,
          config
        )
        .then((res) => {
          console.log(res);
          if (res.data.status == "true") {
            //上传成功
            console.log("上传成功");
            this.$router.push({
              path: "./",
            });
          } else {
            alert("上传失败");
          }
        })
        .catch(() => {
          console.log("请求失败");
        });

这是后端的接口:

@PostMapping("/upload/images")
    @ResponseBody
    public Result<String> uploadImages2Qiniuyun(MultipartFile file){
        // 默认是是将图片的存放的地址设为了华南地区
        Configuration cfg = new Configuration(Region.huanan());
        UploadManager uploadManager = new UploadManager(cfg);

        // 默认不指定key的情况下,以文件内容的hash值作为文件名
        String key = null;
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);

        System.out.println(upToken);
        try{
            if(Objects.isNull(file)){
                return Result.error(CodeMsg.UPLOAD_IMAGE_EMPTY);
            }

            Response response = uploadManager.put(file.getBytes(), key, upToken);
            // 解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            // 拿到这个Key之后,然后拼接域名 + "/" + key,就是该图片的路径了
            String result = domainName + "/" + putRet.key;
            // 返回的就是图片的url地址了
            log.info("图片的存储地址是:{}", result);
            return Result.success(result);

        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
阅读 4.1k
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题