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();
   }
5
  • This is the row content of the posted data. There's no additional text. You must first convert the data to a cleaner format. Commented Nov 10, 2014 at 5:31
  • The data is binary zip or jpg or other formats, i just want to save the content without the http content descriptions. Commented Nov 10, 2014 at 5: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. Commented Nov 10, 2014 at 6: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? Commented Nov 10, 2014 at 6:51
  • 1
    Possible duplicate of File Upload Using HttpHandler Commented Nov 25, 2015 at 13:55

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.