无法下载内容类型为text / html的文件

问题描述 投票:0回答:1

我有一个URL,当我直接在浏览器中尝试pdf文件时,它将下载pdf文件。但是,当我使用相同的URL使用Java代码中的FileInputStream通过FileInputStream下载文件时,出现了一个问题,例如URL的内容类型是text / html,而不是application / pdf,因此我们无法打开文件。

这里带来了困惑,当内容类型不是application / pdf时,我怎么能从浏览器下载文件?

代码有什么问题吗?

String pdfUrl = service.getPdfUrl(bpaRequest);
URL url1 = new URL(pdfUrl);
FileOutputStream fos1 = new FileOutputStream(fileName);
System.out.print("Connecting to " + url1.toString() + " ... ");
URLConnection urlConn = url1.openConnection();

// Checking whether the URL contains a PDF
if (!urlConn.getContentType().equalsIgnoreCase("application/pdf")) {
    throw new CustomException("INVALID_CONTENT", "contentType is not pdf");
} else {
    //some logic here to download
}
java pdf url content-type fileinputstream
1个回答
0
投票

您可以使用应用程序/八位字节流从浏览器下载文件。

也可以使用

Content-Type: application/pdf
Content-Disposition: attachment; filename="fileName.pdf"

Content-Disposition用于告诉您要保存文件而不是显示它。

© www.soinside.com 2019 - 2024. All rights reserved.