2013-08-07 46 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实例,然后重试。