以上传图片为例,废话不多说,直接上代码
//上传图片到文件夹or服务器文件夹并返回图片路径
public String addBenDiImg(MultipartFile file) {
String objectPath = "group1/M00/00/21/";
String path = null;// 文件路径
if (file != null) {// 判断上传的文件是否为空
String type = null;// 文件类型
String fileName = file.getOriginalFilename();// 文件原名称
// 判断文件类型
type = fileName.indexOf(".") != -1 ? fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()) : null;
if (type != null) {// 判断文件类型是否为空
if ("GIF".equals(type.toUpperCase()) || "PNG".equals(type.toUpperCase()) || "JPG".equals(type.toUpperCase())) {
String uuid = UUID.randomUUID().toString().replaceAll("-", "");
fileName = uuid + "." + type;
System.out.println("文件名称:" + fileName);
//服务器文件夹绝对路径
path = "xxx/group1/M00/00/21/";
File desc = new File(path);
if (!desc.exists()) {
desc.mkdirs();
log.info("创建文件夹,说明路径非绝对路径或者服务器没有这个文件夹");
}
try {
File newFile = new File(desc.getAbsolutePath() + File.separator + fileName);
file.transferTo(newFile);
} catch (IOException e) {
e.printStackTrace();
log.error(e.getMessage());
return "上传异常";
}
System.out.println("文件成功上传到指定目录下");
//放到服务器中则还需要拼接项目前缀+图片地址: http://xxx.com+服务器文件夹绝对路径+图片名
return objectPath + fileName;
}
} else {
return "不是我们想要的文件类型,请按要求重新上传";
}
} else {
return "文件类型为空";
}
return "已经成功上传到指定目录";
}
需要注意:上传关键代码就两行行:
File newFile = new File(desc.getAbsolutePath() + File.separator + fileName);
file.transferTo(newFile);
但是!在这之前newFile的参数一定只能用:上面的方式来创建!
以下是错误创建方式,以上述代码为例子:
File newFile = new File(path+fileName);
这样做代码可以编译和运行成功,但图片或文件并不会成功上传并且保存在文件夹中