Download Excel file from Nano httpd web server

126 Views Asked by At

I have an excel file in my Android phone whereby i want to download this file by Nano Httpd web server,I am reading excel content and return as a Nanohttpd's response :

File excelDirectory = new File(GenericContext.getContext().getFilesDir(), "logsFile");
FileInputStream fis = new FileInputStream(excelDirectory + File.separator + "1.xlsx");
return newChunkedResponse(Response.Status.OK, NanoHTTPD.MIME_PLAINTEXT, fis);

and in web server(in ajax success block) i have written this code to download:

var blob = new Blob([result],{type: 'application/vnd.openxmlformats-  officedocument.spreadsheetml.sheet;charset=utf-8'});
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);

when i use console.log() to print the result, the content of excel is not correct.I should mention this file can not be opened by any excel tools.

1

There are 1 best solutions below

0
Kang On

Is mime type correct? (newChunkedResponse api second parameter)
Your file extension is '.xlsx' but you returned MIME_PLAINTEXT mime type.

I am not sure but I think mime type should be changed. Seems returning NanoHTTPD.MIME_PLAINTEXT is cause.
You can get mime type like this.

String type = "";
String extension = MimeTypeMap.getFileExtensionFromUrl(rootDir.getName());
if (extension != null) {
    type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
}

And try downloading with the same mime type on the client side.