SpringMVC 单文件,多文件上传实现详解

这篇文章主要介绍了SpringMVC 单文件,多文件上传实现详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

需要用到的流的相关知识:

SpringMVC中写好了文件上传的类。

要使用文件上传,首先需要文件上传相关的jar包。commons-fileupload.jar 和 commons-io.jar。

添加到pom.xml或lib文件夹下。

pom.xml:

commons-fileuploadcommons-fileupload1.3.1commons-iocommons-io2.4

在SprigMVC的配置文件添加bean(id和class都是固定写法):

前端写一个文件上传的表单,一个文件上传的表单(多文件上传的表单中,多个文件输入input中的name相同):

文件描述:

请选择文件

文件描述:

请选择文件

请选择文件1:

请选择文件2:

文件上传中,参数要使用multipartfile而不是File类,不能使用FileUtils.copyFile()来复制文件,因此使用流来输出到磁盘

文件文件只是将单文件中传递来的file参数改为数组形式,将方法内的file有关的操作都变为数组即可。

文件上传

也可以不使用流,下面这句看到有人使用,但是没有测试。

File dest = new File(filePath + fileName); file.transferTo(dest);

@RequestMapping("testUpload") public String testUpload(@RequestParam("desc") String desc, @RequestParam("file") multipartfile file) throws IOException { System.out.println("文件描述:" + desc); // 得到文件的输入流 InputStream inputStream = file.getInputStream(); // 得到文件的完整名字 img.png/hh.docx String fileName = file.getoriginalFilename(); // 输出流 OutputStream outputStream = new FileOutputStream("C:\tmp\" + fileName); // 缓冲区 byte[] bs = new byte[1024]; int len = -1; while ((len = inputStream.read(bs)) != -1) { outputStream.write(bs,0,len); } inputStream.close(); outputStream.close(); return "success"; }

文件上传

@RequestMapping("testMutiUpload") public String testMutiUpload(@RequestParam("desc") String desc, @RequestParam("file") multipartfile[] files) throws IOException { System.out.println("文件描述:" + desc); for (multipartfile file : files) { InputStream inputStream = file.getInputStream(); String fileName = file.getoriginalFilename(); OutputStream outputStream = new FileOutputStream("C:\tmp\" + fileName); byte[] bs = new byte[1024]; int len = -1; while ((len = inputStream.read(bs)) != -1) { outputStream.write(bs,0,len); } inputStream.close(); outputStream.close(); } return "success"; }

相关文章

HashMap是Java中最常用的集合类框架,也是Java语言中非常典型...
在EffectiveJava中的第 36条中建议 用 EnumSet 替代位字段,...
介绍 注解是JDK1.5版本开始引入的一个特性,用于对代码进行说...
介绍 LinkedList同时实现了List接口和Deque接口,也就是说它...
介绍 TreeSet和TreeMap在Java里有着相同的实现,前者仅仅是对...
HashMap为什么线程不安全 put的不安全 由于多线程对HashMap进...