springboot訪問(wèn)到reource文件下的資源,訪問(wèn)不到資源處理方法:
class path resource [template.xlsx] cannot be resolved to UR
ClassPathResource 可以直接訪問(wèn)到資源文件夾reource,但是為什么提示找不到資源呢,首先我先放出我得代碼
示例代碼
@PostMapping("/downloadExcel")
public ResponseEntity<byte[]> downloadExcel() throws IOException {
// 讀取 Excel 文件為 Resource 對(duì)象
Resource resource = new ClassPathResource("excel/template.xlsx");
// 讀取文件字節(jié)流
byte[] fileBytes = Files.readAllBytes(resource.getFile().toPath());
// 設(shè)置響應(yīng)頭
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=template.xlsx");
return ResponseEntity.ok()
.headers(headers)
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.body(fileBytes);
}
訪問(wèn)不到資源處理方法:
報(bào)錯(cuò):class path resource [template.xlsx] cannot be resolved to UR
于是我檢查target文件是否存在編譯后得文件:發(fā)現(xiàn)果然沒(méi)有我放得excel
如果你的 Excel 文件沒(méi)有出現(xiàn)在編譯后的 target 文件夾中,可能是因?yàn)?Maven 或 Gradle 的默認(rèn)配置導(dǎo)致資源文件沒(méi)有正確地復(fù)制到編譯目錄下。
在 Maven 項(xiàng)目中,src/main/resources 目錄下的文件會(huì)默認(rèn)被復(fù)制到編譯后的 target/classes 目錄下。而在 Gradle 項(xiàng)目中,默認(rèn)的資源目錄為 src/main/resources,也會(huì)被復(fù)制到編譯后的目錄中。
確保按照以下步驟檢查和解決問(wèn)題:
確認(rèn) Excel 文件位于 src/main/resources 目錄下的 excel 文件夾中,并且文件名和路徑的大小寫(xiě)匹配。
檢查 Maven 或 Gradle 配置文件,確保資源文件被正確地包含在構(gòu)建過(guò)程中。在 Maven 項(xiàng)目中,你可以檢查 pom.xml 文件中的標(biāo)簽
<resources>
對(duì)于 Maven 項(xiàng)目,確保以下類(lèi)似的配置存在:
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*</include>
</includes>
</resource>
</resources>
</build>
執(zhí)行 Maven 構(gòu)建命令,重新編譯項(xiàng)目。在構(gòu)建成功后,檢查編譯后的目錄(target/classes)中是否存在 Excel 文件。文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-705944.html
后續(xù)發(fā)現(xiàn)打成jar包無(wú)法訪問(wèn)excel文件
需要將文件轉(zhuǎn)成輸出流進(jìn)行返回
改了一下代碼文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-705944.html
InputStream inputStream = getClass().getResourceAsStream("/excel/代發(fā)一次性待遇導(dǎo)入模板.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=代發(fā)一次性待遇導(dǎo)入模板.xlsx");
return ResponseEntity.ok()
.headers(headers)
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.body(fileBytes);
到了這里,關(guān)于springboot如何訪問(wèn)resource目錄下的文件,訪問(wèn)不到資源處理方法:class path resource [template.xlsx] cannot be resolved to UR的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!