配置部分参考java --多文件上传1
html
直接贴出代码java
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层
app
/** * 测试文件上传 * * **/ public ResultObject test(MultipartHttpServletRequest request);
3.service实现层
post
/** * * 测试文件上传 * * **/ 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.浏览器请求ui
注意查看,选择的文件名称调试
6.断点调试code
7.物理路径查看文件orm
自此,结束。