引入文件上传依赖
commons-fileupload
commons-fileupload
1.4
创建upload(上传)页面
<%--
method: 提交方式 文件上传必须为post提交。
enctype:默认application/x-www-form-urlencoded 表示提交表单数据
multipart/form-data:可以包含文件数据
input的类型必须为file类型,而且必须有name属性
--%>
在springmvc中配置文件上传解析器
创建upload01接口方法
@RequestMapping("upload01")
@ResponseBody
public String upload01(MultipartFile myfile01, HttpServletRequest request) throws Exception{
//获取上传到本地服务的目录地址
String path = request.getSession().getServletContext().getRealPath("upload");
System.out.println(path);
//判断该目录是否存在
File file1 = new File(path);
if(!file1.exists()){
file1.mkdirs();
}
//把myfile01保存到本地服务中某个文件夹下。
String filename = UUID.randomUUID().toString().replace("-", "") + myfile01.getOriginalFilename();
File target = new File(path+"/"+filename);
myfile01.transferTo(target);//把myfile01转移到目标目录下
return "";
}
3.elementui+vue+axios完成文件上传
设计页面布局
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
Title
后台接口
@RequestMapping("upload02")
@ResponseBody
public Map upload02(MultipartFile myfile02,HttpServletRequest request){
try{
//获取上传到服务器的文件夹路径
String path = request.getSession().getServletContext().getRealPath("upload");
//判断目录是否存在
File file2 = new File(path);
if(!file2.exists()){
file2.mkdirs();
}
//设置上传后的文件名称
String filename2 = UUID.randomUUID().toString().replace("-", "") + myfile02.getOriginalFilename();
File target = new File(path+"/"+filename2);
myfile02.transferTo(target);
Map map = new HashMap();
map.put("code",200);
map.put("msg","登录成功");
//通过访问服务器地址来访问图片
map.put("data","http://localhost:8080/springmvc_16/upload"+filename2);
return map;
}catch (Exception e){
e.printStackTrace();
}
Map map = new HashMap();
map.put("code",500);
map.put("msg","登录失败");
return map;
}
4.上传到oss阿里云的服务器
上传到本地服务器的缺点: 如果搭建集群,导致文件无法在集群中共享。 解决方法就是把文件专门上传到一个文件服务器上,这些tomcat服务器都操作同一个文件服务器。
申请oss文件服务



