作者热门文章
- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
以下是android端的java代码。它将文件从智能手机上传到 Flask 服务器(基于 Flask 框架构建的 Web 服务器)。在 Flask 服务器端,如何正确接收文件?我为此工作了好几天,但无法弄清楚如何正确地做到这一点。 request.headers 为我提供了正确解析的 header 数据,但 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')
最佳答案
我不确定你的确切问题是什么,但我能够通过使用从 this SO question 中获取的 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')
我不认为这是“最终答案”,但希望它能帮助您朝着正确的方向前进。
关于android - 如何在 python Flask 服务器端接收从 android 客户端上传的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9283695/
我是一名优秀的程序员,十分优秀!