前端的name名和后台的参数名需要对应
单文件上传
maven
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.11.0</version>
</dependency>
spring-mvc.xml
<!-- 配置文件上传解析器-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 上传编码-->
<property name="defaultEncoding" value="UTF-8"/>
<!-- 上传最大文件大小 -->
<property name="maxUploadSize" value="50000000"/>
</bean>
jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/user/uploadFile" method="post" enctype="multipart/form-data">
文件<input type="file" name="uploadFile"><br>
<input type="submit" value="提交"><br>
</form>
</body>
</html>
controller
package com.zhang.controller;
import com.zhang.pojo.User;
import com.zhang.pojo.UserOv;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.List;
@org.springframework.stereotype.Controller
@RequestMapping("/user")
public class Controller {
@RequestMapping("/uploadFile")
@ResponseBody
public void uploadFile(MultipartFile uploadFile) throws IOException {
//获取文件名称
String originalFilename = uploadFile.getOriginalFilename();
//将文件放到指定的地方
uploadFile.transferTo(new File("d:\\"+ originalFilename));
}
}
}
多文件上传
基本配置都一样只是后台和前端改变就可以了
jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/user/uploadFile" method="post" enctype="multipart/form-data">
文件<input type="file" name="uploadFile"><br>
文件1<input type="file" name="uploadFile"><br>
文件2<input type="file" name="uploadFile"><br>
<input type="submit" value="提交"><br>
</form>
</body>
</html>
controller
@RequestMapping("/uploadFile")
@ResponseBody
public void uploadFile(MultipartFile[] uploadFile) throws IOException {
for (MultipartFile multipartFile : uploadFile) {
//获取文件名称
String originalFilename = multipartFile.getOriginalFilename();
//将文件放到指定的地方
multipartFile.transferTo(new File("d:\\" + originalFilename));
}
}