1.上传到本地服务器
1.引入文件上传的依赖
repMaven.commons-fileupload
commons-fileupload
1.4
2.在spring MVC中配置文件上传解析器
3.创建一个页面
4.创建接口方法
@Controller
public class LoginController {
@RequestMapping("login")
// //springMVC中使用MultipartFile 对象来接收上传的文件,通过这个对象可以得到文件的文件名和文件类型
public String login(MultipartFile wenjian, HttpServletRequest request)throws Exception{
//得到本地服务器的地址
String path = request.getSession().getServletContext().getRealPath("b");
//判断是否存在
File file=new File(path);
if (!file.exists()){
file.mkdirs();
}
//获取我们上传的文件的路径
//UUID.randomUUID().toString().replace("-","") 防止重名
//wenjian.getOriginalFilename() 获取文件的真实姓名
String filename= UUID.randomUUID().toString().replace("-","")+wenjian.getOriginalFilename();
File target=new File(path+"/"+filename);
//transferTo() 方法将文件写入到磁盘
wenjian.transferTo(target);
return "";
}
2.elementui+vue+axios完成文件上传
1.先页面布局
Title
2.创建接口方法
@Controller
public class Page {
@RequestMapping("page")
@ResponseBody
public Map page(MultipartFile file, HttpServletRequest request){
try {
//获取路径
String path = request.getSession().getServletContext().getRealPath("b");
File file1=new File(path);
if (!file1.exists()){
file1.mkdirs();
}
//获取我们上传的文件名字
String filename= UUID.randomUUID().toString().replace("-","")+file.getOriginalFilename();
File target=new File(path+"/"+filename);
file.transferTo(target);
//给页面传入json数据
Map m=new HashMap();
m.put("code",2000);
m.put("msg","上传成功");
m.put("data","http://localhost:8080/springmvc/b/"+filename);
return m;
} catch (Exception e) {
e.printStackTrace();
}
Map m=new HashMap();
m.put("code",5000);
m.put("msg","上传失败");
return m;
}
}