nanohttp支持本地文件下载

  • sdk接入
// app/build.gradle中接入sdk
implementation 'org.nanohttpd:nanohttpd:2.3.1'
  • nanohttp初始化
// 因为Android权限变更,此处使用应用外部私有存储
getExternalFilesDir("mgapkg")?.apply {
    nanoHttpClient = MyNanoHttp(8090, absolutePath)
}
  • 代码实现
class MyNanoHttp(port:Int, private var rootPath:String): NanoHTTPD(port) {

    private val fileNotExisted = """{"code": 1, "msg": "文件不存在"}"""
    private val invalidParams = """{"code": 2, "msg": "参数错误"}"""

    override fun serve(session: IHTTPSession?): Response {
        val uri = session?.uri
        return if (uri?.isNotEmpty() == true && uri.startsWith("/mgapkg/")) {
            try {
                val filePath = "$rootPath${uri.substring("/mgapkg".length)}"
                val file = File(filePath)

                if (file.exists()) {
                    newFixedLengthResponse(Response.Status.OK, getMimeTypeForFile(filePath), FileInputStream(filePath), file.length())
                } else {
                    newFixedLengthResponse(Response.Status.BAD_REQUEST, "application/json", fileNotExisted)
                }
            } catch (ex:Throwable) {
                newFixedLengthResponse(Response.Status.BAD_REQUEST, "application/json", fileNotExisted)
            }
        } else {
            newFixedLengthResponse(Response.Status.BAD_REQUEST, "application/json", invalidParams)
        }
    }
}
  • 下载地址
http://localip:8090/mgapkg/path1/path2/filename
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容