文件上传下载工具类

package org.jmis.equipment.util;

import org.springframework.web.multipart.MultipartFile;
import org.springjmis.core.boot.file.BladeFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

public class FileManage {

	private static final String FILE_PATH = "/data/document";

	public static BladeFile uploadFile(MultipartFile file, String filePath) throws Exception {
		BladeFile bladeFile = new BladeFile();
		File localFile = null;
		//判断文件是否是空
		if (file.isEmpty()) {
			throw new Exception("文件为空,请检查文件");
		}

		try{
			//获取文件名称
			String filename = file.getOriginalFilename();
			//获取文件后缀
			String fileName = UUID.randomUUID().toString();//新生成的文件名字
			String suffixString = filename.substring(filename.lastIndexOf("."));//后缀
			//判断文件时pdf或者是word文件
			if (".docx".equals(suffixString) || ".pdf".equals(suffixString)) {
				bladeFile.setFileName(fileName+suffixString);
				bladeFile.setOriginalFileName(filename);
				File fileInfo = new File(filePath);

				//生成新的文件名字的文件
				localFile = new File(fileInfo.getCanonicalPath() + File.separator + fileName+suffixString);
				//文件上传
				file.transferTo(localFile);
				bladeFile.setUploadPath(localFile.getPath());
			}
		} catch (IOException e) {
			//如果文件异常删除文件
			localFile.delete();
			e.printStackTrace();
		}
		return bladeFile;
	}


	public static void downloadFile(String name, HttpServletResponse httpServletResponse,String filePath) {
		try {
			//创键输入流,读取数据
			FileInputStream inputStream=new FileInputStream(filePath+File.separator+name);
			ServletOutputStream outputStream = httpServletResponse.getOutputStream();
			int len=0;
			byte[] b=new byte[1024];
			while((len=inputStream.read(b))!=-1){
				outputStream.write(b,0,len);
			}
			inputStream.close();
			outputStream.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值