Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7502165
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 29, 20262026-05-29T20:46:21+00:00 2026-05-29T20:46:21+00:00

Following is the java code on android side. It uploads file from the smartphone

  • 0

Following is the java code on android side. It uploads file from the smartphone to a Flask server(a web server built on Flask framework). On Flask server side, how can I receive the file correctly? I worked on it for several days, but couldn’t figure out how to do it correctly. The request.headers gave me the correct parsed header data, but request.data or request.stream couldn’t give me the expected data. Any help will be appreciated!

public void doUpload(String filename)
{
    HttpURLConnection conn = null;
    DataOutputStream os = null;
    DataInputStream inputStream = null;

    String urlServer = "http://216.96.***.***:8000/upload";

    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary =  "*****";
    int bytesRead, bytesAvailable, bufferSize, bytesUploaded = 0;
    byte[] buffer;
    int maxBufferSize = 2*1024*1024;

    String uploadname = filename.substring(23);

    try
    {
        FileInputStream fis = new FileInputStream(new File(filename) );

        URL url = new URL(urlServer);
        conn = (HttpURLConnection) url.openConnection();
        conn.setChunkedStreamingMode(maxBufferSize);

        // POST settings.
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Content-Type", "multipart/form-data; boundary="+boundary);
        conn.addRequestProperty("username", Username);
        conn.addRequestProperty("password", Password);
        conn.connect();

        os = new DataOutputStream(conn.getOutputStream());
        os.writeBytes(twoHyphens + boundary + lineEnd);
        os.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + uploadname +"\"" + lineEnd);
        os.writeBytes(lineEnd);

        bytesAvailable = fis.available();
        System.out.println("available: " + String.valueOf(bytesAvailable));
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        buffer = new byte[bufferSize];

        bytesRead = fis.read(buffer, 0, bufferSize);
        bytesUploaded += bytesRead;
        while (bytesRead > 0)
        {
            os.write(buffer, 0, bufferSize);
            bytesAvailable = fis.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            buffer = new byte[bufferSize];
            bytesRead = fis.read(buffer, 0, bufferSize);
            bytesUploaded += bytesRead;
        }
        System.out.println("uploaded: "+String.valueOf(bytesUploaded));
        os.writeBytes(lineEnd);
        os.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

        // Responses from the server (code and message)
        conn.setConnectTimeout(2000); // allow 2 seconds timeout.
        int rcode = conn.getResponseCode();
        if (rcode == 200) Toast.makeText(getApplicationContext(), "Success!!", Toast.LENGTH_LONG).show();
        else Toast.makeText(getApplicationContext(), "Failed!!", Toast.LENGTH_LONG).show();
        fis.close();
        os.flush();
        os.close();
        Toast.makeText(getApplicationContext(), "Record Uploaded!", Toast.LENGTH_LONG).show();
    }
    catch (Exception ex)
    {
        //ex.printStackTrace();
        //return false;
    }
}
}

My server side code:

@app.route('/cell_upload', methods=['GET', 'POST'])
def cell_upload():
    """Uploads a new file for the user from cellphone."""
    if request.method == 'POST':
        int_message = 1
        print "Data uploading"
        print request.headers
        logdata = request.stream.readline()
        while(logdata):
            print "uploading"
            print logdata
            logdata = request.stream.readline()
        print "Uploading done"
        return Response(str(int_message), mimetype='text/plain')
    int_message = 0
    return Response(str(int_message), mimetype='text/plain')
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-29T20:46:23+00:00Added an answer on May 29, 2026 at 8:46 pm

    I’m not sure what your exact problem is, but I was able to get things to work by using the java (client) code taken from this SO question and by slightly modifying your flask code as follows:

    if request.method == 'POST':
            int_message = 1
            print "Data uploading"
            print request.headers
            for v in request.values:
              print v
            #logdata = request.stream.readline()
            #while(logdata):
            #    print "uploading"
            #    print logdata
            #    logdata = request.stream.readline()
            print "Uploading done"
            return Response(str(int_message), mimetype='text/plain')
    

    I wouldn’t consider this “the final answer”, but hopefully it will give you a shove in the right direciton.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am trying to use org.apache.commons.collections.CollectionUtils in android with following code import java.util.ArrayList; import
Given the following Java code for generating a binary file: DataOutputStream out = new
I've got the following java code, which is giving the error below: import java.io.File;
I used following code in java class of android. Everything works except it wont
I am trying to stream an MP3-file with the following code in Android 2.3.3:
The following Java code is throwing a compiler error: if ( checkGameTitle(currGame) ) ArrayList<String>
The following java code prints Hello World on my co-worker's computer: public void testJDBC()
When running the following Java code, I get very accurate and consistent results in
If I have the following Java code: int[][] readAPuzzle() { Scanner input = new
Consider the following Java code: volatile boolean v1 = false; volatile boolean v2 =

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.