2017-01-13 103 views
1

我想從我的Android應用上傳一個位圖到我的NodeJS服務器。我的位圖有一些數據(Json)必須在相同的(POST)消息中上傳。我看到它可能通過:Android:用json上傳圖片

  • 多部分表單數據。
  • 應用端的圖像編碼(將圖像轉換爲字符串)以及服務器端的解碼。

有沒有更好的方法?有沒有人熟悉一個很好的指導來執行這種上傳?

+0

圖像編碼可能會產生一個非常大的字符串,它會比原始圖像更大,在我看來,多部分表單數據是要走的路。 –

+0

@ Boldijar Paul我應該使用MultipartEntity對象還是常規的DataOutputStream? –

+0

你可以自己編碼。或者在本網站上找到現成的代碼。或者使用一個庫。如果你想使用json(就像你在主題中所說的那樣),你不能使用multipart,而必須對圖像數據base64進行編碼,這會增加30%的大小。 – greenapps

回答

0

感謝您的回覆。這是我爲Multipart上傳所寫的代碼(合併了幾個答案)。如果代碼有問題,請告訴我。

// create a url object 
    URL url = new URL(mGlobalUrl + localUrl); 
    HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 

    conn.setDoInput(true); 
    conn.setDoOutput(true); 
    conn.setUseCaches(false); 

    conn.setRequestMethod("POST"); 
    conn.setRequestProperty("Connection", "Keep-Alive"); 
    conn.setRequestProperty("User-Agent", "Android Multipart HTTP Client 1.0"); 
    conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); 

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

    //--start-- 
    //Deal with data 
    outputStream.writeBytes(twoHyphens + boundary + lineEnd);   //key 
    outputStream.writeBytes("Content-Disposition: form-data; name=\"key\"" + lineEnd); 
    outputStream.writeBytes(lineEnd); 
    outputStream.writeBytes(value); //value 
    outputStream.writeBytes(lineEnd); 

    //Deal with image 
    outputStream.writeBytes(twoHyphens + boundary + lineEnd);   //key 
    outputStream.writeBytes("Content-Disposition: form-data; name=\"uploadFile\"; filename=\"" + "image1" + "\"" + lineEnd); 
    //outputStream.writeBytes("Content-Type: " + fileMimeType + lineEnd); 
    outputStream.writeBytes("Content-Transfer-Encoding: binary" + lineEnd); 
    outputStream.writeBytes(lineEnd); 

    FileInputStream fileInputStream = new FileInputStream(imagePath); //value 
    int bytesAvailable = fileInputStream.available(); 
    int bufferSize = Math.min(bytesAvailable, maxBufferSize); 
    byte[] buffer = new byte[bufferSize]; 

    int bytesRead = fileInputStream.read(buffer, 0, bufferSize); 
    while (bytesRead > 0) { 
     outputStream.write(buffer, 0, bufferSize); 
     bytesAvailable = fileInputStream.available(); 
     bufferSize = Math.min(bytesAvailable, maxBufferSize); 
     bytesRead = fileInputStream.read(buffer, 0, bufferSize); 
    } 
    outputStream.writeBytes(lineEnd); 

    outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); 
    //--end-- 

    // receive response as inputStream 
    int responseCode = conn.getResponseCode(); 
    if (responseCode == HttpsURLConnection.HTTP_OK) { 
     inputStream = new BufferedInputStream(conn.getInputStream()); 

     // convert input stream to string 
     if (inputStream != null) { 
      result = convertInputStreamToString(inputStream); 
     } 
     else { 

      Log.d(TAG, "sendPostRequest: Error - input stream is null"); 
      result = "{}"; 
     } 
    } 

    fileInputStream.close(); 
    outputStream.flush(); 
    outputStream.close(); 
    conn.disconnect(); 

對於服務器端(的NodeJS)我用強大的模塊(我不知道是否已經過時或不),你可以找到關於此模式here一些更多的信息。

upload_image = function(req, res, next) { 

//create new incoming form object 
var form = new formidable.IncomingForm(); 

//parse the request using formidable module 
form.parse(req, function(error, fields, files) { 

    //check if error occurred during the parse 
    if (error) { 
     ...some code 
     return; 
    } 

    //save the data received in the request 
    ...some code 
}); 

//check for errors during the transmission 
form.on('error', function(err) { 
    ...some code 
    return; 
}); 

//check for the end of the transmission 
form.on('end', function(error, fields, files) { 
    //save the temporary location of the uploaded image file 
    var temp_path = this.openedFiles[0].path; 

    //save the file name of the uploaded image file 
    var file_name = this.openedFiles[0].name; 

    //save the file 
    ...some code 

    //update the database 
    ...some code 
}; 
+0

嘿@MaxZ請問你如何處理圖像的代碼?可以很好地知道你使用了哪個庫,因爲大量的庫存在,但其中大多數都有不推薦使用的方法並與android本機衝突。 – nsgulliver

+0

@nsgulliver完成。 –