2014-01-09 34 views
1

我試圖將多個文件發佈到web服務。但是,單個文件發佈工作多個文件發佈不起作用。Android post文件陣列

請幫我一個。如何實現該功能。

我試過下面的代碼。請檢查一下。

String fileName = sourceFileUri; 
String fileName1 = sourceFileUri1;  
// fileName1 - how to post to web service 

HttpURLConnection conn = null; 
    DataOutputStream dos = null; 
    String lineEnd = "\r\n"; 
    String twoHyphens = "--"; 
    String boundary = "*****"; 
    int bytesRead, bytesAvailable, bufferSize; 
    byte[] buffer; 
    int maxBufferSize = 1 * 1024 * 1024; 
    File sourceFile = new File(sourceFileUri); 

    if (!sourceFile.isFile()) { 
     dialog.dismiss(); 
     Log.e("uploadFile", "Source File not exist :" + imagepath); 
     runOnUiThread(new Runnable() { 
      public void run() { 
       messageText.setText("Source File not exist :" + imagepath); 
      } 
     }); 
     return 0; 
    } else { 
     try { 
      // open a URL connection to the Servlet 
      URL url = new URL(upLoadServerUri); 

      // Open a HTTP connection to the URL 
      conn = (HttpURLConnection) url.openConnection(); 
      conn.setDoInput(true); // Allow Inputs 
      conn.setDoOutput(true); // Allow Outputs 
      conn.setUseCaches(false); // Don't use a Cached Copy 
      conn.setRequestMethod("POST"); 
      conn.setRequestProperty("Connection", "Keep-Alive"); 
      conn.setRequestProperty("ENCTYPE", "multipart/form-data"); 
      conn.setRequestProperty("Content-Type", 
        "multipart/form-data;boundary=" + boundary); 
      conn.setRequestProperty("uploaded_file[]", fileName); 

      dos = new DataOutputStream(conn.getOutputStream()); 
      dos.writeBytes(twoHyphens + boundary + lineEnd); 
      dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file[]\";filename=\"" 
        + fileName + "\"" + lineEnd); 
      dos.writeBytes(lineEnd); 

      FileInputStream fileInputStream = new FileInputStream(
        sourceFile); 
      // create a buffer of maximum size 
      bytesAvailable = fileInputStream.available(); 
      bufferSize = Math.min(bytesAvailable, maxBufferSize); 
      buffer = new byte[bufferSize]; 
      // read file and write it into form... 
      bytesRead = fileInputStream.read(buffer, 0, bufferSize); 
      while (bytesRead > 0) { 
       dos.write(buffer, 0, bufferSize); 
       bytesAvailable = fileInputStream.available(); 
       bufferSize = Math.min(bytesAvailable, maxBufferSize); 
       bytesRead = fileInputStream.read(buffer, 0, bufferSize); 

      } 
      // send multipart form data necesssary after file data... 
      dos.writeBytes(lineEnd); 
      dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); 

      // Responses from the server (code and message) 
      serverResponseCode = conn.getResponseCode(); 
      String serverResponseMessage = conn.getResponseMessage(); 

      Log.i("uploadFile", "HTTP Response is : " 
        + serverResponseMessage + ": " + serverResponseCode); 

      // close the streams // 
      fileInputStream.close(); 
      dos.flush(); 
      dos.close(); 

      InputStream is = conn.getInputStream(); 
      // retrieve the response from server 
      int ch; 

      StringBuffer b = new StringBuffer(); 
      while ((ch = is.read()) != -1) { 
       b.append((char) ch); 
      } 
      String s = b.toString(); 
      Log.i("Response", s); 

     } catch (MalformedURLException ex) { 

      dialog.dismiss(); 
      ex.printStackTrace(); 

      runOnUiThread(new Runnable() { 
       public void run() { 
        messageText 
          .setText("MalformedURLException Exception : check script url."); 
        Toast.makeText(MainActivity.this, 
          "MalformedURLException", Toast.LENGTH_SHORT) 
          .show(); 
       } 
      }); 

      Log.e("Upload file to server", "error: " + ex.getMessage(), ex); 
     } catch (Exception e) { 

      dialog.dismiss(); 
      e.printStackTrace(); 

      runOnUiThread(new Runnable() { 
       public void run() { 
        messageText.setText("Got Exception : see logcat "); 
        Toast.makeText(MainActivity.this, 
          "Got Exception : see logcat ", 
          Toast.LENGTH_SHORT).show(); 
       } 
      }); 
      Log.e("Upload file to server Exception", 
        "Exception : " + e.getMessage(), e); 
     } 
     dialog.dismiss(); 
     return serverResponseCode; 

    } 

回答

1

我得到了解決方案。我已經像下面一樣使用了。它正在工作。

public void uploadFileNew(ArrayList<String>IMAGEPTHLIST, ArrayList<String>IMAGENAMELIST) { 
     try { 
      HttpClient httpClient = new DefaultHttpClient(); 
      HttpPost postRequest = new HttpPost(upLoadServerUri); 
      ByteArrayBody bab; 
      ByteArrayOutputStream bos; 
      Bitmap bm; 
      MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); 
      for(int i = 0 ; i< IMAGEPTHLIST.size() ; i++) { 
       bm = BitmapFactory.decodeFile(IMAGEPTHLIST.get(i)); 
       bos = new ByteArrayOutputStream(); 
        bm.compress(CompressFormat.PNG, 100, bos); 
        byte[] data = bos.toByteArray(); 
       bab = new ByteArrayBody(data, IMAGENAMELIST.get(i));      
       reqEntity.addPart("file["+i+"]", bab); 
      } 
      reqEntity.addPart("cat_id", new StringBody("123")); 
      reqEntity.addPart("name", new StringBody("Android test")); 
      postRequest.setEntity(reqEntity);       
      HttpResponse response2 = httpClient.execute(postRequest);       
      BufferedReader reader = new BufferedReader(new InputStreamReader(response2.getEntity().getContent(), "UTF-8")); 

      String sResponse; 
      StringBuilder s = new StringBuilder(); 

      while ((sResponse = reader.readLine()) != null) { 
       s = s.append(sResponse); 
      } 
      System.out.println("===="+s.toString());   
     } catch (Exception e) { 
      e.printStackTrace(); 
     }   
     dialog.dismiss(); 
    } 
0

如果你想傳遞FileBody的數組,你可以嘗試喜歡,

 reqEntity.addPart("file[]["+i+"]", bab); 

 file=>[{"1" => "File" },{"2" => "File"}..] 

這將產生PARAMS希望它澄清你的疑問。

+0

嗨巴拉斯 感謝您的回覆,但我需要的是, 「conn.setRequestProperty(」 uploaded_file [] 「文件名);」這裏如何添加多個文件。 「文件名」是字符串。 「setRequestProperty」不接受數組。如果可能的話在這裏添加更多文件。 – Karthikeyan