如何在Python Flask服务器端接收来自Android客户端的文件上传

3 投票
2 回答
5600 浏览
提问于 2025-04-17 13:02

下面是安卓端的Java代码。它的作用是将文件从智能手机上传到一个Flask服务器(Flask框架搭建的网页服务器)。在Flask服务器那边,我该如何正确接收这个文件呢?我已经研究了好几天,但还是搞不清楚怎么做才对。请求的头信息(request.headers)给了我正确的解析头数据,但请求的数据(request.data)或请求流(request.stream)却无法给我想要的数据。任何帮助都非常感谢!

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;
    }
}
}

我的服务器端代码:

@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')

2 个回答

0

这是一个可以把任何文件上传到本地运行的Flask服务器的代码。你可以通过主机地址o.o.o.o来访问这个服务器,任何在同一个网络上的设备都可以通过你的局域网IP地址来访问。

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)
1

我不太清楚你具体遇到了什么问题,不过我通过使用从这个SO问题中得到的Java(客户端)代码,并稍微修改了你的Flask代码,成功让事情运转起来,代码如下:

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')

我不认为这就是“最终答案”,但希望它能给你一些正确的方向上的帮助。

撰写回答