(1)导入文件上传的jar包-commons-fileupload
commons-fileupload commons-fileupload1.4
(2) 创建jsp页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
Title
(3)在springmvc.xml中配置文件上传解析器
(4)创建upload01接口方法
@Controller
public class UploadController {
@RequestMapping("/upload")
public String upload(MultipartFile myfile, HttpServletRequest request) throws Exception{
String path = request.getSession().getServletContext().getRealPath("upload");
System.out.println(path); //上传文件的本地路径
//新建文件夹
File file=new File(path);
//检测。如果文件不存在,将会创建一个文件
if(!file.exists()){
file.mkdirs();
}
//生成随机的字符串
//replace:替换
String fileName = UUID.randomUUID().toString().replace("-","")+myfile.getOriginalFilename();
File target = new File(path+"/"+fileName);
myfile.transferTo(target);
return "";
}
}
3. elementui+vue+axios完成文件上传
(1)页面的布局
<%--
Created by IntelliJ IDEA.
User: xu
Date: 2022/6/9
Time: 18:56
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
Title
(2)后端的页面
@RequestMapping("/upload02")
//输出JSon格式
@ResponseBody
//MultipartFile file:前端页面默认的name为file
public Map upload02(MultipartFile file, HttpServletRequest request){
try {
String path = request.getSession().getServletContext().getRealPath("upload");
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);
Map map=new HashMap();
map.put("code",2000);
map.put("msg","上传成功");
//路径为服务器的路径
map.put("data","http://localhost:8080/upload/"+fileName);
return map;
} catch (IOException e) {
e.printStackTrace();
}
Map map=new HashMap();
map.put("code",5000);
map.put("msg","上传失败");
return map;
}



