You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.
package com.jiudian.manage.until ; // 工具类包,存放系统通用工具方法
import java.io.File ;
import java.io.FileOutputStream ;
/**
* 文件操作工具类
* 提供文件上传的通用方法,支撑系统中文件(如用户头像、凭证图片)的服务器存储功能
*/
public class FileUtil {
/**
* 上传文件到服务器指定路径
* @param file 待上传的文件字节数组(前端传递的文件会转为字节数组形式传输)
* @param filePath 服务器上的文件存储目录路径(如"D:/hotel_upload/avatar/")
* @param fileName 上传后的文件名(建议包含唯一标识,避免文件名重复覆盖)
* @return 布尔值: true=上传成功, false=上传失败( 实际逻辑中当前仅返回true, 异常通过throws抛出)
* @throws Exception 抛出文件操作相关异常( 如IO异常、权限异常) , 需调用方捕获处理
*/
public static boolean uploadFile ( byte [ ] file , String filePath , String fileName ) throws Exception {
// 1. 根据存储目录路径创建File对象
File targetFile = new File ( filePath ) ;
// 2. 判断存储目录是否存在, 不存在则创建多级目录( mkdirs()支持创建嵌套目录, mkdir()不支持)
if ( ! targetFile . exists ( ) ) {
targetFile . mkdirs ( ) ;
}
// 3. 创建文件输出流,指定文件存储路径(目录路径 + 文件名)
FileOutputStream out = new FileOutputStream ( filePath + fileName ) ;
// 4. 将文件字节数组写入到输出流(即写入到服务器文件)
out . write ( file ) ;
// 5. 刷新输出流,确保所有字节都被写入文件
out . flush ( ) ;
// 6. 关闭输出流, 释放IO资源( 避免资源泄漏)
out . close ( ) ;
// 7. 文件写入完成,返回上传成功
return true ;
}
}