单文件上传:
public class UploadFile {
public String oneFileUpload(HttpServletRequest request, HttpServletResponse response, MultipartFile file) {
// 储存文件名
String fileName = null;
if (file != null) {
// 获取项目web文件保存路径
String currentPath = request.getServletContext().getRealPath("/uploadFile/");
System.out.println("【图片保存路径】:" + currentPath);
// 如果目录不存在,自动创建文件夹
File dir = new File(currentPath);
if (!dir.exists()) {
dir.mkdir();
System.out.println("【保存图片的文件夹不存在,新建一个文件夹】");
}
try {
fileName = Upload(currentPath, file);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return fileName;
}
public String Upload(String currentPath, MultipartFile file) throws Exception {
if (file != null) {
// 文件名后缀
String fileName = file.getOriginalFilename();
String suffix = null;
/**
* 【注意!!!】 用indexOf('.')方法截取字符串:
* 如果String的indexOf方法返回查找字符在字符串中的位置,但是没找到的话就会返回-1
*/
int index = fileName.indexOf('.');
if (index != -1) {
suffix = fileName.substring(fileName.indexOf('.'));
// 上传文件名 生成唯一识别码
String OriginalFileName = UUID.randomUUID() + suffix;// UUID.randomUUID()
System.out.println("【上传文件生成唯一识别码】:" + OriginalFileName);
// 要上传服务器端保存的文件对象 文件保存路径:currentPath 文件名:OriginalFileName
File serviceFile = new File(currentPath + OriginalFileName);
file.transferTo(serviceFile); // 将文件写入到服务器端文件内
return OriginalFileName;
}
return null;
}
return null;
}
}
直接调用oneFileUpload()方法就ok