Android端通过NanoHTTPD服务下载Excel文件后无法正常打开问题求助
问题根因
- 服务端MIME类型配置错误:当前使用
NanoHTTPD.MIME_PLAINTEXT(纯文本类型)返回二进制XLSX文件,传输过程中会对二进制内容做文本编码转换,直接破坏文件结构。 - 前端响应处理逻辑错误:AJAX默认会将响应内容按UTF-8编码转为字符串,二进制Excel内容在字符串转码过程中会出现不可逆的编码错乱,导致最终生成的Blob与原文件不一致。
修复方案
服务端修改
替换错误的MIME类型,同时添加下载响应头标识文件名:
File excelDirectory = new File(GenericContext.getContext().getFilesDir(), "logsFile"); File excelFile = new File(excelDirectory, "1.xlsx"); FileInputStream fis = new FileInputStream(excelFile); // 使用XLSX对应的正确MIME类型构造响应 Response response = newChunkedResponse(Response.Status.OK, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fis); // 添加下载头,指定默认文件名 response.addHeader("Content-Disposition", "attachment; filename=\"1.xlsx\""); return response;
前端修改
修改AJAX请求配置,指定responseType: 'blob'直接接收二进制响应,避免字符串转码损坏数据:
// 原生XHR请求示例 var xhr = new XMLHttpRequest(); xhr.open('GET', '你的下载接口地址', true); // 核心配置:指定响应类型为二进制blob xhr.responseType = 'blob'; xhr.onload = function() { if (this.status === 200) { // 直接使用接口返回的blob对象,无需手动构造 var blob = this.response; var downloadObj = document.createElement('a'); var href = window.URL.createObjectURL(blob); downloadObj.href = href; downloadObj.download = '1.xlsx'; document.body.appendChild(downloadObj); downloadObj.click(); document.body.removeChild(downloadObj); window.URL.revokeObjectURL(href); } }; xhr.send();
如果使用jQuery发起AJAX,需要额外添加xhrFields配置:
$.ajax({ url: '你的下载接口地址', method: 'GET', xhrFields: { responseType: 'blob' }, success: function(blob) { // 后续下载逻辑和上面一致 } })
内容的提问来源于stack exchange,提问作者M.Minbashi
相关产品推荐
相关产品推荐

