Android post文件数组

Android post文件数组,android,httpconnection,Android,Httpconnection,我尝试将多个文件发布到web服务。但是,单文件post工作多文件post不工作 请随便帮我。如何实现该功能 我已经尝试了下面的代码。请检查一下 String fileName = sourceFileUri; String fileName1 = sourceFileUri1; // fileName1 - how to post to web service HttpURLConnection conn = null; DataOutputStream dos =

我尝试将多个文件发布到web服务。但是,单文件post工作多文件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;

    }

如果要传递一个FileBody数组,可以像这样尝试

     reqEntity.addPart("file[]["+i+"]", bab);
这将生成如下参数

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

希望它能澄清你的疑问。

我找到了解决办法。我用过如下的方法。它起作用了

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();  
     }
public void uploadFileNew(ArrayListIMAGEPTHLIST,ArrayListIMAGENAMELIST){
试一试{
HttpClient HttpClient=新的DefaultHttpClient();
HttpPost postRequest=新的HttpPost(upLoadServerUri);
由tearraybodbab;
ByteArrayOutputStream bos;
位图bm;
MultipartEntity reqEntity=新的MultipartEntity(HttpMultipartMode.BROWSER_兼容);
对于(int i=0;i
Hi Bharath感谢您的回复,但我需要的是,“conn.setRequestProperty(“uploaded_file[]”,fileName);”这里介绍如何添加多个文件。“文件名”是字符串。“setRequestProperty”不接受数组。如果可能,请在此处添加更多文件。