- 首先创建一个Spring web项目
- 在resources/static目录下创建upload.html,页面代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>上传文件到服务器</title>
</head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="uploadFile" value="请选择文件夹">
<input type="submit" value="上传">
</form>
</body>
</html>
- 创建文件上传的前端控制器类
package com.example.file;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.xml.ws.http.HTTPBinding;
import java.io.File;
import java.io.IOException;
/**
* @author L葵乄阳S
* @version 1.0
* @description: TODO
* @date 2023/5/23 14:01
* @PROJECT_NAME JavaFoundation
* @NAME UploadController.java
*/
@RestController
public class UploadController {
@PostMapping("/upload")
public String upload(MultipartFile uploadFile, HttpServletRequest request){
String realPath =request.getSession().getServletContext().getRealPath("/uploadFile");
File dir =new File(realPath);
if (!dir.isDirectory()){
dir.mkdir();
}
try{
String fileName = uploadFile.getOriginalFilename();
// 服务器保存的文件对象
File fileServer = new File(dir,fileName);
System.out.println("file文件真实的路径:"+fileServer.getAbsolutePath());
// 2.实现上传
uploadFile.transferTo(fileServer);
String filePath = request.getScheme()+"://"+
request.getServerName()+":"
+request.getServerPort()
+"/uploadFile/"+fileName;
// 3.返回可访问的网络地址
return filePath;
}catch (IOException e){
e.printStackTrace();
}
return "上传失败!";
}
}
- 测试
测试成功!