5

I've successfully achieved file transfer over local network using NanoHttpd. However, I'm unable to send the file name in NanoHttpd Response. The received files have a default name like this: localhost_8080. I tried to attach file name in response header using Content-disposition, but my file transfer failed all together. What am I doing wrong? Here is my implementation:

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;
    }
}

Thanks for your help!

Daniel Nugent
  • 43,104
  • 15
  • 109
  • 137
Vinit Shandilya
  • 1,643
  • 5
  • 24
  • 44

1 Answers1

9

You need to specify the response, the MIME type, and the stream of bytes to be sent. After that you just add a header with the file name of the file since its a http method. Here is a sample code that solves the problem

@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;

}
Daniel Nugent
  • 43,104
  • 15
  • 109
  • 137
T-D
  • 373
  • 8
  • 21
  • 2
    Header name is `Content-Disposition`, value is `attachment; filename="+fileName+"`. I edited your answer accordingly. – Matthieu Jun 09 '16 at 12:49