如何在python服务器端接收android客户端上传的文件
以下是android端的java代码。它将文件从智能手机上传到Flask服务器(基于Flask框架构建的web服务器)。在Flask服务器端,如何正确接收文件?我花了好几天的时间来做这件事,但都不知道如何正确地做。request.headers为我提供了正确的解析标头数据,但request.data或request.stream无法为我提供所需的数据。任何帮助都将不胜感激如何在python服务器端接收android客户端上传的文件,android,python,http,flask,Android,Python,Http,Flask,以下是android端的java代码。它将文件从智能手机上传到Flask服务器(基于Flask框架构建的web服务器)。在Flask服务器端,如何正确接收文件?我花了好几天的时间来做这件事,但都不知道如何正确地做。request.headers为我提供了正确的解析标头数据,但request.data或request.stream无法为我提供所需的数据。任何帮助都将不胜感激 public void doUpload(String filename) { HttpURLConnection
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')
我不确定您的确切问题是什么,但我能够通过使用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')
<>我不认为这是“最后的答案”,但希望它能在正确的方向上推你一把。 < p>将任何文件上传到本地运行的烧瓶服务器上。您可以使用主机o.o.o.o访问服务器,同一网络上的任何设备都可以使用LAN IP地址/网络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)
request.data
或request.stream
是否提供了不正确的数据(如果是,是什么?)或没有数据?客户端或服务器端有任何异常吗?print request.data没有给我任何信息。print request.stream给了我类似于流对象地址的信息。但当我试图打印request.stream.readline()时,我又一无所获。客户端和服务器端都没有抱怨任何错误或异常。我猜我的服务器端代码有问题。我可能没有正确收到包裹。但是当我打印出request.headers时,一切看起来都很好。谢谢。你是在android上还是在桌面上安装java客户端?桌面上,因为除了你的toast,它看起来没有任何真正的android特定的东西。