//简单文件上传页面index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>文件上传</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/upload" enctype="multipart/form-data" method="post">
<input type="file" name="file">
<input type="submit" value="文件上传">
</form>
</body>
</html>
//文件上传代码
@RestController
public class FileController {
//@RequestParam("file") 将name=file控件得到的文件封装成CommonsMultipartFile 对象
//批量上传CommonsMultipartFile则为数组即可
@RequestMapping("/upload")
public String fileUpload(@RequestParam("file")CommonsMultipartFile file, HttpServletRequest request) throws IOException {
//获取文件名
String uploadFileName = file.getOriginalFilename();
//上传时可能遇到文件名中存在空格无法成功上传,将空格替换
// uploadFileName = uploadFileName.replaceAll(" ","");
// 使用uuid重新命名更加安全
// String newFileName = UUID.randomUUID() + "_" + uploadFileName;
//如果文件名为空,直接返回首页
if("".equals(uploadFileName)){
return "redirect:/index.jsp";
}
System.out.println("上传文件名:"+uploadFileName);
//上传路径保存
String path = request.getServletContext().getRealPath("/upload");
//当文件数量太多 想要通过日期归类
// Date date = new Date();
// SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
// String dateName = format.format(date);
// String filePath = path+"/"+dateName;
//如果路径不存在,创建一个目录
File realPath = new File(path);
if(!realPath.exists()){
realPath.mkdirs();
}
System.out.println("上传文件保存地址:"+realPath);
//第一种方式
//通过CommonsMultipartFile的方法直接写文件
file.transferTo(new File(realPath+"/"+uploadFileName));
// //第二种方式
// //文件输入流
// InputStream is = file.getInputStream();
// //文件输入流
// FileOutputStream os = new FileOutputStream(new File(newFile, uploadFileName));
// //读取写出
// int len = 0;
// byte[] buffer = new byte[1024];
// while((len = is.read(buffer))!= -1){
// os.write(buffer,0,len);
// os.flush();
// }
// os.close();
// is.close();
return "ok";
}