1. 文件上传的原理
2. 文件上传到本地服务器
(1)文件上传的依赖。
<!--文件上传的依赖-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
(2) 创建一个页面
<%--
Created by IntelliJ IDEA.
User: myL
Date: 2022/6/10
Time: 8:45
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%--
method:必须post提交
enctype:multipart/form-data 可以包含文件数据
input:必须file类型 必须有name属性
--%>
<form method="post" action="upload01" enctype="multipart/form-data">
<input type="file" name="myfile"/><br/>
<input type="submit" value="提交"/>
</form>
</body>
</html>
(3)在springmvc中配置文件上传解析器
<!--
上传文件拦截器
id必须为:multipartResolver
单位为字节
-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="10485760"/>
</bean>
</beans>
(3) 创建upload01接口方法
@RequestMapping("/upload01")
//注意:MultipartFile 参数名必须和<input type="file" name="myfile"/>中name相同
public String upload01(MultipartFile myfile, HttpServletRequest request) throws IOException {
//1.得到本地服务目录的地址
String path = request.getSession().getServletContext().getRealPath("upload");
System.out.println(path);
//2.判断该目录是否存在
File file = new File(path);
if (!file.exists()) {
file.mkdirs();
}
//3.把myfile保存到本地文件夹中
//随机一个文件名字
String filename= UUID.randomUUID().toString().replace("-","")+myfile.getOriginalFilename();
File target=new File(path+"/"+filename);
//把file转到目标目录下
myfile.transferTo(target);
return "";
}
3. elementui+vue+axios完成文件上传
(1)页面的布局
<%--
Created by IntelliJ IDEA.
User: myL
Date: 2022/6/10
Time: 9:34
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<!--引入element得css样式-->
<link type="text/css" rel="stylesheet" href="css/index.css"/>
<!--引入vue得js文件 这个必须在element之前引入-->
<script type="text/javascript" src="js/vue.js"></script>
<script type="text/javascript" src="js/qs.min.js"></script>
<script type="text/javascript" src="js/axios.min.js"></script>
<!--element得js文件-->
<script type="text/javascript" src="js/index.js"></script>
</head>
<body>
<div id="app">
<%--action:文件上传的路径--%>
<el-upload
class="avatar-uploader"
action="/upload02"
:show-file-list="false"
:on-success="handleAvatarSuccess"
:before-upload="beforeAvatarUpload">
<img v-if="imageUrl