在开发JAvaweb中封装一套用于文件上传的方法
时间: 2024-03-08 15:50:19 浏览: 25
好的,针对文件上传的需求,可以封装以下方法:
```java
public class FileUtils {
/**
* 上传文件
* @param file 待上传的文件
* @param destPath 文件上传后保存的路径
* @return 上传成功返回true,否则返回false
* @throws IOException
*/
public static boolean uploadFile(MultipartFile file, String destPath) throws IOException {
File destFile = new File(destPath);
if (!destFile.getParentFile().exists()) {
destFile.getParentFile().mkdirs();
}
file.transferTo(destFile);
return true;
}
/**
* 删除文件
* @param filePath 待删除文件的路径
* @return 删除成功返回true,否则返回false
* @throws IOException
*/
public static boolean deleteFile(String filePath) throws IOException {
File file = new File(filePath);
if (file.isFile() && file.exists()) {
return file.delete();
}
return false;
}
/**
* 获取文件名的后缀
* @param fileName 文件名
* @return 文件后缀
*/
public static String getFileSuffix(String fileName) {
return fileName.substring(fileName.lastIndexOf(".") + 1);
}
}
```
其中,`uploadFile`方法用于上传文件,`deleteFile`方法用于删除文件,`getFileSuffix`方法用于获取文件名的后缀。需要注意的是,`MultipartFile`类是Spring框架提供的用于处理文件上传的类,需要在Controller中注入并使用。