VUE+springboot上传附件(不只是上传图片,各种文件都行)到服务器并且可以预览附带上传时的预览确认

最近项目碰到一个需求,上传附件,平时上传附件做的很多,比如上传个图片,然后还可以预览,这是稀松平常的功能,但是这次这个上传客户要求不限制文件类型,什么都能上传,什么Excel,word,ppt,txt,图片,视频,音乐等等,关键是上传的时候还需要用户看到上传的东西,方便用户确认,我们知道图片上传预览其实也不是展示的客户端物理机上的图片(浏览器出于安全考虑是不会让我们获取到客户端物理机上面的文件的真实路径的),而是我们选择的图片文件的binary,其实就是二进制文件,也就是预览是把我们选择的图片的二进制文件转成图片让我们看到。为了解决这个需求,就有了这篇文章。
效果图:
在这里插入图片描述
前端代码:
定义组件

<template>
  <div>
    <v-button-search @click="uploadExcel" style="float:right;">上传附件</v-button-search>
    <el-dialog title="上传文件" :visible.sync="dialogTableVisible">
      <div style="width:100%;height:200px;">
        <el-upload
          ref="upload"
          :limit="5"
          :action="uploadUrl"
          :on-remove="handleRemove"
          :on-error="uploadFalse"
          :on-success="uploadSuccess"
          :auto-upload="true"
          :before-upload="beforeUpload"
          :show-file-list="false"
        >
          <el-button slot="trigger" size="small" type="primary">选择上传</el-button>
<!--          <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">提交附件</el-button>-->
        </el-upload>
        <div v-if="showPreview">
          <h4 style="font-weight:500;height:15px;">已上传发票附件确认(点击文件名称下载查看确认):</h4><br><br>
          <template v-for="(value,index) in attachedUrls">
            <div style="width: 100%;"><a :href='attUrl+value'>{{value.substring(value.indexOf('_')+1,value.length)}}</a><i @click="deleteUrl(value)" class="el-icon-delete" style="float: right;"></i></div>
          </template>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<style>
.el-upload__input {
  display: none !important;
}
</style>
<script>
import Vue from "vue";

import RemarksUpload from '../../../../static/project/js/remarksUpload-file.js';
export default {
  props: ["uploadUrl"],
  data() {
    return {
      uploadFiles:[],
      attachedUrls:[],
      dialogTableVisible: false,
      showList:true,
      showPreview:false,
      attUrl:'http://127.0.0.1:8088/server/invoice/downFile?name='
    };
  },
  mounted() {},
  methods: {
    // 上传
    uploadExcel() {

      this.dialogTableVisible = true;
    },
    beforeUpload(file) {
      this.loading = this.$loading({
        lock: true,
        text: "上传中.......",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      this.files = file;
      return true;

    },
    uploadSuccess(response, file, fileList) {
      if (response.success) {
        this.uploadFiles.push(response.data);
        this.attachedUrls.push(response.data);
        RemarksUpload.$emit('demo','msg');
        if(this.uploadFiles.length==fileList.length){
          alert("文件上传成功");
          this.showList=false;
          this.showPreview=true;
          // this.dialogTableVisible=false;
        }
      } else {
        this.loading.close();
        alert("《" + file.name + "》" + response.data);
      }
      this.loading.close();
    },
    uploadFalse(err, file, fileList) {
      this.loading.close();
      alert(err.name)
      alert("文件上传失败......!");
    },
    submitUpload() {
      this.$refs.upload.submit();
    },
    handleRemove(file, fileList) {

    },
    deleteUrl(value){
      this.$confirm("确认删除?","确认删除",{
        confirmButtonText: "确定",
        cancelButtonText: "取消"
      }).then(()=>{
        this.uploadFiles.splice(this.uploadFiles.indexOf(value),1)
        this.attachedUrls.splice(this.attachedUrls.indexOf(value),1)
        alert("附件已删除");
      }).catch(() => {
        this.loading.close();
      });


    }
  }
};
</script>

remarksUpload-file.js文件内容:

import Vue from 'vue'
export default new Vue

暴露组件

import FilesUpload from "../../components/common/dialog/files-upload.vue";
Vue.component("v-files-upload", FilesUpload);

使用组件

<v-files-upload :uploadUrl="uploadUrl" ref="childtag" v-if="hasPermssion('invoiceDataOperate')"></v-files-upload>

this.permissions = this.$getSessionPermission();

uploadUrl: this.GLOBAL.ProjectUrl.fileUpload

hasPermssion(name) {
  if (this.permissions != null && this.permissions.indexOf(name) >= 0) {
    return true;
  } else {
    return false;
  }
},

this.submitFormArray[0]["url"]=this.$refs.childtag.uploadFiles;

后台代码:
接口:

@RequestMapping(value = "/upload", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public AjaxForm addFile(HttpServletRequest request, @RequestParam("file") MultipartFile file) throws Exception {
		AjaxForm ajaxForm = new AjaxForm();
		try {
			File localFile = ExcelReadUtil.saveFile(file);
			ajaxForm.setData(localFile.getName());
			ajaxForm.setSuccess(true);
		} catch (Exception e) {
			ajaxForm.setSuccess(false);
			ajaxForm.setData(e.getMessage());
			e.printStackTrace();
		}
		return ajaxForm;
	}

上传下载工具类中的方法:

public static File saveFile(MultipartFile file) throws Exception  {
		if (file == null) {
			throw new Exception("file is null");
		}
		if (file.isEmpty()) {
			throw new Exception("文件为空");
		}
		//upload_file是文件上传的路径,写在配置文件中
		String path = ProjectConfigUtil.get("upload_file");
		// 获取上传的文件名称,并结合存放路径,构建新的文件名称
		String filename = StringUtil.getFileNameBySysDate() + "_" + file.getOriginalFilename();
		File localFile = new File(path, filename);
		//如果目录不存在,创建目录
		if (!localFile.getParentFile().exists()) {
			localFile.getParentFile().mkdirs();
		}
		//文件移动
		file.transferTo(localFile);
		return localFile;
	}
	```
  • 0
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值