让我们在 webapp 中创建uploads目录并将文件保存在webapp/uploads中:
@RestController
public class GreetingController {
private final static Logger log = LoggerFactory.getLogger(GreetingController.class);
@Autowired
private HttpServletRequest request;
@RequestMapping(value = "/uploadfile", method = RequestMethod.POST)
public
@ResponseBody
ResponseEntity handleFileUpload(@RequestParam("file") MultipartFile file) {
if (!file.isEmpty()) {
try {
String uploadsDir = "/uploads/";
String realPathtoUploads = request.getServletContext().getRealPath(uploadsDir);
if(! new File(realPathtoUploads).exists())
{
new File(realPathtoUploads).mkdir();
}
log.info("realPathtoUploads = {}", realPathtoUploads);
String orgName = file.getOriginalFilename();
String filePath = realPathtoUploads + orgName;
File dest = new File(filePath);
file.transferTo(dest);
编码
String realPathtoUploads = request.getServletContext().getRealPath(uploadsDir);
如果我从 Idea IDE 运行应用程序,则返回下一条路径
C:\Users\Iuliia\IdeaProjects\ENumbersBackend\src\main\webapp\uploads\
如果我制作 .war 并在 Tomcat 下运行它,则为下一条路径:
D:\Programs_Files\apache-tomcat-8.0.27\webapps\enumbservice-0.2.0\uploads\
我的项目结构: