效果
项目代码结构
关键代码
HTML
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>
<form id="formId" action="/d/testUpload3" target="frame1" method="POST" enctype="multipart/form-data">
<input type="text" name="username"></input>
<input type="file" name="file"/>
<input type="button" value="提交" onclick="upload()">
</form>
<iframe name="frame1" frameborder="0" height="40"></iframe>
<script type="text/javascript">
function upload() {
$("#formId").submit();
}
</script>
</body>
</html>
Controller
package com.zz.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
@RestController
public class FileController {
//@Value 获取配置文件里面的属性值,并且赋值给下面的属性
@Value("${fileUpLoadPath}")
String filePath;
/**
* @RequestMapping 表示同时支持接收post和get请求。
* 如果加上method=RequestMethod.POST, 表示只接收post请求
* 其实有一个注解可以直接指定,只接收post请求---@PostMapping
* @param req
* @param multiReq
* @throws IOException
*/
@PostMapping("/testUpload3")
// @RequestMapping(value="/testUpload3",method=RequestMethod.POST)
public void testUploadFile(HttpServletRequest req,MultipartHttpServletRequest multiReq) throws IOException{
MultipartFile multipartFile= multiReq.getFile("file");
String filename=multipartFile.getOriginalFilename();
System.out.println("文件名字:"+multipartFile.getOriginalFilename());
File file=new File(filePath+filename);
multipartFile.transferTo(file);
String username=req.getParameter("username");
System.out.println("用户名字:"+username);
}
}
application.properties
server.port=9083
server.servlet.context-path=/d
spring.servlet.multipart.max-file-size=100MB
spring.servlet.multipart.max-request-size=100MB
fileUpLoadPath=C://tmp//