使用多部分数据发送文本数据和图像一起发送到服务器

时间:2014-05-05 09:18:38

标签: android http-post multipartform-data

我是android的新手。如何使用multipart post方法将文本数据与图像一起发送到服务器?我现在可以将图像和名称一起发送到服务器。我必须发送String data1和data2。

代码如下:

public class UploadToServerNew extends Activity {

    TextView messageText;
    Button uploadButton;
    int serverResponseCode = 0;
    private static final int SELECT_PHOTO = 100;

    String upLoadServerUri = null;

    /**********  File Path *************/

    Uri selectedImage;
    String pathtoimage;

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_upload_to_server);

        uploadButton = (Button)findViewById(R.id.uploadButton);
        messageText  = (TextView)findViewById(R.id.messageText);



        /************* Php script path ****************/
        upLoadServerUri = "http://192.168.1.23/imagetransfer/UploadToServer.php";


        uploadButton.setOnClickListener(new OnClickListener() {            
            @Override
            public void onClick(View v) {

                Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
                photoPickerIntent.setType("image/*");
                startActivityForResult(photoPickerIntent, SELECT_PHOTO); 



                }
            });
    }
    private String getRealPathFromURI(Uri contentURI) {
        String result;
        Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
        if (cursor == null) { // Source is Dropbox or other similar local file path
            result = contentURI.getPath();
        } else { 
            cursor.moveToFirst(); 
            int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA); 
            result = cursor.getString(idx);
            cursor.close();
        }
        return result;
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) { 
        super.onActivityResult(requestCode, resultCode, imageReturnedIntent); 

        switch(requestCode) { 
        case SELECT_PHOTO:
            if (resultCode == RESULT_OK) {
                selectedImage = imageReturnedIntent.getData();

                pathtoimage = getRealPathFromURI(selectedImage);
                new uploadFile().execute(pathtoimage);
                Log.d("path", pathtoimage);

            }
        }
    }
    private class uploadFile extends AsyncTask<String, Void, Void>{
        ProgressDialog dialog;
        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();
            messageText.setText("");
            dialog = ProgressDialog.show(UploadToServerNew.this, "", "Uploading file...", true);
            dialog.show();
        }
        @Override
        protected Void doInBackground(String... pathtoimage) {
            // TODO Auto-generated method stub
             uploadFile(pathtoimage[0]);      
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            if(dialog.isShowing()){
                dialog.dismiss();
            }
        }
    }

    public int uploadFile(String sourceFileUri) {


          String fileName = sourceFileUri;
          String data1="one",data2="two";

          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); 


               try { 

                     // open a URL connection to the Servlet
                   FileInputStream fileInputStream = new FileInputStream(sourceFile);
                   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);

                   // 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);

                   if(serverResponseCode == 200){

                       runOnUiThread(new Runnable() {
                            public void run() {

                                String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
                                              +"http://localhost/imagetransfer/uploads/";

                                messageText.setText(msg);
                                Toast.makeText(UploadToServerNew.this, "File Upload Complete.", 
                                             Toast.LENGTH_SHORT).show();
                            }
                        });                
                   }    

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

              } catch (MalformedURLException ex) {

                //  dialog.dismiss();  
                  ex.printStackTrace();

                  runOnUiThread(new Runnable() {
                      public void run() {
                          messageText.setText("MalformedURLException Exception : check script url.");
                          Toast.makeText(UploadToServerNew.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(UploadToServerNew.this, "Got Exception : see logcat ", 
                                  Toast.LENGTH_SHORT).show();
                      }
                  });
                  Log.e("Upload file to server Exception", "Exception : " 
                                                   + e.getMessage(), e);  
              }
             // dialog.dismiss();       
              return serverResponseCode; 


         } 

}

5 个答案:

答案 0 :(得分:3)

将文本和图像发送到服务器是一项简单的任务。只需将图像转换为字符串并随文本一起发送..

       Bitmap bitmap = BitmapFactory.decodeFile(fileUri);

       ByteArrayOutputStream stream = new ByteArrayOutputStream();

       bitmap.compress(Bitmap.CompressFormat.JPEG, 90, stream);


       byte[]  byteArray= stream.toByteArray();
       String  imageString= Base64.encode(byteArray);


      ArrayList<NameValuePair> ValuePairs= newArrayList<NameValuePair>(); 
      ValuePairs .add(new BasicNameValuePair("image", imageString));
      ValuePairs .add(new BasicNameValuePair("imageName", Name));

      ValuePairs .add(new BasicNameValuePair("FolderId", folder));

      try 
      {
         HttpClient httpclient = new DefaultHttpClient();
         HttpPost httppost =new HttpPost("http://64.125.119.152:1991/uploadserver/UploadToServer.php");              
        System.setProperty("http.keepAlive", "false");
        httppost .setEntity(new UrlEncodedFormEntity(ValuePairs ));
        HttpResponse response = httpclient.execute(httppost );
        Strresponse= convertResponseToString(response );

        }
   catch (Exception e)

    {
     Toast.makeText(s, "ERROR " + e.getMessage(),       
     Toast.LENGTH_LONG).show();
     System.out.println("Error in http connection " + e.toString());
    }

 return Strresponse;
} //*visit:http://androiddhina.blogspot.in/p/androidhints.html  */

答案 1 :(得分:1)

您可以尝试这样的事情:

conn.setRequestProperty("uploaded_file", fileName);
conn.setRequestProperty("key_1", "value_1"); 
conn.setRequestProperty("key_2", "value?_2"); 
conn.setRequestProperty("key_3", "value_3"); 

conn.setRequestProperty("key_n", "value_n"); 

其中key__1,2,3,n是data1,data2,datan ....

<强> EDITED

在php中的服务器端:

您可以使用此$_SERVER["key_1"]$_SERVER["key_2"] .... $_SERVER["key_n"];

答案 2 :(得分:0)

尝试使用HTTP Request库。要执行多部分发布,您只需要:

HttpRequest request = HttpRequest.post("http://google.com");
request.part("status[body]", "Making a multipart request");
request.part("status[image]", new File("/home/kevin/Pictures/ide.png"));
if (request.ok())
  System.out.println("Status was updated");

答案 3 :(得分:0)

你可以试试这个:

THIS IS YOUR CODE
.......

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

// add code below ...
// start from here ............  

dos.writeBytes(twoHyphens + boundary + lineEnd); 
dos.writeBytes("Content-Disposition: form-data; name=\"YOUR VARIABLE NAME\"" + lineEnd + lineEnd + "YOUR DATA VALUE" + lineEnd);

// end .............  

THIS IS YOUR CODE

dos.writeBytes(lineEnd);

...........

答案 4 :(得分:0)

请在此处使用以下方法:

    Button btn_update = view.findViewById(R.id.btn_update);
    btn_update.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {                    
               if (Util.isConnectingToInternet(getActivity())) {
                    updateProfileDetails();
                } else {
                  // No Internet Connection code here
                }    
        }
    });
    private String imagePath;
    ProgressDialog pDialog;
    AlertDialog.Builder builder;

    public void updateProfileDetails() {
        new AsyncTask<Void, Integer, String>(){
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                pDialog = new ProgressDialog(getActivity());
                pDialog.setTitle("Please wait");
                pDialog.setMessage("updating.... ");
                pDialog.setCancelable(false);
                pDialog.show();
                builder = new AlertDialog.Builder(getActivity());
            }

            @Override
            protected String doInBackground(Void... voids) {
                return uploadFile();
            }

            private String uploadFile(){
                File uploadFile1 = new File(imagePath);
                File uploadFile2 = new File(imagePath);
                String logId = applicationController.getValueFromPerference(Constants.LOGID);

                String responseString = null;

                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(Constants.URL + Constants.UPDATE_PROFILE);
                try {
                    MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
                    entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
                    entityBuilder.addTextBody("companyname", companyName);
                    entityBuilder.addTextBody("name", name);
                    entityBuilder.addTextBody("phone", mobileNo);
                    entityBuilder.addTextBody("email", emailId);
                    entityBuilder.addTextBody("dateofbirth", dateOfBirth);
                    entityBuilder.addTextBody("aadharnumber", aadhaarCardNo);
                    entityBuilder.addTextBody("pannumber", pancardNo);
                    entityBuilder.addTextBody("address", address);
                    entityBuilder.addTextBody("location", location);
                    entityBuilder.addTextBody("pincode", pincode);
                    entityBuilder.addTextBody("logid", logId);

                    entityBuilder.addBinaryBody("userimage", uploadFile1);
                    entityBuilder.addBinaryBody("gumasta", uploadFile2);

                    HttpEntity entity = entityBuilder.build();
                    httppost.setEntity(entity);

                    HttpResponse response = httpclient.execute(httppost);
                    HttpEntity  httpEntity = response.getEntity();

                    int statusCode = response.getStatusLine().getStatusCode();
                    if (statusCode == 200) {
                        // Server response
                        responseString = EntityUtils.toString(httpEntity);
                    } else {
                        responseString = "Error occurred! Http Status Code: "
                                + statusCode;
                    }
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                } catch (ClientProtocolException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                return responseString;
            }

            @Override
            protected void onPostExecute(String resultString) {
                super.onPostExecute(resultString);
                if (pDialog.isShowing())
                    pDialog.dismiss();
                Toast toast = Toast.makeText(context, resultString, Toast.LENGTH_LONG);
                toast.getView().setBackgroundColor(getResources().getColor(R.color.nevy_blue));
                toast.show();
                if (resultString != null && !resultString.equals("")) {
                    try {
                        JSONObject jsonObject = new JSONObject(resultString);
                        if (jsonObject.getString("status").equals("1")) {
                            builder.setCancelable(true);
                            builder.setMessage(jsonObject.getString("message"));
                            builder.setInverseBackgroundForced(true);
                            builder.setPositiveButton("Done", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            });
                            builder.show();

                        } else {
                            Toast toast1 = Toast.makeText(context, jsonObject.getString("message"), Toast.LENGTH_LONG);
                            toast1.getView().setBackgroundColor(getResources().getColor(R.color.green));
                            toast1.show();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                } else {
                    Toast toast2 = Toast.makeText(context, "Sorry! Due to some problem Message sending failed", Toast.LENGTH_LONG);
                    toast2.getView().setBackgroundColor(getResources().getColor(R.color.red));
                    toast2.show();
                }
            }

        }.execute();
    }