1:文件上传需要导入的依赖包,还需要配置xml文件,
因为我这里是纯注解方式的方式;
<!-- 文件上传-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
<!-- io流-->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
2:然后就是html
<%--
Created by IntelliJ IDEA.
User: Andlime
Date: 2023/3/8
Time: 14:42
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<script src="../jq/jquery.js"></script>
</head>
<body>
<form method="post" enctype="multipart/form-data" id="form">
<input type="file" name="file" id="value">
<input type="button" value="提交" id="t">
</form>
<img src="">
</body>
<script>
$("#t").click(function (){
// 2.把传递给服务器数据,追加到formData对象里面
let formData = new FormData($("#form")[0]);
console.log("点击成功")
$.ajax({
url:'testFile',
method:"post",
data:formData,
// 告诉jQuery不要去处理发送的数据,用于对data参数进行序列化处理 这里必须false
processData : false,
// 告诉jQuery不要去设置Content-Type请求头
contentType : false,
success:function (data) {
console.log("返回")
}
})
})
</script>
</html>
3:然后就是后台的controller层的编写
/**
* 文件上传测试
* @param file
* @param request
*/
@PostMapping(value = "/**/testFile")
public void testFile(@RequestBody MultipartFile file,HttpServletRequest request){
//获取当前项目路径(存储图片的文件夹)
String path = request.getSession().getServletContext().getRealPath("/myFile");
//将上传的文件保存
try {
//1:获得当前上传文件的输入流
InputStream inputStream = file.getInputStream();
//2:获得当前上传文件的输出流
FileOutputStream fileOutputStream = new FileOutputStream(path+"/"+file.getOriginalFilename());//文件名字
//3:执行文件拷贝
IOUtils.copy(inputStream,fileOutputStream);
//4:关闭流资源
inputStream.close();
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
4:这个是我自己项目所存放上传文件的包
现在下面是没有任何文件的;
5:然后我们现在来运行看结果,能不能保存进去