0

I am new to AOSP. NanoHttpd is implemented for web part of the project. I want to upload file from a Javascript page which is hosted on the Android device and then I want to get this uploaded file to the Android Device's file system. I am facing some issues:

    private Response handlePostMethod(IHTTPSession session) {
    final Map<String, String> params = new HashMap<>();
    try {
        session.parseBody(params);
    } catch (IOException e) {
        return new Response(Response.Status.INTERNAL_ERROR, MIME_PLAINTEXT, e.getMessage());
    } catch (ResponseException e) {
        return new Response(e.getStatus(), MIME_PLAINTEXT, e.getMessage());
    }


    if (params.containsKey("postData") ||  session.getUri().equalsIgnoreCase("/upload")) {
        final String postData = params.get("postData");
        Logd("data " + postData);

        switch (session.getUri()) {
            ...
            case "/upload":
            Log.d(TAG,"upload case entered");
                try {

                    session.parseBody(params);
                    for (String key : params.keySet()) {
                        File file1 = new File(params.get(key));
                        if(file1==null){
                            Log.d(TAG,"inside for file1 is empty");
                        }

                        byte[] fileData = Files.readAllBytes(file1.toPath());

                        ByteArrayInputStream inputStream = new ByteArrayInputStream(fileData);
                        String fileDownloadLocation = Environment.getExternalStorageDirectory() + "/Download";
                        File newFile = new File(fileDownloadLocation);
                        return responseOk;
                        //  downloadFiles(newFile,session);

                    }
                } catch (Exception e) {
                    Logd("responseJsonError:" + e);
                    return responseJsonError;
                }
        }
    }

    return null;
}

and I am posting the file from javascript :

    apkInstallBtn.onclick = () => {
    // Get the file input element
    var fileInput = document.getElementById('fileInput');

    // Check if a file is selected
   

    // Create a URL for the file object
    var fileURL = URL.createObjectURL(file);
    fileURL = fileURL.replace("blob:","");
    
    
    // Log the URL of the file
    console.log('File URL:', fileURL);

    // Create a FormData object
    var formData = new FormData();
    formData.append('file', file);

    // Make a POST request to upload the file
    fetch('http://' + ip_address + '/upload', {
        method: 'POST',
        body: formData
    })
    .then(response => response.text())
    .then(data => console.log(data))
    .catch(error => console.error('Error:', error));
    


};

It gives this error:

User Error while uploading file: java.net.SocketTimeoutException: Read timed out on line session.parseBody(files);

How can I fix this?

I tried to set timeout value but It didn't work either.

session.setReadTimeout(timeoutInMillis);

It gave this error:

symbol: method setReadTimeout(int) location: variable session of type IHTTPSession

5
  • Sorry, dint understand. First you want to upload a file? And after that you want to download that file? For which action NanoHTTPD would be used. And where was that file before uploading. Commented Mar 21, 2024 at 10:12
  • Hello @blackapps, the method named handlePostMethod is in a class which extends NanoHTTPD (HTTPServer class). the user selects file in the html and the js code that I pasted posts the file to the HTTPServer class' serve method, then I am forwarding to the handlePostMethod. I want to download the file to the file system with the help of this class Commented Mar 21, 2024 at 11:02
  • You did not answer my questions. Do i understand right that all happens on the same device? If so then the user selects a file on the same device as you wanna download it? Well a nice exercise but why this scenario? The file was already on the device. You will get a copy. Ok. But why in this way? Commented Mar 21, 2024 at 11:13
  • The user opens the html page on their computer by typing the ip address of the device, then select a file in their computer in order to download this file to the Android device - in my case it's an android TV, so the file is not in the device before, it's on the user's pc Commented Mar 21, 2024 at 11:28
  • Ok. But that does not match I want to upload file from a Javascript page which is hosted on the Android device. Or does it? And was the html + javascript first loaded from nanohttpd into your pc browser? Very strange you did not tell the scenario right at the start of your post. You nowhere mentioned a pc or another device. Commented Mar 21, 2024 at 17:54

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.