基本上,我有一个从教程中获得的方法(我的主要目标是简单地从spring boot服务器返回图像,以便我可以在Angular中动态查看它们)
@RestController
public class FileController {
@Autowired
ServletContext context;
@GetMapping(path = "/allImages")
public ResponseEntity<List<String>> getImages(){
List<String> images = new ArrayList<String>();
String filesPath = context.getRealPath("/images");
File fileFolder = new File(filesPath);
if(fileFolder!=null) {
for(final File file : fileFolder.listFiles()) {
if(!file.isDirectory()) {
String encodeBase64 = null;
try {
String extention = FilenameUtils.getExtension(file.getName());
FileInputStream fileInputStream = new FileInputStream(file);
byte[] bytes = new byte[(int)file.length()];
encodeBase64 = Base64.getEncoder().encodeToString(bytes);
images.add("data:image/"+extention+";base64,"+encodeBase64);
fileInputStream.close();
} catch (Exception e) {
// TODO: handle exception
}
}
}
}
return new ResponseEntity<List<String>>(HttpStatus.OK);
}使用当前代码,当我尝试返回文件时,我得到:
java.lang.NullPointerException: Cannot read the array length because the return value of "java.io.File.listFiles()" is null我一直在寻找,并注意到人们推荐使用java.nio.file,但我有点迷茫,我不知道如何在这里实现它。任何帮助都是非常感谢的。
发布于 2021-03-29 21:15:07
我用下面的代码解决了这个问题:
@Autowired
ServletContext context;
@GetMapping(path = "/allImages")
public List<String> readImages() throws IOException {
return Files.list(Paths.get(context.getRealPath("/images")))
.filter(Files::isRegularFile)
.map(this::encode)
.filter(Objects::nonNull)
.collect(Collectors.toList());
}
private String encode(Path file) {
try {
String extension = FilenameUtils.getExtension(file.getFileName().toString());
String encodeBase64 = Base64.getEncoder().encodeToString(Files.readAllBytes(file));
return "data:image/"+extension+";base64,"+encodeBase64;
} catch (Exception e) {
return null;
}
}感谢每一个帮助过我们的人。
发布于 2021-03-29 20:15:11
首先获取文件夹的Path:
Path folderPath = Paths.get(filesPath);如果Path指向某个目录,则可以使用Files.list获取其内容的Stream<Path>
if (Files.isDirectory(folderPath)) {
List<Path> files = Files.list(folderPath)
.filter(path -> !Files.isDirectory(path))
.collect(Collectors.toList());
// Do something with the files.
}看起来您并没有使用FileInputStream做任何事情,所以您应该不需要翻译该部分。要获得路径的文件扩展名,您可能需要将Path转换为字符串,然后自己提取扩展名。
发布于 2021-03-29 20:16:33
使用nio的示例:
public List<String> readImages() throws IOException {
return Files.list(Path.of("/images"))
.filter(Files::isRegularFile)
.map(this::encode)
.filter(Objects::nonNull)
.collect(Collectors.toList());
}
private String encode(Path file) {
try {
String extension = FilenameUtils.getExtension(file.getFileName().toString());
String encodeBase64 = Base64.getEncoder().encodeToString(Files.readAllBytes(file));
return "data:image/"+extension+";base64,"+encodeBase64;
} catch (Exception e) {
return null;
}
}https://stackoverflow.com/questions/66853771
复制相似问题