vue 手写文件上传

784 阅读1分钟

1 文件上传简单版

<template>
  <div class="csjUpload">
    <div
      v-show="imgArr.length !== 3"
      class="csjUpload_btn"
      @click="clickUpload"
    >
      <i class="csjUpload_btn--add">+</i>
      <div class="csjUpload_btn--describe">建议使用JPG/PNG格式</div>
    </div>
    <div
      v-for="(item,i) in imgArr"
      :key="i"
      class="csjUpload_content"
    >
      <span
        class="csjUpload_content--close"
        @click.stop="handleClose(i)"
      > <i class="el-icon-close" /></span>
      <img :src="item.url">
    </div>
    <input
      ref="uploadFile"
      type="file"
      style="display:none;"
      accept="image/*"
      files
      @change="BeforeUpload"
    >
  </div>
</template>

<script>
import { cookies } from "@/utils/storage";
export default {
  components: {},
  data() {
    return {
      imgArr: [],
      imgUrl: "",
    };
  },
  methods: {
    clickUpload() {
      this.$refs.uploadFile.click();
    },
    BeforeUpload(event) {
      let files = event.target.files || event.dataTransfer.files;
      if (!files.length) {
        return;
      }
      var reader = new FileReader(); //读取文件
      reader.readAsDataURL(files[0]); //将文件读取为DataURL
      let fileNmae = files[0].name;

      reader.onload = (e) => {
        this.imgUrl = e.target.result;
      };
      // 上传之后调用接口...
      let params = new FormData();
      params.append("file", files[0]);
      this.upload(params, fileNmae);
      this.$refs.uploadFile.value = null; // 移除文件,可以保证上传同样的文件时,也会触发change事件
    },
    upload(params, name) {
      let _this = this;
      fetch(this.$uploadUrl, {
        method: "post",
        headers: {
          admin_token: cookies.get("admin_token"),
        },
        body: params,
      })
        .then(function (response) {
          if (response.status !== 200) {
            return;
          }
          response.json().then(function (res) {
            let { code, data, message } = res;
            if (code === 1) {
              _this.imgArr.push({
                path: data,
                url: _this.imgUrl,
                name,
              });
            } else {
              _this.$message.error(message);
            }
          });
        })
        .catch(function (err) {
          console.log(err);
        });
    },
    handleClose(i) {
      this.imgArr.splice(i, 1);
    },
  },
};
</script>

<style lang='scss' scoped>
.csjUpload {
  display: flex;
  &_btn {
    width: 125px;
    height: 125px;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    border-radius: 4px;
    border: 1px solid #c5c5c5;
    background: #f4f4f4;
    cursor: pointer;
    &:hover {
      border: 1px solid #2686f8ff;
    }
    &--add {
      display: block;
      width: 22px;
      height: 22px;
      line-height: 22px;
      text-align: center;
      background: #2686f8ff;
      border-radius: 50%;
      color: #fff;
      font-size: 20px;
    }
    &--describe {
      margin: 18px 4px 0;
      text-align: center;
      color: #999999ff;
      font-size: 12px;
    }
  }
  &_content {
    position: relative;
    width: 125px;
    height: 125px;
    border-radius: 4px;
    cursor: pointer;
    margin-left: 16px;
    img {
      width: 125px;
      height: 125px;
    }
    &--close {
      position: absolute;
      top: -11px;
      right: -11px;
      width: 22px;
      height: 22px;
      background: #999999;
      line-height: 22px;
      text-align: center;
      color: #fff;
      font-size: 18px;
      border-radius: 50%;
    }
  }
}
</style>

1

2

  • input display:none;
  • 自定义元素@click事件 this.$refs.uploadFile.click(); 去触发input的点击上传事件
  • 在input的change事件调用上传接口 参数为上传的文件

3

4

  • 上传文件 参数 new FormData()

  • FormData对象用以将数据编译成键值对,以便用XMLHttpRequest来发送数据。

fetch

www.jianshu.com/p/e18ced22c…

fetch('http://example.com/movies.json')
  .then(function(response) {
    return response.json();
  })
  .then(function(myJson) {
    console.log(myJson);
  });

当然它只是一个 HTTP 响应,而不是真的JSON。为了获取JSON的内容,我们需要使用json)方法(在mixin 中定义,被Request) 和Response) 对象实现)。

入参 JSON.stringify(data) 获取结果 res.json()

fetch(url, {
  method: 'POST', // or 'PUT'
  body: JSON.stringify(data), // data can be `string` or {object}!
  headers: new Headers({
    'Content-Type': 'application/json'
  })
}).then(res => res.json())
.catch(error => console.error('Error:', error))
.then(response => console.log('Success:', response));