0

I am using sun.net.httpserver from JDK to create a simple http service for my device.

Now I want to save the post form data in to a file, but I always found there are additional content saved in the file.

root@android:/sdcard # cat a.jpg
-----------------------------288271103222787
Content-Disposition: form-data; name="myfile"; filename="a.jpg"
Content-Type: text/plain

CONTENT of the uploaded file

-----------------------------288271103222787--

how can I handle this to only save the "CONTENT of the uploaded file"?

My current code is:

private String handleWebSvcApi(HttpExchange exchange, String apiName) throws Exception {
        Log.d(TAG, "handleWebSvcApi : " + apiName);
        InputStream is = exchange.getRequestBody();
        String ret = mWebServiceApiHandler.handleWebServiceApi(apiName, is);
        return ret;
    }

public String handleWebServiceApi(String apiName, InputStream apiData) throws Exception {
        Object ret = null;
        if(apiName.equals("upload")) {
            String filePath = saveApiDataAsFile(apiData);
        }
}

private static String saveApiDataAsFile(InputStream is) throws IOException {
        BufferedInputStream in = new BufferedInputStream(is);
        File outPutFile = new File(Environment.getExternalStorageDirectory().getPath() + "/newfirmware.zip");
        OutputStream os = new FileOutputStream(outPutFile);
        int len = 0;
        byte buff[] = new byte[8192];
        while ((len = in.read(buff)) > 0) {
            os.write(buff, 0, len);
        }
        os.close();
        return outPutFile.getAbsolutePath();
   }
Robin
  • 10,052
  • 6
  • 31
  • 52
  • This is the row content of the posted data. There's no additional text. You must first convert the data to a cleaner format. – Lorenz Meyer Nov 10 '14 at 05:31
  • The data is binary zip or jpg or other formats, i just want to save the content without the http content descriptions. – Robin Nov 10 '14 at 05:34
  • The headers define the content. You have binary content, but depending on the browser it could also be base64 encoded. I don't know the http server component you are using, but it should expose methods to extract the post data. Use them instead of trying to read the raw post data. – Lorenz Meyer Nov 10 '14 at 06:47
  • I am using the sun.net.httpserver packages, extracted from JDK source code. It is pretty simple, and just provide methods to get request methods/header(as hash map)/body(as inputstream), and no other fancy APIs. So I think I might need to deal with the content by myself? – Robin Nov 10 '14 at 06:51
  • 1
    Possible duplicate of [File Upload Using HttpHandler](http://stackoverflow.com/questions/33732110/file-upload-using-httphandler) – Jan Nov 25 '15 at 13:55

0 Answers0