在pom.xml添加这几个依赖
二、在springMVC的配置文件添加配置org.springframework spring-webmvc5.2.22.RELEASE commons-fileupload commons-fileupload1.4 com.fasterxml.jackson.core jackson-databind2.13.3 javax.servlet javax.servlet-api3.1.0
添加文件上传配置
三、开始配置控制器
@RequestMapping(value = "/upload",method = RequestMethod.POST)
@ResponseBody
public Result upload(MultipartFile file,HttpSession session) throws IOException{
//获取服务器路径
String path = session.getServletContext().getRealPath("/upload");
//获取原文件名字
String originalName = file.getOriginalFilename();
//随机生成文件的名字
String newName = UUID.randomUUID().toString().replace("-", "")
+ originalName.substring(originalName.indexOf("."));
File file1 = new File(path);
//如果目录不存在 就创建目录
if(!file1.exists() || !file1.isFile()){
file1.mkdirs();
}
file1 = new File(file1, newName);
//生成新名字的目标文件是否存在 不存在则创建文件
if(!file1.exists()){
file1.createNewFile();
}
//io流input读取 output写入
try(
InputStream read = myFile.getInputStream();
OutputStream out = new FileOutputStream(file1);
){
byte[] bytes = new byte[1024];
int ch = 0;
while((ch = read.read(bytes)) != -1){
out.write(bytes, 0, ch);
}
out.flush();
out.close();
return Result.success("上传成功!", "http://localhost:8080/SpringMvcLogin01/uploadupload/"+newName);
}catch (Exception e){
e.printStackTrace();
return Result.error("上传失败!");
}
}
四、jsp页面
<%--
Created by IntelliJ IDEA.
User: DELL
Date: 2022/6/9
Time: 18:57
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
Title



