Bah*_*Ali 6 java spring file-upload spring-boot
此答案不是获取应用程序根路径(文件系统路径)的标准方法。我需要将文件上传到目录,例如在应用程序主目录中创建的上传。如何在Java类中获取应用程序的根路径。我正在开发Rest API。请帮助这方面。
您可以简单地使用FileSystemResource来获取根目录:
new FileSystemResource("").getFile().getAbsolutePath()
Run Code Online (Sandbox Code Playgroud)
非弹簧方式:
或者,您也可以使用 来获取它System.getProperty("user.dir")。这也适用于properties,yml或文件。pom.xml
# properties file
info.root-dir=${user.dir}
Run Code Online (Sandbox Code Playgroud)
<!-- pom.xml -->
<properties> <!-- not really sure if anyone would ever do it -->
<another.project.dir>${user.dir}/../someproject</another.project.dir>
</properties>
Run Code Online (Sandbox Code Playgroud)
如果我理解正确,您想开发一个REST API,旨在将文件上传到应用程序目录中的目录。建议在资源目录中创建文件,图像等。基本上,您应该使用servlet上下文来获取此目录的绝对路径。首先,您需要ServletContext
@Autowired
ServletContext context;
Run Code Online (Sandbox Code Playgroud)
然后,您可以获得绝对和相对目录(“ resources / uploads”):
String absolutePath = context.getRealPath("resources/uploads");
File uploadedFile = new File(absolutePath, "your_file_name");
Run Code Online (Sandbox Code Playgroud)
编辑:
您想开发rest api。所以你可以先创建一个控制器类
@RestController
@RequestMapping("/file")
public class FileController {
@Autowired
ServletContext context;
@PostMapping("/upload")
public String fileUpload(@RequestParam("file") MultipartFile file) {
if (file.isEmpty()) {
throw new RuntimeException("Please load a file");
}
try {
// Get the file and save it uploads dir
byte[] bytes = file.getBytes();
Path path = Paths.get(context.getRealPath("uploads") + file.getOriginalFilename());
Files.write(path, bytes);
} catch (IOException e) {
e.printStackTrace();
}
return "success";
}
}
Run Code Online (Sandbox Code Playgroud)
还有另一种管理文件操作的方式,Spring Boot文档很好地解释了:上传文件Spring Boot
| 归档时间: |
|
| 查看次数: |
15709 次 |
| 最近记录: |