文件上传下载工具类

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();
		}

	}

}

你可能感兴趣的:(servlet,java,开发语言)