为了从文件系统中读取以下文件,我向方法提供了包括"c://“在内的完整文件名。下面是方法:
private Resource loadAsResource(String filename) throws MalformedURLException {
Path file = root.resolve(filename);
Resource resource = new UrlResource(file.toUri());
if (resource.exists() || resource.isReadable()) {
return resource;
}
return null;
}在打印日志时,我发现exist()和isReadable()都返回false。以下是tomcat日志中显示的错误:
cannot be resolved in the file system for checking its content length还请注意,当我刷新页面(角度9)时,文件(图片)显示在屏幕上,因此这不是路径问题。我已经搜索了解决方案,并找到了使用类路径的可能解决方案,但在我的情况下,我不能使用它,因为要求使用文件系统。文件夹不能在静态文件夹中,因为我不希望它在jar文件中。在生产环境中,该文件夹应包含140K文件,包括图片和视频。
发布于 2021-07-31 05:27:47
我不喜欢这个解决方案,但它很有效:
private Resource loadAsResource(String filename) {
try {
Path file = root.resolve(filename);
Resource resource = new UrlResource(file.toUri());
int i=0;
while(!resource.exists() || !resource.isReadable()) {
Thread.sleep(100);
if (++i == 20) {
break;
}
}
return resource;
} catch (MalformedURLException e) {
throw new RuntimeException("Error: " + e.getMessage());
} catch (InterruptedException e) {
throw new RuntimeException("Could not read the file!");
}
}循环会在2秒后中断,这没什么大不了的。
https://stackoverflow.com/questions/68599128
复制相似问题