0

大家好,你能帮我解决这个问题吗?我目前正在制作一个可以将多个文件上传到 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;

}
4

1 回答 1

0

当您创建 HttpPost 的实例时,您可能只有一个帖子更改。因此,在您的 for 循环中,您将设置新的 HttpPost 和 HttpClient。在 for 循环中创建 HttpPost 和 HttpClient 实例,然后再试一次。

于 2013-08-07T06:38:29.090 回答