springboot实现文件上传和下载

springboot实现文件上传和下载

//配置文件中配置的,在服务器上统一保存文件的文件夹的绝对路径
@Value("${uploadFilePrefixPath}")
private String uploadFilePrefixPath;

/**
* 上传单个文件
*
* @param 	file		上传的文件
* @return	filePath	文件保存在服务器上的绝对路径
*/
@Transactional(readOnly = false)
public EntityResult uploadFile(MultipartFile file) {
	EntityResult result = new EntityResult<>();
	//校验文件是否为空
	if (file == null || file.isEmpty()) {
		return result.failCustom("上传的文件不能为空");
	}
	//校验文件后缀是否合法(根据需要校验,此处只能上传指定格式的图片和视频)
	String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
	//校验有效的文件格式
	if (!Global.validFileFormat.contains(suffix)) {
		return result.failCustom("文件格式错误");
	}
	//文件夹路径 + UUID(文件名)
	String realPath = uploadFilePrefixPath + "/" + UUID.randomUUID().toString().replaceAll("-","");
	//以上生成UUID的方法也可使用IdUtil.simpleUUID()
	File folder = new File(realPath);
	//文件夹不存在,则创建文件夹
	if (!folder.exists() && !folder.isDirectory()) {
		//创建多级文件夹
		folder.mkdirs();
	}
	//上传文件到服务器
	try {
		file.transferTo(new File(realPath));
		//上传成功
		result.success("filePath", realPath);
	} catch (IOException e) {
		//上传失败
		e.printStackTrace();
		result.failCustom("文件上传失败");
	}
	return result;
}

格式校验

public class Global {
	/**
	 * 上传的文件的有效格式
	 */
	public static final Set<String> validFileFormat = new HashSet<String>(){
		{
			//合法的图片后缀名
			add("bmp");
			add("jpg");
			add("jpeg");
			add("png");
			add("gif");
			add("BMP");
			add("JPG");
			add("JPEG");
			add("PNG");
			add("GIF");

			//合法的视频后缀名
			add("mp4");
			add("wmv");
			add("MP4");
			add("WMV");
			add("mov");
			add("MOV");
		}
	};
}

文件下载

/**
 * 文件下载
 *
 * @param 	filePath	下载的文件路径
 * @param 	response	
 */
@Transactional(readOnly = true)
public void download(String filePath, HttpServletResponse response) {
	File file = new File(filePath);
	//设置强制下载不打开
	response.setContentType("application/force-download");
	//设置文件名
	response.addHeader("Content-Disposition", "attachment;fileName=" + file.getName());
	byte[] buffer = new byte[1024];
	FileInputStream fis = null;
	BufferedInputStream bis = null;
	try {
		fis = new FileInputStream(file);
		bis = new BufferedInputStream(fis);
		OutputStream os = response.getOutputStream();
		int i = bis.read(buffer);
		while (i != -1) {
			os.write(buffer, 0, i);
			i = bis.read(buffer);
		}
		//下载成功
	} catch (Exception e) {
		e.printStackTrace();
		//下载失败
	} finally {
		if (bis != null) {
			try {
				bis.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if (fis != null) {
			try {
				fis.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值