十年河东,十年河西,莫欺少年穷
学无止境,精益求精
这是一个后端开发人员的倔强
因项目需要,我从一个纯后端变成了前端+后端,也俗称全栈。
在实际项目中,上传附件几乎是必不可少的,因此,我们有必要将上传控件进行组件化。
设计理念,通过vue的父子传值进行封装,上传组件为子组件,调用方为父组件,由父组件传值给子组件,用来校验上传的文件扩展名及大小。
子组件
<template> <a-upload :beforeUpload="beforeUpload" :multiple="false" @change="filechange" :customRequest="customRequest" :fileList="fileList" :remove="fileRemove" > <a-button> <a-icon type="upload" /> 选择文件 </a-button> </a-upload> </template> <script> export default { props: ["fileinfo"], created() {}, data() { return { fileList: [], }; }, methods: { beforeUpload(file) { var that = this; //console.log(file); return new Promise((resolve, reject) => { const isLt100M = file.size / 1024 / 1024 > that.fileinfo.maxsize; if (isLt100M) { this.$message.warning( "上传附件大小不能超过" + that.fileinfo.maxsize + "M。" ); return reject(false); } var index = file.name.lastIndexOf("."); var suffix = file.name.substring(index + 1); if( that.fileinfo.filetype.indexOf(suffix)<0){ this.$message.warning( "上传的文件格式不符合要求" ); return reject(false); } return resolve(true); }); }, filechange(info) { //console.log(info); this.fileList = info.fileList; //console.log(this.fileList); if (info.file.status == "uploading") { } if (info.file.status === "done") { } else if (info.file.status === "error") { } }, customRequest(data) { // 上传提交 const formData = new FormData(); formData.append("file", data.file); this.saveFile(formData); }, saveFile(formData) { let that = this; this.$axios({ url: "/api/File/UploadFileStream", method: "post", data: formData, }) .then(function (result) { //console.log(result); //that.fileList.push(result.Data) if (result.IsSuccess) { for (var i = 0; i < that.fileList.length; i++) { that.fileList[i].status = "done"; } console.log(that.fileinfo.uploadfiles); that.fileinfo.uploadfiles.push(result.Data); that.$message.success("上传附件成功。"); } else { //that.fileList = []; for (var i = 0; i < that.fileList.length; i++) { if (that.fileList[i].status != "done") { that.fileList.splice(i, 1); } } that.$message.warning(result.ResultMessage); } }) .catch(function (error) { console.log(error); }); }, fileRemove(file) { //console.log(file); var that = this; for (var i = 0; i < that.fileinfo.uploadfiles.length; i++) { if ( that.fileinfo.uploadfiles[i].oldfilename == file.name && that.fileinfo.uploadfiles[i].filesize == file.size ) { that.fileinfo.uploadfiles.splice(i, 1); //alert(1) } } }, }, }; </script>