2014-03-31 33 views
1

我有以下一段代碼,它從圖庫中選取圖像並將其放到圖像視圖上,現在我需要將其上傳到服務器上!我在網上查了很多代碼,但其中大部分代碼都不起作用。誰能幫我這個 ?Android - 如何將Imageview中的圖像上傳到遠程服務器?

public class MainActivity extends Activity { 

    ImageView viewImage; 
     Button b; 

     @Override 
     protected void onCreate(Bundle savedInstanceState) { 
      super.onCreate(savedInstanceState); 
      setContentView(R.layout.activity_main); 
      b=(Button)findViewById(R.id.btnSelectPhoto); 
      viewImage=(ImageView)findViewById(R.id.viewImage); 
      b.setOnClickListener(new View.OnClickListener() { 
       @Override 
       public void onClick(View v) { 
        selectImage(); 
       } 
      }); 
     } 




      private void selectImage() { 

      final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" }; 

      AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); 
      builder.setTitle("Add Photo!"); 
      builder.setItems(options, new DialogInterface.OnClickListener() { 
       @Override 
       public void onClick(DialogInterface dialog, int item) { 
        if (options[item].equals("Take Photo")) 
        { 
         Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
         File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg"); 
         intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f)); 
         startActivityForResult(intent, 1); 
        } 
        else if (options[item].equals("Choose from Gallery")) 
        { 
         Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); 
         startActivityForResult(intent, 2); 

        } 
        else if (options[item].equals("Cancel")) { 
         dialog.dismiss(); 
        } 
       } 
      }); 
      builder.show(); 
     } 

     @Override 
     protected void onActivityResult(int requestCode, int resultCode, Intent data) 
     { 
      super.onActivityResult(requestCode, resultCode, data); 
      if (resultCode == RESULT_OK) { 
       if (requestCode == 1) { 
        File f = new File(Environment.getExternalStorageDirectory().toString()); 
        for (File temp : f.listFiles()) { 
         if (temp.getName().equals("temp.jpg")) { 
          f = temp; 
          break; 
         } 
        } 
        try { 
         Bitmap bitmap; 
         BitmapFactory.Options bitmapOptions = new BitmapFactory.Options(); 

         bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(), 
           bitmapOptions); 

         viewImage.setImageBitmap(bitmap); 

         String path = android.os.Environment 
           .getExternalStorageDirectory() 
           + File.separator 
           + "Phoenix" + File.separator + "default"; 
         f.delete(); 
         OutputStream outFile = null; 
         File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg"); 
         try { 
          outFile = new FileOutputStream(file); 
          bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile); 
          outFile.flush(); 
          outFile.close(); 
         } catch (FileNotFoundException e) { 
          e.printStackTrace(); 
         } catch (IOException e) { 
          e.printStackTrace(); 
         } catch (Exception e) { 
          e.printStackTrace(); 
         } 
        } catch (Exception e) { 
         e.printStackTrace(); 
        } 
       } else if (requestCode == 2) { 

        Uri selectedImage = data.getData(); 
        String[] filePath = { MediaStore.Images.Media.DATA }; 
        Cursor c = getContentResolver().query(selectedImage,filePath, null, null, null); 
        c.moveToFirst(); 
        int columnIndex = c.getColumnIndex(filePath[0]); 
        String picturePath = c.getString(columnIndex); 
        c.close(); 
        Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath)); 
        Log.w("path of image from gallery......******************.........", picturePath+""); 
        viewImage.setImageBitmap(thumbnail); 
       } 
      } 
     } 
    } 





activity_main.xml code : 

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
       xmlns:tools="http://schemas.android.com/tools" 
       android:id="@+id/LinearLayout1" 
       android:layout_width="match_parent" 
       android:layout_height="match_parent" 
       android:orientation="vertical" 
       android:padding="10dp" > 

    <LinearLayout 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:gravity="center" 
      android:padding="5dp" > 

    <Button 
      android:id="@+id/btnSelectPhoto" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:text="Select Photo" /> 

    </LinearLayout> 

    <LinearLayout 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:orientation="vertical" 
     android:padding="10dp" > 

     <ImageView 
      android:id="@+id/viewImage" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:layout_weight="0.86" 
      android:src="@drawable/ic_launcher" /> 

     <Button 
      android:id="@+id/button1" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:text="Upload" /> 
    </LinearLayout> 

</LinearLayout> 

回答

0

這是我上傳圖片到服務器代碼,它的工作。您需要導入httpmime jar

PHP代碼

$uploads_dir = '/Library/WebServer/Documents/Upload/upload/'.$_FILES['userfile']['name']; 
if(is_uploaded_file($_FILES['userfile']['tmp_name'])) { 
    echo $_POST["contentString"]."\n"; 
    echo "File path = ".$uploads_dir; 
    move_uploaded_file ($_FILES['userfile'] ['tmp_name'], $uploads_dir); 
} else { 
    echo "\n Upload Error"; 
    echo "filename '". $_FILES['userfile']['tmp_name'] . "'."; 
    print_r($_FILES); 

JAVA代碼

HttpClient client = new DefaultHttpClient(); 
HttpPost postMethod = new HttpPost("http://localhost/Upload/index.php"); 

File file = new File(filePath); 

MultipartEntity entity = new MultipartEntity(); 
FileBody contentFile = new FileBody(file); 
entity.addPart("userfile",contentFile); 

StringBody contentString = new StringBody("This is contentString"); 
entity.addPart("contentString",contentString); 

postMethod.setEntity(entity); 
HttpResponse response = client.execute(postMethod); 
HttpEntity httpEntity = response.getEntity(); 
String state = EntityUtils.toString(httpEntity); 
+0

三江源的代碼,但如何將該imageview設置爲文件路徑? – user3458008

+0

file.getPath()... – henry4343

5

使用下面的代碼行併發送Base64的字符串作爲服務器:

ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bitmap is required image which have to send in Bitmap form 
byte[] byteArray = baos.toByteArray(); 

String encodedImage = Base64.encodeToString(byteArray, Base64.DEFAULT); 
相關問題