vue+element+upload實現頭像上傳

 

 

 

後臺css

    @RequestMapping("/up")
    public JSONObject up(@RequestParam("picFile") MultipartFile picture,HttpServletRequest request) {
                
        
                    System.out.println(picture.getContentType());
            
        //獲取文件在服務器的儲存位置
        String path = request.getSession().getServletContext().getRealPath("/upload");
        File filePath = new File(path);
        System.out.println("文件的保存路徑:" + path);
        if (!filePath.exists() && !filePath.isDirectory()) {
            System.out.println("目錄不存在,建立目錄:" + filePath);
            filePath.mkdir();
        }

        //獲取原始文件名稱(包含格式)
        String originalFileName = picture.getOriginalFilename();
        System.out.println("原始文件名稱:" + originalFileName);

        //獲取文件類型,以最後一個`.`爲標識
        String type = originalFileName.substring(originalFileName.lastIndexOf(".") + 1);
        System.out.println("文件類型:" + type);
        //獲取文件名稱(不包含格式)
        String name = originalFileName.substring(0, originalFileName.lastIndexOf("."));

        //設置文件新名稱: 當前時間+文件名稱(不包含格式)
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String date = sdf.format(d);
        String fileName = date + name + "." + type;
        System.out.println("新文件名稱:" + fileName);

        //在指定路徑下建立一個文件
        File targetFile = new File(path, fileName);

        //將文件保存到服務器指定位置
        try {
            picture.transferTo(targetFile);
            System.out.println("上傳成功");
            //將文件在服務器的存儲路徑返回
            return null;
        } catch (IOException e) {
            System.out.println("上傳失敗");
            e.printStackTrace();
            return null;
        }
   
    }

 

前臺api

<template>
  <div>
    <el-button type="success"
               @click="dialogVisible2 = true">點擊打開 Dialog</el-button>
    <el-dialog title="上傳頭像"
               :visible.sync="dialogVisible2"
               width="30%">
      <el-form :model="form">
        <el-form-item :label-width="formLabelWidth"
                      ref="uploadElement">
          <el-upload ref="upload"
                     action="#"
                     accept="image/png,image/gif,image/jpg,image/jpeg"
                     list-type="picture-card"
                     :limit=limitNum
                     :auto-upload="false"
                     :on-exceed="handleExceed"
                     :before-upload="handleBeforeUpload"
                     :on-preview="handlePictureCardPreview"
                     :on-remove="handleRemove"
                     :on-change="imgChange"
                     :class="{hide:hideUpload}">
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%"
                 :src="dialogImageUrl"
                 alt="">
          </el-dialog>
        </el-form-item>
        <el-form-item>
          <el-button size="small"
                     type="primary"
                     @click="uploadFile">當即上傳</el-button>
          <el-button size="small"
                     @click="tocancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>

</template>

<script>
export default {
  data () {
    return {
      hideUpload: false,
      dialogImageUrl: '',
      dialogVisible: false,//圖片預覽彈窗
      formLabelWidth: '80px',
      limitNum: 1,
      form: {},
      dialogVisible2: false//彈窗
    }
  },
  methods: {
    // 上傳文件以前的鉤子
    handleBeforeUpload (file) {
      if (!(file.type === 'image/png' || file.type === 'image/gif' || file.type === 'image/jpg' || file.type === 'image/jpeg')) {
        this.$notify.warning({
          title: '警告',
          message: '請上傳格式爲image/png, image/gif, image/jpg, image/jpeg的圖片'
        })
      }
      let size = file.size / 1024 / 1024 / 2
      if (size > 2) {
        this.$notify.warning({
          title: '警告',
          message: '圖片大小必須小於2M'
        })
      }
      let fd = new FormData();//經過form數據格式來傳
      fd.append("picFile", file); //傳文件
      console.log(fd.get('picFile'));
      this.api({
        url: "/test/up",
        method: "post",
        data: fd,
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }).then((data) => {

      })
    },
    // 文件超出個數限制時的鉤子
    handleExceed (files, fileList) {

    },
    // 文件列表移除文件時的鉤子
    handleRemove (file, fileList) {
      this.hideUpload = fileList.length >= this.limitNum;

    },
    // 點擊文件列表中已上傳的文件時的鉤子
    handlePictureCardPreview (file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    uploadFile () {
      this.$refs.upload.submit()

    },
    imgChange (files, fileList) {
      this.hideUpload = fileList.length >= this.limitNum;
      if (fileList) {
        this.$refs.uploadElement.clearValidate();
      }
    },
    tocancel () {
      this.dialogVisible2 = false



    }
  }
}
</script>

<style lang="scss" >
.hide .el-upload--picture-card {
  display: none;
}
</style>
相關文章
相關標籤/搜索