3

I am attempting to upload a file from my Android app to the Flask server. The logcat on Android Studio shows I/uploadFile: HTTP Response is : OK: 200 but I am unable to see the uploaded file on the server.

Following is my flask code which I have referred to from http://flask.pocoo.org/docs/0.12/patterns/fileuploads/:

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

UPLOAD_FOLDER = '/Users/Vishwak/PycharmProjects/BraiNet/'
ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'}

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER


def allowed_file(filename):
    return '.' in filename and \
        filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS


@app.route('/', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        print request
        print request.values
        # check if the post request has the file part
        if 'file' not in request.files:
            # flash('No file part')
            return redirect(request.url)
        print(request.files['file'])
        file = request.files['file']
        # if user does not select file, browser also
        # submit a empty part without filename
        if file.filename == '':
            print(file)
            # flash('No selected file')
            return redirect(request.url)
        if file and allowed_file(file.filename):
            print(file)
            print(file.filename)
            filename = secure_filename(file.filename)
            # print filename
            print(app.config['UPLOAD_FOLDER'])
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            return redirect(url_for('upload_file',
                                filename=filename))
    return '''
    <!doctype html>
    <title>Upload new File</title>
    <h1>Upload new File</h1>
    <form method=post enctype=multipart/form-data>
    <p><input type=file name=file>
    <input type=submit value=Upload>
    </form>
    '''
if __name__ == '__main__':
    app.run()

This works as expected when I upload a file using the Web interface and I can view the file on the server.

The problem arises when I try to upload the file from the Android app. Here is the java code:

private class UploadTask extends AsyncTask { private Context context;

public UploadTask(Context context) {
    this.context = context;
}

@Override
protected String doInBackground(String... params) {
    String fileName =path;
    String fileName2=path.substring(path.lastIndexOf("/")+1);
    String fileName4 = fileName2.substring(0, fileName2.lastIndexOf("."));

    HttpURLConnection conn = null;
    DataOutputStream dos = null;
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";
    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024 * 1024;
    File sourceFile = new File(fileName);

    if (!sourceFile.isFile()) {

        Log.e("uploadFile", "Source File not exist :"
                + uri);

        runOnUiThread(new Runnable() {
            public void run() {
//                    messageText.setText("Source File not exist :"
//                            +uploadFilePath + "" + uploadFileName);
            }
        });
    } else {
        try {

            // open a URL connection to the Servlet
            FileInputStream fileInputStream = new FileInputStream(sourceFile);
//                    System.out.println(Array.toString(fileInputStream));
            URL url = new URL(upLoadServerUri);

            // Open a HTTP  connection to  the URL
            conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true); // Allow Inputs
            conn.setDoOutput(true); // Allow Outputs
            conn.setUseCaches(false); // Dont use a Cached Copy
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("ENCTYPE", "multipart/form-data");
            conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
            conn.setRequestProperty("uploaded_file", fileName);

            dos = new DataOutputStream(conn.getOutputStream());

            dos.writeBytes(twoHyphens + boundary + lineEnd);
            dos.writeBytes("Content-Disposition: form-data; uploaded_file=uploaded_file ;filename=" + fileName + lineEnd);
            // dos.writeBytes("Content-Disposition: form-data; name=" + fileName4 + ";filename=" + fileName2 + "" + lineEnd);
            dos.writeBytes(lineEnd);

            // create a buffer of  maximum size
            bytesAvailable = fileInputStream.available();

            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            buffer = new byte[bufferSize];

            // read file and write it into form...
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);

            while (bytesRead > 0) {

                dos.write(buffer, 0, bufferSize);
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);

            }

            // send multipart form data necesssary after file data...
            dos.writeBytes(lineEnd);
            dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

            // Responses from the server (code and message)
            serverResponseCode = conn.getResponseCode();
            String serverResponseMessage = conn.getResponseMessage();

            Log.i("uploadFile", "HTTP Response is : "
                    + serverResponseMessage + ": " + serverResponseCode);

            if (serverResponseCode == 200) {

                runOnUiThread(new Runnable() {
                    public void run() {

                        Toast.makeText(MainActivity.this, "File Upload Complete.",
                                Toast.LENGTH_SHORT).show();
                    }
                });
            }

            //close the streams //
            fileInputStream.close();
            dos.flush();
            dos.close();

        }
        catch (MalformedURLException ex) {

            ex.printStackTrace();

            runOnUiThread(new Runnable() {
                public void run() {
//                        messageText.setText("MalformedURLException Exception : check script url.");
                    Toast.makeText(MainActivity.this, "MalformedURLException",
                            Toast.LENGTH_SHORT).show();
                }
            });

            Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
        }
        catch (Exception e) {

            e.printStackTrace();

            runOnUiThread(new Runnable() {
                public void run() {
//                        messageText.setText("Got Exception : see logcat ");
                    Toast.makeText(MainActivity.this, "Got Exception : see logcat ",
                            Toast.LENGTH_SHORT).show();
                }
            });
            Log.e("Upload Exception", "Exception:" + e.getMessage(), e);
        }
    }
    return null;
} // End else block

I am a novice at Java and I don't really understand where I am going wrong in my Android code and what I will have to change to make this work.

Any feedback on changing the Flask or Android code will be greatly appreciated.

Vishwak
  • 323
  • 3
  • 11
  • 1
    This is a bit late. but for those looking for an answer, have a look here: https://stackoverflow.com/questions/11766878/sending-files-using-post-with-httpurlconnection – Cryptoharf84 Feb 27 '20 at 18:23

0 Answers0