1、实现的效果

在这里插入图片描述

在这里插入图片描述

2、Vue前端

      <!--    ==================================增加汽车==========================================-->
      <el-dialog
        title="添加汽车"
        :visible.sync="adddialogVisible"
        width="30%"
        :close-on-click-modal="false">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" style="width: 60%" label-width="100px" class="demo-ruleForm">
    

          <el-form-item label="汽车押金" prop="guarantee_money">
            <el-input v-model="ruleForm.guarantee_money" placeholder="请输入汽车押金"></el-input>
          </el-form-item>

          <el-form-item label="上传图片"  prop="imageUrl">
            <el-upload
              class="avatar-uploader"
              action="http://localhost:8282/upload/img"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload">
              <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>
        <span slot="footer" class="dialog-footer">
         <el-button @click="resetForm('ruleForm')">重置</el-button>
    <el-button @click="adddialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="submitForm('ruleForm')">确 定</el-button>
  </span>
      </el-dialog>

3、图片上传

重点部分:==

在这里插入图片描述

4、字段变量根据自己的字段名自行设置(这里不给出了,哈哈哈)

5、method方法

5.1、图片显示在选择框中,同时返回后端存储的地址

      //图片回显
      handleAvatarSuccess(res, file) {
        console.log(res)
        this.imageUrl = res.data.final_fileName
        sessionStorage.setItem("imgUrl",this.imageUrl)
        alert(this.imageUrl)
      },
     //图片上传大小限制
      beforeAvatarUpload(file) {
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isLt2M;
      },

解释:
在这里插入图片描述

5.2查看后端返回给前端的图片地址

在这里插入图片描述

5.3 提交表单数据到后端

      //提交表单
      submitForm() {
        let _this = this;
        _this.ruleForm.imageUrl =sessionStorage.getItem("imgUrl")
        axios.post('/car/addcar',this.ruleForm).then(resp => {
          if(resp.data.code==200){
            _this.$alert('《'+_this.ruleForm.name+'》添加成功', '消息', {
              confirmButtonText: '确定',
              callback: action => {
                _this.adddialogVisible=false
                _this.showAllUsers();
              }
            });
          }
        });
      },

6、后端的配置

6.1、处理前端传输过来的图片、将图片地址返回给前端


    @Value("${pictureFile.path}")
    private String picturePath;

    @Value("${pictureFile.path-mapping}")
    private String picturePath_mapping;
//这个写在了配置文件中

    @PostMapping("/upload/img")
    public Result upload(MultipartFile file) {
        String fileName = file.getOriginalFilename();  // 文件名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));  // 后缀名
        fileName = UUIDutilsu.getUUID() + suffixName; // 新文件名
        File dest = new File(picturePath + fileName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String final_fileName = "http://localhost:8282" + picturePath_mapping + fileName;
        System.out.println(final_fileName);
        return Result.ok().data("final_fileName",final_fileName);
    }

讲解:UUIDutilsu.getUUID()是我写的一个UUID的工具类。Result.ok().data("final_fileName",final_fileName);是统一返回给前端的数据格式。如上图所示。Result是我封装好的统一返回给前端数据的字段。这里可以直接返回String类型的字符串

6.2、application.yml文件中

pictureFile:
  path: "G:/BISHE/upload/"
  path-mapping: "/myImg/"
  
resources:
  static-locations: classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,file:${pictureFile.path-mapping}



6.3、这个重点配置

@Configuration
public class URLConfig implements WebMvcConfigurer {
    @org.springframework.beans.factory.annotation.Value("${pictureFile.path}")
    private String picturePath;

    @Value("${pictureFile.path-mapping}")
    private String picturePath_mapping;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler(picturePath_mapping+"**").addResourceLocations("file:"+picturePath);

    }

}

7、添加商品的接口(使用了swagger)

    @ApiOperation(value = "添加汽车", notes = "添加汽车")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Car")
    })
    @RequestMapping(value = "/car/addcar", method = RequestMethod.POST)
    public Result addCar(@RequestBody Car car) {
        car.setStatus(1);//新增加的商品默认是上架商品
        String date = CurrentTime.getCurrentTime();
        car.setDate(date);
        int rs = carService.addCar(car);
        if (rs > 0) {
            return Result.ok();
        } else {
            throw new BusinessException(ResultCode.ADD_CAR_ERROR.getCode(),
                    ResultCode.ADD_CAR_ERROR.getMessage());
        }

    }
posted on 2022-08-28 22:17  热爱技术的小郑  阅读(5869)  评论(5编辑  收藏  举报