springboot访问到reource文件下的资源,访问不到资源处理方法:
class path resource [] cannot be resolved to UR
ClassPathResource 可以直接访问到资源文件夹reource,但是为什么提示找不到资源呢,首先我先放出我得代码
示例代码
@PostMapping("/downloadExcel")
public ResponseEntity<byte[]> downloadExcel() throws IOException {
// 读取 Excel 文件为 Resource 对象
Resource resource = new ClassPathResource("excel/");
// 读取文件字节流
byte[] fileBytes = Files.readAllBytes(resource.getFile().toPath());
// 设置响应头
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=");
return ResponseEntity.ok()
.headers(headers)
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.body(fileBytes);
}
访问不到资源处理方法:
报错:class path resource [] cannot be resolved to UR
于是我检查target文件是否存在编译后得文件:发现果然没有我放得excel
如果你的 Excel 文件没有出现在编译后的 target 文件夹中,可能是因为 Maven 或 Gradle 的默认配置导致资源文件没有正确地复制到编译目录下。
在 Maven 项目中,src/main/resources 目录下的文件会默认被复制到编译后的 target/classes 目录下。而在 Gradle 项目中,默认的资源目录为 src/main/resources,也会被复制到编译后的目录中。
确保按照以下步骤检查和解决问题:
确认 Excel 文件位于 src/main/resources 目录下的 excel 文件夹中,并且文件名和路径的大小写匹配。
检查 Maven 或 Gradle 配置文件,确保资源文件被正确地包含在构建过程中。在 Maven 项目中,你可以检查 文件中的标签
<resources>
对于 Maven 项目,确保以下类似的配置存在:
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*</include>
</includes>
</resource>
</resources>
</build>
执行 Maven 构建命令,重新编译项目。在构建成功后,检查编译后的目录(target/classes)中是否存在 Excel 文件。
后续发现打成jar包无法访问excel文件
需要将文件转成输出流进行返回
改了一下代码
InputStream inputStream = getClass().getResourceAsStream("/excel/代发一次性待遇导入模板.xlsx");
byte[] fileBytes;
try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
// Read the input stream and write it to the output stream
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
fileBytes = outputStream.toByteArray();
}
// Set the response headers
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=代发一次性待遇导入模板.xlsx");
return ResponseEntity.ok()
.headers(headers)
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.body(fileBytes);