vue 利用input "file" 上传功能

2020-10-21  本文已影响0人  前端陈陈陈

最近公司一个需求是:用户上传excel 表格时候,后端根据状态判断是上传还是 上传excel 还是导出excel 表格;如果是上传,那么接口会返回json 数据,如果是下载,接口会返回二进制数据流让前端处理下载。这样一个需求自然element 组件无法满足需求了,只能自己动手丰衣足食了。

//html 代码
   <form id="upload" enctype="multipart/form-data" method="post">
            <label for="fileinp">
              <input type="button" id="btn" value="批量发货" />
              <input
                type="file"
                id="fileinp"
                ref="referenceUpload"
                name="file"
                accept=".xls, .xlsx"
                @change="uploadPic"
              />
            </label>
          </form>
//css
label {
  position: relative;
}
#fileinp {
  position: absolute;
  left: 0;
  top: 0;
  opacity: 0;
}
#btn {
  margin-right: 5px;
  background: #0068b7;
  border-color: #0068b7;
  color: #fff;
  width: 100px;
  height: 40px;
  border: 1px solid #dcdfe6;
}
#text {
  color: red;
}
//js
  uploadPic() {
      let that = this;
      var form = document.getElementById("upload"),
        formData = new FormData(form);
      let url = "  ";
      this.$axios
        .axiose({
          url: url,
          data: formData,
          method: "post",
          responseType: "blob"
        })
        .then(result => {
          if (result.type == "text/html") {
            const reader = new FileReader();
            reader.onload = function() {
              let info = JSON.parse(reader.result);
              if (info.code == 200) {
                that.$message({
                  message: info.msg,
                  type: "success"
                });
                that.getorders();
                that.$refs.referenceUpload.value = null;
              } else {
                that.$message({
                  message: info.msg,
                  type: "warning"
                });
                that.$refs.referenceUpload.value = null;
              }
              that.loading = false;
            };
            reader.readAsText(result);
          } else if (result.type == "applicationnd.ms-excel") {
            const content = result;
            const blob = new Blob([content]);
            if ("download" in document.createElement("a")) {
              //支持a标签download的浏览器
              const link = document.createElement("a"); //创建a标签
              link.download = `订单.xlsx`;
              link.style.display = "none";
              link.href = URL.createObjectURL(blob);
              document.body.appendChild(link);
              link.click(); //执行下载
              URL.revokeObjectURL(link.href); //释放url
              document.body.removeChild(link); //释放标签
              this.$refs.referenceUpload.value = null;
            } else {
              //其他浏览器
              navigator.msSaveBlob(blob, `订单.xlsx`);
              this.$refs.referenceUpload.value = null;
            }
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
上一篇 下一篇

猜你喜欢

热点阅读