首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何通过NanoHttpd响应发送文件名

如何通过NanoHttpd响应发送文件名
EN

Stack Overflow用户
提问于 2014-08-18 18:44:30
回答 1查看 3.8K关注 0票数 5

我已经成功地使用NanoHttpd实现了本地网络上的文件传输。但是,我无法在NanoHttpd响应中发送文件名。接收到的文件的默认名称类似于: localhost_8080。我尝试使用Content-disposition在响应头中附加文件名,但我的文件传输全部失败。我做错了什么?下面是我的实现:

代码语言:javascript
复制
private class WebServer extends NanoHTTPD {
    String MIME_TYPE;
    File file;

    public WebServer() {
        super(PORT);
    }

    @Override
    public Response serve(String uri, Method method,
            Map<String, String> header, Map<String, String> parameters,
            Map<String, String> files) {
        try {
            file=new File(fileToStream);
            fis = new FileInputStream(file);
            bis = new BufferedInputStream(fis);
            MIME_TYPE= URLConnection.guessContentTypeFromName(file.getName());
        } catch (IOException ioe) {
            Log.w("Httpd", ioe.toString());
        }
        NanoHTTPD.Response res=new NanoHTTPD.Response(Status.OK, MIME_TYPE, bis);
        res.addHeader("Content-Disposition: attachment; filename=", file.getName());
        return res;
    }
}

谢谢你的帮忙!

EN

回答 1

Stack Overflow用户

发布于 2015-01-31 18:51:06

您需要指定响应、MIME类型和要发送的字节流。在此之后,您只需添加一个标头,其中包含文件的文件名,因为它是一个http方法。以下是解决此问题的示例代码

代码语言:javascript
复制
@Override
public Response serve(String uri, Method method,
    Map<String, String> header, Map<String, String> parameters,
    Map<String, String> files) {

    FileInputStream fis = null;
    try {
        fis = new FileInputStream(fileName);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

    NanoHTTPD.Response res = new NanoHTTPD.Response(Response.Status.OK, "application/vnd.android.package-archive", fis);
    res.addHeader("Content-Disposition", "attachment; filename=\""+fileName+"\""); 
    return res;

}
票数 9
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25361457

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档