springboot+vue+element-ui实现文件上传前后台代码+文件上传后台工具类

10/18 08:27
阅读数 34
//新增模板接口
@PreAuthorize("@ss.hasPermi('pshdhx:template:add')")
@Log(title="template",businessType=BusinessType.INSERT)
@PostMapping("add")
@ResponseBody
public AjaxResult add (Template template,MutipartFile file){
	if(file!=null){
		String filePath = MyProjectConfig.getUploadPath();	//获取服务器上传文件的路径
		String templateFilePath = FileUploadUtil.upload(filePath,file); //文件上传,返回文件存储路径
		template.setTemplateFilePath(templateFilePath);
		template.setTemplateFileName(file.getOriginalFilename());
	}
	return toAjax(templateService.insertTemplate(template));
}

//文件上传工具类
/**
*@author pshdhx
*/
public class FileUploadUtil{
	//默认大小
	public static final long DEFAULT_MAX_SIZE = 50 *1024 *1024;

	//默认的文件名最大长度
	public static final int DEFAULT_FILE_NAME_LENGTH = 100;

	//默认上传的服务器路径
	private staitc String defaultBaseDir = MyProject.getProfile();

	private staitc int counter = 0;

	public static void setDefaultBaseDir(String defaultBaseDir){
		FileUploadUtil.defaultBaseDir = defaultBaseDir;
	}

	public static String getDefaultBaseDir(){
		return defaultBaseDir;
	}

	//以默认配置进行文件上传
	public static final String upload(MutipartFile file) throws IOException{
		try{
			return upload(getDefaultBaseDir(),file,MimeTypeUtils.Default_ALLOWED_EXTENSION);
		}
		catch(Exception e){
			throw new IOException(e.getMessage(),e);
		}
	}
	//根据文件路径进行上传
	public static final String upload(String baseDir,MultipartFile file) throws Excetion{
		try{
			return upload(baseDir,MimeTypeUtil.DEFAULT_ALLOWED_EXTENSION);
		}catch(Exception){
			throw new IOException(e.getMessage(),e);
		}
	}

	//文件上传
	public static final String upload(String baseDir,MutipartFile file,String[] allowedExtension)
		throws FileSizeLimitExceededException,IOEXxception,FileNameLengthLimitExceedException,
		InvalidExtensionException{
			int fileNamelength = file.getOriginalFilename().length();
			if(fileNamelength>FileUploadUti.DEFAULT_FILE_NAME_LENGTH){
				throw new FileNameLengthLimitExceededException(FileUploadUtil.DEFAULT_FILE_NAME_LENGTH);
			}
			assertAllowed(file,allowedExtension);
			String fileName = extracFilename(file);
			File desc = getAbsoluteFile(baseDir,fileName);
			file.transferTo(desc);
			String pathFileName = getPathFileName(baseDir,fileName);
			return pathFileName;
		}

	//编码文件名
	public static final String extracFilename(MultiPartFile file){
		String  fileName = file.getOriginalFilename();
		String extension = getExtension(file);
		fileName = encodingFilename(fileName)+ "." + extension;
		return fileName;
	}

	public static final File getAbsoluteFile(String uploadDir,String fileName) throws IOException{
		File desc = new File(new File(uploadDir).getAbsolutePath()+File.spearator+fileName);
		if(!desc.getParantFile().exists()){
			desc.getParentFile().mkdirs();
		}
		if(!desc.exists()){
			desc.createNewFile();
		}
		return desc;
	}

	private static final String getPathFileName(String uploadDir,String fileName) throws IOException{
		int dirLastIndex = MyProject.getProfile().length()+1;
		String currentDir = StringUtils.subString(uploadDir,DirLastIndex);
		String pathFileName = "/"+currentDir+"/"+fileName;
		return pathFileName;
	}
	//编码文件名
	private static final String encodingFilename(String fileName){
		fileName = fileName.replace("_"," ");
		fileName = Md5Utils.hash(fileName);
		return fileName;
	}
	//文件大小检验
	public static final void assertAllowed(MultipartFile file,String[] allowedExtension) throws
		FileSizeLimitExceededException,InvalidExtendsionException{
		long size = file.getSize();
		if(DEFAULT_MAX_SIZE !=-1 && size> DEFAULT_MAX_SIZE){
			throw new FileSizeLimitExceededException(DEFAULT_MAX_SIZE/1024/2014);
		}
		String fileName = file.getOriginalFilename();
		String extension = getExtension(file);
		if(allowedExtension != null && !isAllowedExtension(extension,allowedExtension)){
			if(allowedExtension == MimeTypeUtils.IMAGE_EXTENSION){
				throw new InvalidExtensionException.InvalidImageExtensionException(allowedExtension,extension,fileName);
			}else if(allowedExtension == MimeTypeUtils.FLASH_EXTENSION){
				throw new InvalidExtension.InvalidFlashExtensionException(allowedExtension,extension,fileName);
			}else if(allowedExtension == MimeTypeUtils.MEDIA_EXTENSION){
				throw new InvalidExtensionException.InvalidMediaExtensionException(
					allowedExtension,extension,fileName);
			}else{
				throw new InvalidExtensionException(allowedExtension,extension,fileName);
			}
		}
	}
	//判断MIME类型是否是MIME允许的类型
	public static fianl boolean isAllowedExtension(String extension,String[] allowedExtension){
		for(String str : allowedExtension){
			if(str.equalIgnoreCase(extension)){
				return true;
			}
		}
		return false;
	}

	//获取文件名的后缀
	public static final String getExtension(MultipartFile file){
		String extension = FilenameUtils.getExtension(file.getOriginalFilename());
		if(StringUtils.isEmpty(extension)){
			extension = MimeTypeUtils.getExtension(file.getContentType());
		}
		return extension;
	}
}

//媒体类型工具类
public class MimeTypeUtis{
	public staitc final String IMAGE_PNG = "image/png";
	public static final String IMAGE_JPG = "image/jpg";
	public static fianl String IMAGE_JPEG = "image/jpeg";
	public static final String IMAGE_BMP = "image/bmp";
	public static final String IMAGE_GIF = "image/gif";

	public static fanal String[] IMAGE_EXTENSION = {"bmp","gif","jpg","jpeg","png"};
	public static final String[] FLASH_EXTENSION = {"swf","flv"};
	public static final String[] MEDIA_EXTENSION = {"swf","flv","mp3","wav","wma","wmv","mid","avi","mpg","asf","rm","rmvb"};
	public static final String[] DEFAULT_ALLOWED_EXTENSION = {
		//图片
		"bmp","gif","jpg","jpeg","png",
		//word excel powerpoint
		"doc","docx","xls","xlsx","ppt","pptx","html","htm","txt",
		//压缩文件
		"rar","zip","gz","bz2",
		//pdf
		"pdf"
	}
	public static String getExtension(String prefix){
		switch(prefix){
			case IMAGE_PNG:
				return "png";
			case IMGE_JPG:
				return "jpg";
			case IMAGE_JPEG
				return "jpeg";
			case IMAGE_BMP
				return "bmp";
			case IMAGE_GIT
				return "gif";
			default:
				return "";
		}
	}
}


element-ui +vue 实现文件上传前端
<el-form-item label="上传文件">
	<el-upload
		ref="upload"
		:limit="1"
		:data=”form“  //form是后端回显过来的表单数据
		:headers="upload.headers"
		:action="upload.url"
		:auto-upload="false"
		drag
		:on-error="uploadFalse"
		:on-success="uploadSuccess"
		:on-progress="handleFileUploadProgress"
		:before-upload="beforeAvatarUpload"
		:on-preview="downloadFile"
		:on-change="fileChange"
		:file-list="fileList"
	>
		<i class="el-icon-upload"></i>
		<div class="el-upload_text">
			将文件拖到此处,或<em>点击上传</em>
		</div>
	</el-upload>
</el-form-item>

定义数据对象:
	data(){
		return{
			upload:{
				headers:{Authorization:"Bearer"+getToken()},
				url:process.env.VUE_APP_BASE_API+"/basesystem/formtemplate/edit",
				isUploading:false
			},
			fileList:[],
		}
	},
	methods:{
		fileChange(file){
			this.form.fileName = file.name;
			this.changeFile = true;
		},
		uploadFalse(response,file,fileList){
			this.$message({
				message:'文件上传失败',
				type:"error"
			})
		},
		uploadSucccess(response,file,fileList){
			if(response.code == 200){
				this.$message({
					message:'上传成功',
					type:'succcess'
				})
				this.open = false;
				this.getList(); //重新请求页面数据
			}else{
				this.$message({
					message:'上传失败',
					type:'error'
				})
				this.open = false;
				this.getList();
			}
		},
		handleFileUploadProgress(event,file,fileList){
			this.uploadisUploading = true
		},
		//文件下载
		downloadFile(file){
			let a = document.createElement("a");
			a.href = this.downloadUrl;
			a.setAttribute("download","文件");
			a.click();
		},
		//上传之前
		beforeAvatarUpload(file){
			this.form.fileName = file.name;
			let tmp = file.name.subString(file.name.lastIndexOf(",")+1);
			const extension1 = temp==="xlsx";
			const extension2 = temp==="xlsm";
			const extension3 = temp==="xls";
			const ext = extension1||extension2||extension3;
			if(!extension1&&!extension2&&!extension3){
				this.$message({
					message:'上传文件必须是xls或是xlsx文件',
					type:'error'
				})
			}
			const isLt1m = file.size/1024/1024<1;
			if(!isLt1M){
				this.$message({
					message:'上传文件大小不能超过1MB'
					type:'error'
				})
			}
			return ext&& isLt1M;
		},

		//添加表单操作
		handleAdd(){
			this.upload.url = process.evu.VUE_APP_BASE_API+"/basesystem/formtempaltemanage/add",
			this.reset();
			this.getTreeselectFormClass();
			this.open = true;
			this.title = "添加表单模板"
		},
		//修改表单操作
		handleUpdate(row){
			this.reset();
			this.downloadUrl = proceess.env.VUE_APP_BASE_API+"/common/showing?delete=false&fileName="+row.fileName;
			const formTemplateId = row.formTemplateId || this.ids
			getTemplate(formTemplateId).then(response=>{
				this.form = response.data;
				this.open = true;
				this.title = "修改表单模板"
				this.fileList = [];
				this.fileList.push({name:response.data.fileName,url:process.evn.VUE_APP_BASE_API+
				"common/showing/?delte=false&fileName-"+response.data.formPath});
			})
		},
		//提交按钮
		submitForm:function(form){  //此处的form是从upload传递过来的
			delete form.params; //因为后端用实体类接受,所要删除前端自带的参数,要不然后端会报错
			this.$refs["form"].validate(valid=>{
				if(valid){
						if(this.form.formTemplateId!=undefined){
							//走修改接口
							uploadTemplate(this.form).then(res=>{
								if(res.code == 200){
									this.msgSuccess("修改成功");
									this.open = false;
									this.getList(); //重新请求表单数据
								}else{
									this.msgError(response.msg);
								}
							})
						}else{
							//走添加接口
							this.$refs.upload.submit();
						}
							
					}
			})
		}

	},

 

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部