
在移动端下载 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 文件。
以上就是移动端下载 Linux 根目录下的 PDF 文件,为何会显示未知文件?如何解决?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号