3

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')
kevinlu
  • 1,811
  • 2
  • 14
  • 19
  • does `request.data` or `request.stream` give you incorrect data (if so, what is it?) or no data? Any exceptions on either the client or server side? – gdw2 Feb 14 '12 at 20:30
  • print request.data gave me nothing. print request.stream gave me something like the address of a stream object. But when I was trying to print request.stream.readline(), I got nothing again. Neither client side or server side complained about any errors or exceptions. I guess there is something wrong with my server side code. I may not receive the package correctly. But when I printed out request.headers, everything looked good. – kevinlu Feb 14 '12 at 20:56

2 Answers2

1

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.

Community
  • 1
  • 1
gdw2
  • 7,558
  • 4
  • 46
  • 49
0

Working Code to upload any file to flask server running locally. you can access the server either using host o.o.o.o and any device on the same neterwork can assess using your LAN IP address/Network IP Address

from flask import Flask, render_template, request, url_for, flash 
import os
from werkzeug.utils import secure_filename, redirect

UPLOAD_FOLDER = '/Users/arpansaini/IdeaProjects/SmartHomeGestureControlAppFlaskServer/uploads/'
app = Flask(__name__)

app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER


@app.route('/upload')
def upload_file():
    return render_template('upload.html')


@app.route('/uploader', methods=['GET', 'POST'])
def handle_request():
    if request.method == 'POST':
        if 'file' not in request.files:
            flash('No file part')
            return redirect(request.url)
        f = request.files['file']
        if f:
            f.save(secure_filename(f.filename))
            f.save(os.path.join(app.config['UPLOAD_FOLDER'], f.filename))
            return "Success"
    else:
        return "Welcome to server"


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)
Arpan Saini
  • 4,623
  • 1
  • 42
  • 50