2012-02-14 4 views
2

以下はアンドロイド側のJavaコードです。スマートフォンからFlaskサーバー(Flaskフレームワーク上に構築されたWebサーバー)にファイルをアップロードします。 Flaskサーバー側では、ファイルを正しく受信するにはどうすればよいですか?私は数日間それに取り組んだが、それを正しく行う方法を理解できませんでした。 request.headersは私に正しい解析されたヘッダーデータを与えましたが、request.dataまたはrequest.streamは私に予想されるデータを与えることができませんでした。どんな助けもありがとう!python Flaskサーバー側でアンドロイドクライアントからアップロードされたファイルを受け取るにはどうすればいいですか

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

'request.data'または' request.stream'はあなたに間違ったデータを与えます(もしそうなら、それは何ですか?クライアント側とサーバー側の例外はありますか? – gdw2

+0

印刷request.dataは私に何も与えませんでした。 print request.streamはストリームオブジェクトのアドレスのようなものを私に与えました。しかし、私がrequest.stream.readline()を印刷しようとしていたとき、私はもう何も得ませんでした。クライアント側またはサーバー側は、エラーまたは例外について苦情を申し立てませんでした。私は、サーバーのサイドコードに何か問題があると思います。パッケージが正しく届かない場合があります。しかし、私がrequest.headersを印刷したとき、すべてが良く見えました。おかげさまで – kevinlu

答えて

1

を私はあなたの正確な問題が何であるかわからないんだけど、私は物事が(クライアント)は、Javaを使って仕事を得ることができたthis SO questionから取られたコードそして、次のように少しあなたのフラスコのコードを変更することによって:

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

私は、この「最終的な答え」を検討していないだろうが、うまくいけば、それはあなたの右direcitonで突き出すを与えるだろう。

+0

あなたはAndroidクライアントまたはデスクトップにJavaクライアントをインストールしましたか? – kevinlu

+0

あなたのトーストを除いて本当にアンドロイド特有のものは何もないように見えなかったので、デスクトップ。 – gdw2

関連する問題