首页 > 文章列表 > 移动端下载 Linux 根目录下的 PDF 文件,为何会显示未知文件?如何解决?

移动端下载 Linux 根目录下的 PDF 文件,为何会显示未知文件?如何解决?

123 2025-01-17

移动端下载 Linux 根目录下的 PDF 文件,为何会显示未知文件?如何解决?

在移动端下载 pdf 文件

问题描述

开发者希望在移动端下载存储在 linux 根目录下的 pdf 文件,但使用 servlet 返回文件流后,发现移动端点击下载后显示未知文件。

解决方法

编码文件路径

编码文件路径可以解决移动端无法正确识别路径的问题。在 servlet 中获取文件路径时,使用 encodeuricomponent(path) 对路径进行编码,然后再发送给客户端。

修改后的 pdfdownloadservlet 代码如下:

resp.setcontenttype("application/pdf;charset=utf-8");
resp.setheader("content-disposition", "attachment;filename=a.pdf");
string path = req.getparameter("path");
file w2 = new file(path);
logger.info("pdf path:" + w2.getpath());

fileinputstream fs;
try {
    fs = new fileinputstream(w2);
    bufferedinputstream bs = new bufferedinputstream(fs);
    printwriter outw = resp.getwriter();
    byte buffbytes[] = new byte[3072];
    int read = 0;
    while ((read = bs.read(buffbytes)) != -1) {
        string strtemp = new sun.misc.base64encoder().encode(arrays.copyofrange(buffbytes, 0, read));
        outw.print(strtemp);
    }
} catch (exception e) {
    logger.info("pdf出错");
    logger.error(e.getmessage(), e);
}

修改后的 javascript 代码如下:

$.ajax({
  type: "post",
  async: false,
  url: projectName + "/PdfDownloadServlet?path=" + encodeURIComponent(path),
  success: function (data) {
    var blob = new Blob([data], { type: "application/pdf;charset=utf-8" });
    saveAs(blob, "CF1002.pdf");
  },
  error: function (e) {
    console.log(e);
    alert(e);
  },
});

通过对文件路径进行编码,移动端即可正确识别路径,并下载 pdf 文件。

来源:1731074504