ssm+vue使用element-UI 进行手动图片上传并实现图片预览

背景

我们在写项目的时候,基本的一个功能,那就是图片上传,可以是用户头像上传,也可以是当时我们核心功能成品的图片。故文件上传在ssm项目中是比较基础的存在。

效果

代码

1、导入依赖

使用commons-fileupload的版本大于1.0的话则必须引入commons-io.jar

<dependency>
   <groupId>commons-fileupload</groupId>
   <artifactId>commons-fileupload</artifactId>
   <version>1.4</version>
</dependency>
<dependency>
   <groupId>commons-io</groupId>
   <artifactId>commons-io</artifactId>
   <version>2.7</version>
</dependency>

2、spring-mvc配置

处理文件上传,id是固定值,不可改变,直接cv就可

<!--	配置文件上传解析器-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
	<property name="maxUploadSize">
		<value>5242880</value>
	</property>
</bean>

3、编写文件工具类

将文件工具类写在service层,这边直接放出实现类里的具体方法

    @Override
    public String createFile(MultipartFile file,String filePath, String filename) {
        // 获取文件名
        String fileName = file.getOriginalFilename();
        String type=fileName.substring(fileName.lastIndexOf("."));
        System.out.println(type);
        System.out.println("文件名"+fileName);
        // 重命名,避免文件名重复
        File newFile = new File(filePath, filename+type);
        // 检测是否存在该目录
        if (!newFile.getParentFile().exists()){
            newFile.getParentFile().mkdirs();
        }
        try {
            // 写入文件
            file.transferTo(newFile);
            return filename+type;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

    }

4、controller层

使用MultipartFile类来接收前端传来的文件,前端传来的文件等信息是存储在表单数据里的,故要使用@RequestPart接收,还要配置consumes = "multipart/form-data"

//上传图片
    @ResponseBody
    @RequestMapping(value = "/uploadPic", method = RequestMethod.POST, consumes = "multipart/form-data")
    public Result uploadPic(@RequestPart("file") MultipartFile pic,@RequestParam("picName")String picName){

        String fileName=pic.getOriginalFilename();
        System.out.println("原图片名称:"+fileName);
        String filePath="D:\\myjava\\ssmProject\\vue-supermarket\\src\\assets\\goods";
        String newName=uploadFileService.uploadUserPic(pic,filePath,picName);

        return new Result(newName,111,"",true);
    }

5、前端组件

核心思路:

使用upload组件,取消自动上传(auto-upload="false")因为取消了自动上传,只能通过on-change方法来获取上传文件的信息、图片预显示等,再将将文件信息存入表单数据里面,后续使用按钮,实现手动触发,使用axios传入后端在指定文件夹生成图片。

upload组件

 我的把文件上传组件配合表单添加信息使用,在点击表单信息确认添加时,再触发文件上传

 data数据

 涉及方法

文件上传有一个单独的controller层方法,表单数据也有个单独的controller层方法。我们把文件上传的最终图片名存入表单添加信息的类里,涉及到了一个同步与异步问题。如果我们重命名在controller里面,就需要先执行文件上传,获取返回文件名存入表单数据,才能进行表单提交。但是文件上传上传axios与表单数据axios是异步进行的,也就是说没有等到文件上传后台返回文件名,表单提交方法以及执行了。故我直接在前端设置重命名的文件名。

完整代码

<template>
  <div>
    <el-row>
      <el-col :span="10" class="uploadDiv">
        <div>
          <el-upload
            class="avatar-uploader"
            action=""
            :show-file-list="false"
            :on-change="picturePreview"
            :auto-upload="false"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </div>

        <el-button
          type="warning"
          class="cancelBtn"
          v-show="imageUrl"
          @click="cancelUpload"
          >取消图片</el-button
        >
      </el-col>

      <el-col :span="14">
        <el-form
          :model="goodsFormData"
          status-icon
          :rules="rules"
          ref="addFrom"
        >
          <el-form-item
            label="商品名称"
            :label-width="formLabelWidth"
            prop="name"
          >
            <el-input
              v-model="goodsFormData.name"
              autocomplete="off"
              clearable
            ></el-input>
          </el-form-item>
          <-表单略!-->
          <el-form-item>
            <el-button @click="cancelAdd">取消</el-button>
            <el-button type="primary" @click="onSubmit('addFrom')"
              >添加</el-button
            >
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import axios from "axios";
export default {
  name: "AddGoods",
  data() {
    //表单绑定的rules验证略
   
    return {
      formLabelWidth: "80px",
      goodsFormData: {
        name: "",
        type: "",
        state: "",
        picture: "",
        price: "",
      },
      file: "",
      imageUrl: "",
      
      rules: {
        //略
      },
    };
  },
 
  methods: {
    //onchange:预览图片
    picturePreview(file, fileList) {
      // console.log("fffff", file.raw);
      //预览图片
      if (window.createObjectURL != undefined) {
        this.imageUrl = window.createObjectURL(file.raw);
      } else if (window.URL != undefined) {
        this.imageUrl = window.URL.createObjectURL(file.raw);
      } else if (window.webkitURL != undefined) {
        this.imageUrl = window.webkitURL.createObjectURL(file.raw);
      }
      this.file = file.raw;
    },
    //取消上传
    cancelUpload() {
      this.imageUrl = "";
      this.file = "";
    },
    //文件上传 async这里本来想设置同步,但是怎么也改不了同步,还是异步
    async uploadPic() {
      const formData = new FormData();
      formData.append("file", this.file);
      formData.append("fileType", "IMAGE");
      let picName = new Date().getTime() + "";
      formData.append("picName", picName);
      this.goodsFormData.picture = picName;
      let response = await axios
        .post("/uploadPic", formData, {
          "Content-Type": "multipart/form-data;charset=utf-8",
        })
        .then((res) => {
          return res.data.data;
        })
        .catch((error) => {
          this.$message.error("上传失败");
        });

      this.imageUrl = "";
    },
    
    clearForm() {
      this.imageUrl = "";
      this.goodsFormData.picture = "";
      this.goodsFormData.batch = "";
      this.goodsFormData.name = "";
      this.goodsFormData.state = "";
      this.goodsFormData.type = "";
      this.goodsFormData.price = "";
    },
    //表单添加最终按钮触发的方法添加
    onSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          //表单验证通过
          if (this.imageUrl != "") {
            console.log("图片上传");
            this.uploadPic();
          }
          //添加商品
          this.addGoods();
          //清空表单输入框
          
        } else {
          return false;
        }
      });
    },
    
  
};
</script>

<style scoped lang="scss">
.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  width: 178px;
  height: 178px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  display: inline-block;
}
.avatar-uploader:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.uploadDiv {
  height: 100%;

  justify-content: center;
  align-items: center;
  text-align: center;
  margin-bottom: 0;
}

</style>

 最终效果

  • 3
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值