1、直接使用 file.transferTo();
String path = "";
if(!StringUtils.isNull(file)){
String contentType = file.getContentType();
// 获得文件后缀
String imageSux = contentType.substring(contentType.indexOf("/")+1);
if(!(imageSux.equalsIgnoreCase("png") || imageSux.equalsIgnoreCase("jpg") || imageSux.equalsIgnoreCase("bmp") || imageSux.equalsIgnoreCase("jpeg") || imageSux.equalsIgnoreCase("gif"))){
return new AjaxResult(ERROR,"请上传正常的图片文件");
}
String uuid = UUID.randomUUID().toString().replaceAll("-","");
path = request.getSession().getServletContext().getRealPath("image");
String filename = uuid + "." + imageSux;
try {
File targetFile = new File(path, filename);
if(!targetFile.getParentFile().exists()){
targetFile.getParentFile().mkdirs();
targetFile.createNewFile();
}
crmUser.setHeadPhoto(path + "\\" + filename);
//写入文件
file.transferTo(targetFile);
} catch (Exception e) {
return new AjaxResult(ERROR,"上传出现异常");
}
}
2、JDK1.7以后,使用nio进行上传;
if(!StringUtils.isNull(file)){
try {
byte[] bytes = file.getBytes();
String contentType = file.getContentType();
// 获得文件后缀
String imageSux = contentType.substring(contentType.indexOf("/")+1);
if(!(imageSux.equalsIgnoreCase("png") || imageSux.equalsIgnoreCase("jpg") || imageSux.equalsIgnoreCase("bmp") || imageSux.equalsIgnoreCase("jpeg") || imageSux.equalsIgnoreCase("gif"))){
return new AjaxResult(ERROR,"请上传正常的图片文件");
}
String uuid = UUID.randomUUID().toString().replaceAll("-","");
String filename = uuid + "." + imageSux;
Path path = Paths.get(UPLOAD_FOLDER + filename);
//如果没有files文件夹,则创建
if (!Files.isWritable(path)) {
Files.createDirectories(Paths.get(UPLOAD_FOLDER));
}
//文件写入指定路径
Files.write(path, bytes);
crmUser.setHeadPhoto(path.toString());
logger.debug("文件写入成功...");
} catch (IOException e) {
e.printStackTrace();
return new AjaxResult(ERROR,"上传出现异常");
}
}
3、可以使用文件服务请求接口上传 SpringBoot请求第三方接口方式