版权声明:本文为博主原创文章,带上地址可以随意转载。 https://blog.csdn.net/haiyang4988/article/details/82917025
服务端使用的spring boot,手机端使用的混合开发mui框架和H5+
废话不多说,直接上代码
服务端:
@RequestMapping(value = "/viewFile")
@SystemControllerLog(description = "文件预览")
public void pdfStreamHandler(@RequestParam Map<String, Object> params, HttpServletRequest request) {
InputStream in = null;
try {
//本项目文件
// String filePath = "static/";
// String fileName = "test.docx";
// Resource resource = new ClassPathResource(filePath+fileName);
// File file = resource.getFile();
// in = new FileInputStream(file);
//本地文件
// String filePath = "d:/";
// String fileName = "test.docx";
// in = new FileInputStream(new File(filePath+fileName));//本地文件
//网络文件
String filePath = "https://www.baidu.com/img/";
String fileName = "xinshouye_728e7789595ab05362ac012e4bab23db.png";
URL url = new URL(filePath+fileName);
URLConnection conn = url.openConnection();
InputStream inStream = conn.getInputStream();
in = inStream;
// 重置response对象中的缓冲区,该方法可以不写,但是你要保证response缓冲区没有其他数据,否则导出可能会出现问题,
response.reset();
response.setContentType("application/octet-stream");
// 直接下载时加attachment,预览时候不加
// response.addHeader("Content-Disposition", "attachment; filename=\""+fileName+"\"");
response.addHeader("Content-Disposition", "filename=\""+fileName+"\"");
// response.addHeader("Content-Disposition",
// "filename=\"" + GeneralUtil.getFilename(request,
// file.getFileName()) + "\"");
byte[] buffer = new byte[1024];
int length;
while ((length = in.read(buffer)) > 0) {
response.getOutputStream().write(buffer, 0, length);
}
} catch (Exception e) {
// logger.error("下载文件出错", e);
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
}
}
}
}
前端代码:
mui('body').on('tap','#doc',function(){
openRemoteFile("http://192.168.10.35:8080/doc/viewFile");
});
function openRemoteFile(url) {
var wait = plus.nativeUI.showWaiting("正在打开文件...");
var dtask = plus.downloader.createDownload(url, {
method: "GET"
}, function(d, status) {
if(status == 200) {
plus.runtime.openFile(d.filename, {}, function(e) {
wait.close();
mui.alert("无法打开此文件:" + e.emssage, "我的软件");
});
wait.close();
} else {
wait.close();
mui.alert("文件打开失败: " + status, "我的软件");
}
});
dtask.start();
}