美文网首页
nanohttp支持本地文件下载

nanohttp支持本地文件下载

作者: 钰大人 | 来源:发表于2024-01-16 15:27 被阅读0次
    • 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
    

    相关文章

      网友评论

          本文标题:nanohttp支持本地文件下载

          本文链接:https://www.haomeiwen.com/subject/wemkodtx.html