准备工作: 需要先搭建一个spirngmvc的maven项目
- 1、加入jar包
commons-fileupload commons-fileupload 1.3
- 2、在springmvc的配置文件中,加入如下配置:
- 3、创建Controller
package cn.van.controller;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.io.IOException; /** * Created by van on 2017-07-18. */ @Controller @RequestMapping("/upload") public class MultipartFileController { //单文件上传 @RequestMapping("/toFileUpload") public String toUpload(){ return "fileUpload/fileUpload"; } @RequestMapping("fileUpload") @ResponseBody public String upload(MultipartFile multipartFile){ if(!multipartFile.isEmpty()){ //设置文件的保存路径 String filePath = "D:\\MultipartFile\\" + multipartFile.getOriginalFilename(); //转存文件 try { multipartFile.transferTo(new File(filePath)); } catch (IOException e) { e.printStackTrace(); } } return "success"; } //多文件上传 @RequestMapping("/toFileUploadFiles") public String toUploadFiles(){ return "fileUpload/fileUploadFiles"; } @RequestMapping("fileUploadFiles") @ResponseBody //此处用@RequestParam("xx")来指定参数名,不加会报错 public String uploadFiles(@RequestParam("multipartFile") MultipartFile[] multipartfiles) throws IOException { String savePath = "D:\\MultipartFile\\"; if(multipartfiles != null && multipartfiles.length != 0){ if(null != multipartfiles && multipartfiles.length > 0){ //遍历并保存文件 for(MultipartFile file : multipartfiles){ file.transferTo(new File(savePath + file.getOriginalFilename())); } } } return "success"; } }
- 4、写两个简单的上传页面(单文件和多文件)
单文件:
<%@page language="java" contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%> <%@include file="/WEB-INF/jsp/common/common.jsp"%>test test
多文件:
<%@page language="java" contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%> <%@include file="/WEB-INF/jsp/common/common.jsp"%>test test
5、访问页面,选择本地文件,上传成功。