使用Multipart / form-data的POST请求。内容类型用android(两张图片)

时间:2014-01-15 14:54:18

标签: php android post file-upload multipartform-data

嗨我从android上传两张图片到服务器,我只收到一张图片(第一张图片,但不是第二张图片)请问我的错误在哪里?!

我认为错误是在public int uploadFile(String sourceFileUri,String sourceFileUri2)中但是如何纠正他

感谢

这是我的布局

enter image description here

这是我上传的java代码

        buttonmodifprofil = (TextView)alertDialogView.findViewById(R.id.buttonmodifprofil);
                editphoto = (TextView)alertDialogView.findViewById(R.id.editphoto);
                editphoto.setText("Uploading file path :- '/sdcard/android_1.png'");
                uploadimage_btn = (ImageView) alertDialogView.findViewById(R.id.joindreimage);
                uploadimage_btn.setOnClickListener( new OnClickListener(){
                @Override
                public void onClick(View view) {
                // To open up a gallery browser
                  Intent intent = new Intent();
                  intent.setType("image/*");
                  intent.setAction(Intent.ACTION_GET_CONTENT);
                  startActivityForResult(Intent.createChooser(intent, "Select Picture"),1);
                }});

                editlogo = (TextView)alertDialogView.findViewById(R.id.editlogo);
                editlogo.setText("Uploading file path :- '/sdcard/android_1.png'");
                uploadlogo_btn = (ImageView) alertDialogView.findViewById(R.id.joindrelogo);
                uploadlogo_btn.setOnClickListener( new OnClickListener(){
                @Override
                public void onClick(View view) {
                // To open up a gallery browser
                  Intent intent = new Intent();
                  intent.setType("image/*");
                  intent.setAction(Intent.ACTION_GET_CONTENT);
                  startActivityForResult(Intent.createChooser(intent, "Select Picture"),0);
                }});

                buttonmodifprofil.setOnClickListener(new OnClickListener() {            
                    @Override
                    public void onClick(View v) {
                        dialog = ProgressDialog.show(MainClient.this, "", "Uploading file...", true);
                         new Thread(new Runnable() {
                                public void run() {
                                     runOnUiThread(new Runnable() {
                                            public void run() {
                                                editphoto.setText("uploading started.....");
                                            }
                                        });                      
                                 int response= uploadFile(editphoto.getText().toString(),editlogo.getText().toString());
                                 System.out.println("RES : " + response);                         
                                }
                              }).start();        
                        }
                });

这是上传2文件的代码

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK) {
        if (requestCode == 1) {
        // currImageURI is the global variable I’m using to hold the content:
            Uri currImageURI = data.getData();
            System.out.println("Current image Path is ----->" +                          getRealPathFromURI(currImageURI));
           // TextView editphoto_path = (TextView) findViewById(R.id.editphoto);
            editphoto.setText(getRealPathFromURI(currImageURI));
        }
        else{
              // currImageURI is the global variable I’m using to hold the content:
            Uri currImageURI = data.getData();
            System.out.println("Current image Path is ----->" +                          getRealPathFromURI(currImageURI));
           // TextView editphoto_path = (TextView) findViewById(R.id.editphoto);
            editlogo.setText(getRealPathFromURI(currImageURI));
        }
    }
}

//Convert the image URI to the direct file system path of the image file
public String getRealPathFromURI(Uri contentUri) {
    String [] proj={MediaStore.Images.Media.DATA};
    @SuppressWarnings("deprecation")
    android.database.Cursor cursor = managedQuery( contentUri,
    proj,     // Which columns to return
    null,     // WHERE clause; which rows to return (all rows)
    null,     // WHERE clause selection arguments (none)
    null);     // Order-by clause (ascending by name)
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
}

public int uploadFile(String sourceFileUri,String sourceFileUri2) {
      String upLoadServerUri = "http://www.citations-inoubliables.com/mappnet/upload.php";
      String fileName = sourceFileUri;
      String fileName2 = sourceFileUri2;
      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; 
      int bytesRead2, bytesAvailable2, bufferSize2;
      byte[] buffer2;
      int maxBufferSize2 = 1 * 1024 * 1024; 
      File sourceFile = new File(sourceFileUri); 
      File sourceFile2 = new File(sourceFileUri2); 
      if (!sourceFile.isFile()) {
       Log.e("uploadFile", "Source File Does not exist");
       return 0;
      }
      if (!sourceFile2.isFile()) {
          Log.e("uploadFile", "Source File Does not exist");
          return 0;
         }
          try { // open a URL connection to the Servlet
           FileInputStream fileInputStream = new FileInputStream(sourceFile);
           FileInputStream fileInputStream2 = new FileInputStream(sourceFile2);
           URL url = new URL(upLoadServerUri);
           conn = (HttpURLConnection) url.openConnection(); // Open a HTTP  connection to  the URL
           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("uploadImage", fileName); 
           conn.setRequestProperty("uploadLogo", fileName2); 
           dos = new DataOutputStream(conn.getOutputStream());

           dos.writeBytes(twoHyphens + boundary + lineEnd); 
           dos.writeBytes("Content-Disposition: form-data; name=\"uploadImage\";filename=\""+ fileName + "\"" + lineEnd);
           dos.writeBytes("Content-Disposition: form-data; name=\"uploadLogo\";filename=\""+ fileName2 + "\"" + lineEnd);

           dos.writeBytes(lineEnd);

           bytesAvailable = fileInputStream.available(); // create a buffer of  maximum size
           bytesAvailable2 = fileInputStream2.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);               
            }

           bufferSize2 = Math.min(bytesAvailable2, maxBufferSize2);
           buffer2 = new byte[bufferSize2];

           // read file and write it into form...
           bytesRead2 = fileInputStream2.read(buffer2, 0, bufferSize2);  


           while (bytesRead2 > 0) {
             dos.write(buffer2, 0, bufferSize2);
             bytesAvailable2 = fileInputStream2.available();
             bufferSize2 = Math.min(bytesAvailable2, maxBufferSize2);
             bytesRead2 = fileInputStream2.read(buffer2, 0, bufferSize2);               
            }

           // 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);
           if(serverResponseCode == 200){
               runOnUiThread(new Runnable() {
                    public void run() {
                        editphoto.setText("File Upload Completed.");
                        Toast.makeText(MainClient.this, "File Upload Complete.", Toast.LENGTH_SHORT).show();
                    }
                });                
           }    

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

      } catch (MalformedURLException ex) {  
          dialog.dismiss();  
          ex.printStackTrace();
          Toast.makeText(MainClient.this, "MalformedURLException", Toast.LENGTH_SHORT).show();
          Log.e("Upload file to server", "error: " + ex.getMessage(), ex);  
      } catch (Exception e) {
          dialog.dismiss();  
          e.printStackTrace();
          Toast.makeText(MainClient.this, "Exception : " + e.getMessage(),      Toast.LENGTH_SHORT).show();
          Log.e("Upload file to server Exception", "Exception : " + e.getMessage(), e);  
      }
      dialog.dismiss();       
      return serverResponseCode;  
     }  

这是php代码

<?php

     $output_users_icons = "uploads/";
     $output_offices_icons = "uploads/";
     $ok_upload_image;
     $ok_upload_logo;
     $err_post=0;
     if(isset($_FILES["uploadImage"])|isset($_FILES["uploadLogo"]))
     {     /* Upload Image User */
            if ($_FILES["uploadImage"]["error"] > 0)
            {
                $ok_upload_image = 0;
            }
            else
            {
                $ok_upload_image = 1;
                $path = $_FILES['uploadImage']['name'];
                $ext = pathinfo($path, PATHINFO_EXTENSION);
                move_uploaded_file($_FILES["uploadImage"]["tmp_name"],$output_users_icons."21.jpg");
            }
           /* END */ 



            /* Upload Image User */
            if ($_FILES["uploadLogo"]["error"] > 0)
            {
                $ok_upload_logo = 0;
            }
            else
            {
                $ok_upload_logo = 1;
                move_uploaded_file($_FILES["uploadLogo"]["tmp_name"],$output_offices_icons. $_FILES["uploadLogo"]["name"]);
            }
           /* END */ 

     }
    ?>

0 个答案:

没有答案