在原始的Servlet中

要上传文件最原始的方法是使用io流:
request.getInputStream()获取request请求的io流来获取文件 


在SpringMVC中,(在比较新版本的servlet也适用)

提供了上传文件的工具,需引入包:

然后,配置文件:【commonsMultipartResolver是spring提供的处理上传文件配置的类】

multipartFile是一个接口,是spring用来接收文件的,常用方法:

注意:前端表单的enctype必须是multipart/form-data,否则识别不了
代码:

多文件上传:
MultipartFile[]
接收,然后用for循环一个个存储就行了


在SpringBoot中:

springboot的web框架已经自动集成上传工具了,无需导包。

配置文件:(此时我的项目版本为2.1.6)


上传图片的例子(多文件上传):
 
@Value("${web.upload-path}") private String path;

public
String upload2(@RequestParam("files") MultipartFile[] multipartFiles,@RequestParam("text1")String text1,Model model){
StringBuilder sb=new StringBuilder();//用于存储路径名,可以返回给前端显示图片 

if (multipartFiles.length>0){ for (MultipartFile multipartFile:multipartFiles){
//String localPath = "src/main/resources/static/images"; String localPath="C:/Users/asus/Desktop"; String filename=multipartFile.getOriginalFilename(); // 获得文件类型 String fileType = multipartFile.getContentType(); // 获得文件后缀名称 String suffix=filename.substring(filename.lastIndexOf(".")); String suffix2=filename.substring(filename.lastIndexOf(".")+1); //String imageName = fileType.substring(fileType.indexOf("/") + 1); String allowImgFormat = "gif,jpg,jpeg,png"; if (!allowImgFormat.contains(suffix2.toLowerCase())) { System.out.println( "上传的图片不符合格式要求" ); }
//随机生成的姓名
String uuid = UUID.randomUUID().toString().replaceAll("-", ""); String newFileName=uuid+suffix;
// 生成保存路径名
String realPath = path + "/" + newFileName;
File dest = new File(realPath);
//判断文件父目录是否存在
if(!dest.getParentFile().exists()){ dest.getParentFile().mkdirs();
}
try { //保存文件
multipartFile.transferTo(dest);
} catch (IllegalStateException e) { e.printStackTrace();
} catch (IOException e) { e.printStackTrace();
}
System.out.println(path+" "+filename+" "+fileType+" "+newFileName); try { Thumbnails.of(realPath)//这里是压缩文件的插件,详情网上查一下 .size(120, 120) .toFile(path + "/compress" + newFileName); }
catch (IOException e) { e.printStackTrace();
} //读取相对路径
String getpath="/" + newFileName;//原图地址
String getcompresspath="/compress" + newFileName;//压缩图片的地址
System.out.println(getpath);
System.out.println(getcompresspath);
//return "redirect:/"+newFileName;
//model.addAttribute("img", "/" + newFileName);
sb.append(getpath+","+getcompresspath+";"); } }
//System.out.println(text1);
String msg=sb.toString();
sb.setLength(0);
System.out.println(msg);//输出本次保存的全部文件的图片地址与压缩图片地址
return msg;
}