2013-08-07 113 views
0

你好,你能幫我這個嗎?我目前正在製作一個應用程序,可以將多個文件上傳到Web API,目前我可以上傳單個文件,但是當我試圖上傳多個文件時,只有第一個文件成功上傳並且沒有損壞,儘管其他文件(文件名)仍然可以看到該網站,但已損壞。我有一個奇怪的懷疑,我的代碼下面(特別是循環)給我的應用程序不正確的輸出,但我無法弄清楚。預先感謝任何能夠幫助我的人。上傳多個圖像到web API

protected Boolean doInBackground(String... arg0) 
{ 

    try 
     { 

      JSONObject jObjectFileUpload = new JSONObject(); 

      FileBody localFileBody; 
      MultipartEntity localMultipartEntity; 

      HttpParams httpParameters   = new BasicHttpParams(); 
      HttpConnectionParams.setConnectionTimeout(httpParameters, 15000); 
      HttpConnectionParams.setSoTimeout(httpParameters, 15000); 
      HttpPost httpPost     = new HttpPost("http://sampleserversvr4.guru.com:0727/api/fileupload"); 
      HttpClient httpclient    = new DefaultHttpClient(httpParameters); 
      httpPost.addHeader("Authorization","Basic "+ Base64.encodeToString((_username + ":" + _password).getBytes(),Base64.NO_WRAP)); 

      for (int i = 0; i < Constants.ARRAYLIST_URI.size(); i++) 
      { 
       uri = Constants.ARRAYLIST_URI.get(i); 
       file = new File(uri); 
       mimetype = Constants.getMimeType(uri); 
       filename = file.getName(); 
       localFileBody = new FileBody(file, mimetype); 
       localMultipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); 
       try { 
        localMultipartEntity.addPart("name", new StringBody(filename)); 
       } catch (UnsupportedEncodingException e) { 
        e.printStackTrace(); 
       } 
       try { 
        localMultipartEntity.addPart("chunk", new StringBody("1")); 
       } catch (UnsupportedEncodingException e) { 
        e.printStackTrace(); 
       } 

       localMultipartEntity.addPart("file data", localFileBody); 
       httpPost.setEntity(localMultipartEntity); 
       HttpResponse localHttpResponse = httpclient.execute(httpPost); 

       Log.i("response upload", localHttpResponse.toString()); 
       Log.i("Multipart Entity", localMultipartEntity.toString()); 
      } 




     } catch (ClientProtocolException e) 
      { 
       e.printStackTrace(); 
       Log.e("fileUpload", "ClientProtocolException in callWebService(). " + e.getMessage()); 
      } catch (IOException e) 
       { 
        e.printStackTrace(); 
        Log.e("fileUpload","IOException in callWebService(). " + e.getMessage()); 
       } 

    return true; 

} 

回答

0

當您創建HttpPost的實例時,您可能只有一個職位更改。因此,在您的for循環中,您將設置新的HttpPost和HttpClient。在for循環中創建HttpPost和HttpClient實例,然後重試。