vue文件上传

写入HTML

<template>
  <div>
    <el-upload
      class="upload-demo"
      :action="upload.url"
      :headers="upload.headers"
      :on-change="handleUploadChange"
      :on-success="handleUploadSuccess"
      :on-remove="handleUploadRemove"
      :on-preview="handleUploadPreview"
      :before-upload="beforeUpload"
      :file-list="upload.fileList"
      :disabled="disabled" >
      <el-button size="small" type="primary">点击上传</el-button>
    </el-upload>

    <el-dialog
      :visible.sync="imgDialogVisible"
      append-to-body
      title="预览"
      width="800"
    >
      <img
        :src="dialogImageUrl"
        style="display: block; max-width: 100%; margin: 0 auto"
      />
    </el-dialog>
  </div>
</template>

写入变量

name: 'UploadCommon',
  props: {
    outFileList: {
      type: Array,
      default: () => []
    },
    disabled: {
      type: Boolean,
      default: () => false
    },
    finishUploadChange: {
      type: Function
    },
  },
  watch: {
    outFileList(val) {
      this.fileList = val
      this.initUpload()
    }
  },
  data() {
    return {
      // 文件上传配置
      upload: {
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/common/uploadGetId",
        // 上传的文件列表
        fileList: []
      },
      form: {
        layoutFileIds: null,
        layoutFileIdsArr: []
      },
      fileList: [],
      dialogImageUrl: "",
      imgDialogVisible: false
    }

写入方法

methods: {
    handleUploadChange(file, fileList) {
      this.fileList = fileList.slice(-3);
    },
    handleUploadRemove(file, fileList, event) {
      console.log(file)
      this.form.layoutFileIdsArr.splice(this.form.layoutFileIdsArr.indexOf(file.id), 1)
      this.form.layoutFileIds = this.form.layoutFileIdsArr.join(",")
      this.finishUploadChange(this.form.layoutFileIds)
    },
    handleUploadSuccess(response, file, fileList) {
      this.form.layoutFileIdsArr.push(response.id)
      this.form.layoutFileIds = this.form.layoutFileIdsArr.join(",").toString()
      this.finishUploadChange(this.form.layoutFileIds);
    },
    resetFileList() {
      this.fileList = []
    },
    beforeUpload(file) {
      console.log(file)
      let isJPG = file.type === 'image/jpeg';
      let isTxt = file.type === 'text/plain';
      let isWord = ( file.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
        || file.type === 'application/msword' );
      let isPdf = file.type === 'application/pdf';
      // const isLt2M = file.size / 1024 / 1024 < 2;

      if (! (isJPG || isTxt || isWord || isPdf)) {
        this.$message.error('上传文件只能是 JPG、TXT、Word、PDF 格式!');
      }
      // if (!isLt2M) {
      //   this.$message.error('上传头像图片大小不能超过 2MB!');
      // }
      return isJPG || isTxt || isWord || isPdf;
    },
    handleUploadPreview(file) {
      let id = file.id ? file.id : file.response.id
      getFileUrl(id).then(response => {
        let fileType = response.file.fileType
        if (fileType === 'pdf' || fileType === 'txt') {
          window.open(response.file.url)
        } else if (fileType === 'docx' || fileType === 'doc') {
          // window.location.href = './wordPreview?id=' + id;
          window.open('/backstage/emergency/wordPreview?id=' + id)
        } else if (fileType === 'jpg') {
          this.dialogImageUrl = response.file.url
          this.imgDialogVisible = true
        }
      })
    },
    initUpload() {
      this.fileList = this.outFileList
      this.upload.fileList = this.fileList
      this.form.layoutFileIdsArr = []
      for (let i=0; i<this.fileList.length; i++) {
        this.fileList[i].name = this.fileList[i].fileName + "." + this.fileList[i].fileType
        this.fileList[i].size = this.fileList[i].fileSize
        this.form.layoutFileIdsArr.push(this.fileList[i].id)
      }
      this.form.layoutFileIds = this.form.layoutFileIdsArr.join(",")
      console.log(this.fileList)
    }
  },
  created() {
    this.initUpload()
  }
}

注意,引入接口api

import { getFileUrl } from '@/api/system/file'

文件预览

<template>
  <div class="word-wrap">
    <div id="wordView" v-html="wordText" />
  </div>
</template>

<script>
// docx文档预览(只能转换.docx文档,转换过程中复杂样式被忽,居中、首行缩进等)
import mammoth from "mammoth";
import { getFileUrl } from '@/api/system/file'
export default {
  name: "EnterpriseWordPreview",
  data() {
    return {
      id: Number,
      wordText: "",
      wordURL: ''//文件地址
    };
  },
  created() {
    this.getWord();
    this.getWordText();
  },
  methods: {
    getWord() {
      let _this = this
      this.id = this.$route.query.id
      getFileUrl(this.id).then(response => {
        let fileType = response.file.fileType
         if (fileType === 'docx' || fileType === 'doc') {
          // window.location.href = './wordPreview?id=' + id;
          // console.log(response.file.fileName + "." + fileType)
          _this.wordURL = response.file.url
          _this.getWordText()
        } else {
           _this.wordText = "当前文档格式不正确"
         }
      })
    },
    getWordText() {
      let xhr = new XMLHttpRequest();
      xhr.open("get", this.wordURL, true);
      xhr.responseType = "arraybuffer";
      xhr.onload = () => {
        if (xhr.status === 200) {
          mammoth.convertToHtml({ arrayBuffer: new Uint8Array(xhr.response) }).then((resultObject) => {
            this.$nextTick(() => {
              this.wordText = resultObject.value;
            });
          });
        }
      };
      xhr.send();
    }
  },
};
</script>

<style>
.word-wrap {
  padding: 15px;

}
.word-wrap img {
  width: 100%;
}
</style>

后端代码

 @ApiOperation("通用上传请求返回文件表id")
    @ApiImplicitParam(name = "file", value = "文件流", dataType = "MultipartFile")
    @PostMapping("/common/uploadGetId")
    public AjaxResult uploadGetId(MultipartFile file) {
        try {
            // 上传文件路径
            String filePath = KingTopConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String realName = file.getOriginalFilename().substring(0, file.getOriginalFilename().indexOf("."));
            String url = serverConfig.getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("fileName", realName);
            ajax.put("url", url);

            String localFilePath = filePath + fileName.substring(fileName.indexOf("/upload")+7);
            // 存储到文件表
            SysFile sysFile = new SysFile();
            // 这不懂干什么用的,但是是必填,随便填个0
            sysFile.setTableId(0l);
            sysFile.setDataId(0l);
            sysFile.setMark(IdUtils.simpleUUID());
            sysFile.setUserId(SecurityUtils.getUserId());
            sysFile.setUserName(SecurityUtils.getUsername());
            sysFile.setUploadTime(new Date());
            sysFile.setUrl(url);
            sysFile.setFileSize(file.getSize());
            sysFile.setFileName(realName);
            sysFile.setFilePath(localFilePath);
            sysFile.setFileType(url.substring(url.lastIndexOf(".")+1));
            sysFile.setFileMd5(SecureUtil.md5(new File(localFilePath)));
            sysFile.setStatus(0l);
            ajax.put("id", sysFileService.insertSysFile(sysFile));
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

原作者地址
https://www.csdn.net/tags/NtTaAgysMDQwMTgtYmxvZwO0O0OO0O0O.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值