使用java下载文件(在下载的文件中显示无效字符)

时间:2017-04-25 06:34:57

标签: java file file-io download fileinputstream

我正在尝试使用java下载文件,文件正在下载但在文件中显示无效字符,如下所示。

图像也一样,显示无效图像。

一切都很好看,我错过了什么吗?或者任何人有比这更好的解决方案?

index.jsp

<body>  
     Click on the link to download:
     <a href="download.jsp">Download Link</a>
</body>

download.jsp

<%
try {
    String filename = "C:/slcmimages/StudentDetails.xls"; // jpg, png, doc etc
    response.setContentType("APPLICATION/OCTET-STREAM");
    response.setHeader("Content-Disposition", "attachment; filename=" + filename);

    // transfer the file byte-by-byte to the response object
    File fileToDownload = new File(filename);
    response.setContentLength((int) fileToDownload.length());
    FileInputStream fileInputStream = new FileInputStream(fileToDownload);
    int i = 0;
    while ((i = fileInputStream.read()) != -1) {
        out.write(i);
    }
    fileInputStream.close();
} catch (Exception e) {
    e.printStackTrace();
}
%>

实际档案

enter image description here

下载后的文件:

enter image description here

0 个答案:

没有答案