不需要依赖包,直接用springboot的multipartFile对象
1、前端页面(index.html)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>上传图片</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="https://cdn.bootcss.com/jquery/2.2.4/jquery.min.js"></script>
</head>
<body>
<h3>请选择图片文件:JPG/GIF</h3>
<form name="form0" id="form0" action="/MyDubboStudy/getPicture" method="post" enctype="multipart/form-data">
<!--multiple="multiple"-->
<input type="file" name="file" id="file" /><br>
<img src="" id="img0" style="width: 20rem;height: 15rem;">
<input type="submit" value="提交" >
</form>
<script>
$("#file").change(function(){
var objUrl = getObjectURL(this.files[0]) ;//获取文件信息
console.log("objUrl = "+objUrl);
if (objUrl) {
$("#img0").attr("src", objUrl);
}
});
function getObjectURL(file) {
var url = null;
if (window.createObjectURL!=undefined) {
url = window.createObjectURL(file) ;
} else if (window.URL!=undefined) { // mozilla(firefox)
url = window.URL.createObjectURL(file) ;
} else if (window.webkitURL!=undefined) { // webkit or chrome
url = window.webkitURL.createObjectURL(file) ;
}
return url ;
}
</script>
</body>
</html>
2、设置限制的文件大小配置(application.properties)
//设置上传文件的大小(如果不设置上限,两个值设为-1)
//单个文件的大小
spring.servlet.multipart.max-file-size = 10MB
//上传的总文件大小
spring.servlet.multipart.max-request-size=100MB
3、后台代码(多文件上传,使用multipartFile[] 数据当作入参,以此循环)
package com.liu.web.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
@RestController
public class getPicController {
Logger logger = LoggerFactory.getLogger(this.getClass());
@RequestMapping(value = "/getPicture",method = RequestMethod.POST)
public void getPicture(MultipartFile file){
//文件名(my.jpg)
logger.info("----file.getName="+file.getOriginalFilename());
try {
HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
OutputStream outputStream = response.getOutputStream();
//直接返回流,自己另存为选择保存的地方
outputStream.write(file.getBytes());
}catch (Exception e){
logger.error("-----上传异常");
}
}
}
4、页面测试
5、提交之后,返回图片流