配置部分参考java --多文件上传1
直接贴出代码
1.controller层
/**
*
* 测试文件上传
*
* **/
@RequestMapping(value = "/test", method = RequestMethod.POST)
public ResultObject test(MultipartHttpServletRequest request) {
System.out.println("request:" + request);
ResultObject ro = customerCommentService.test(request);
return ro;
}
2.service层
/**
* 测试文件上传
*
* **/
public ResultObject test(MultipartHttpServletRequest request);
3.service实现层
/**
*
* 测试文件上传
*
* **/
public ResultObject test(MultipartHttpServletRequest request){
ResultObject ro = new ResultObject();
//接收所有的文件
List<MultipartFile> file = request.getFiles("files");
System.out.println("取到的文件个数:"+file.size());
//获取系统路径
String ctxPath=request.getSession().getServletContext().getRealPath("/")+"Upload\\";
System.out.println("文件路径:"+ctxPath);
//如果目录不存在,则新建
File dir = new File(ctxPath);
if(!dir.exists()){
dir.mkdirs();
}
//创建文件输出流
FileOutputStream fileOutputStream = null;
//记录上传过程起始时的时间,用来计算上传时间
int pre = (int) System.currentTimeMillis();
for (int i = 0; i < file.size(); i++)
{
if (!file.get(i).isEmpty())
{
//获得文件名字
String fileName = file.get(i).getOriginalFilename();
System.out.println("上传的文件名:"+fileName);
try{
//拿到输出流
fileOutputStream = new FileOutputStream(ctxPath+fileName);
//
fileOutputStream.write(file.get(i).getBytes());
//
fileOutputStream.flush();
}catch(Exception e)
{
e.printStackTrace();
//上传失败
}
if (fileOutputStream != null) {
try {
//关闭流
fileOutputStream.close();
//上传成功
}catch(Exception e)
{
e.printStackTrace();
//上传失败
}
}
}
}
//记录上传该文件后的时间
int finaltime = (int) System.currentTimeMillis();
System.out.println(finaltime - pre);
return ro;
}
4.测试代码
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html" charset="utf-8">
<title> This is my HTML </title>
</head>
<body>
<h3> 上传多文件实例 </h3>
<form action="http://192.168.2.67:8080/pets/test" method="post" enctype="multipart/form-data">
选择文件1:<input type="file" name="files"><br>
选择文件2:<input type="file" name="files"><br>
<input type="submit" value="提交">
</form>
</body>
</html>
5.浏览器请求
注意查看,选择的文件名称
6.断点调试
7.物理路径查看文件
自此,结束。