android - 使用多部分数据发布将文本数据与图像一起发送到服务器

标签 android http-post multipartform-data

我是安卓新手。如何使用多部分发布方法将文本数据与图像一起发送到服务器?我现在可以将图像和名称一起发送到服务器。我必须同时发送字符串 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; 


         } 

}

最佳答案

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

       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  */

关于android - 使用多部分数据发布将文本数据与图像一起发送到服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23468908/

相关文章:

android - 从 Activity 完成 2 个 AsyncTask 后如何启动新 Activity ?

javascript - 如何从 Ajax 调用将非 url 请求参数传递给 Smalltalk Teapot

java - 将curl 与apache HttpPost 对象一起使用

ajax - Dart Adaj错误

react-native - 在 React Native (Expo) 中上传图片,使用 fetch 导致 400 错误

Android 位图与透明区域

java - 如何让应用程序的启动图标运行首选项 Activity ?

forms - 如何访问在 multipart/form-data POST 中上传的内容数据?

java - HttpURLConnection 向 Apache/PHP 发送 JSON POST 请求

c# - 如何将文件发送到列表 - .net 核心 web api - postman