2014-01-17 25 views
0

我很難找出如何傳遞圖像的uri,因爲我需要它來抓取文件,除非有另一種方式,我只是沒有看到它(我對此很新)。我選擇了圖像工作,並將imageview的位圖設置爲位圖,但現在嘗試在點擊提交按鈕後將其發送到服務器。如何將android image的uri傳遞給異步任務的執行調用?

我知道我可以執行(uri);但是我怎麼才能從imageview中取出uri呢?

下面是代碼:)

public class wardrobe extends Activity implements OnClickListener { 

    // set variable for the fields 
    private EditText nameField, sizeField, colorField, quantityField; 
    private Spinner typeField, seasonField; 
    private ImageView imageview; 
    private ProgressBar progressBarField; 
    private TextView imageTextSelect, resImage; 
    private ProgressDialog progressDialog = null; 
    private int serverResponseCode = 0; 
    private Button uploadImageButton, postWardrobe; 
    private String upLoadServerUri = null; 
    private String imagepath = null; 
    private Bitmap bitmap; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.wardrobe); 

     // image upload stuff 
     imageview = (ImageView) findViewById(R.id.user_photo); 
     imageTextSelect = (TextView) findViewById(R.id.imageTextSelect); 

     // button for upload image 
     uploadImageButton = (Button) findViewById(R.id.uploadImageButton); 

     // button for posting details 
     postWardrobe = (Button) findViewById(R.id.postButton); 

     uploadImageButton.setOnClickListener(this); 
     postWardrobe.setOnClickListener(this); 



    @Override 
    public void onClick(View v) { 

     /** 
     * Opens dialog picker, so the user can select image from the gallery. 
     * The result is returned in the method <code>onActivityResult()</code> 
     */ 
     if (v == uploadImageButton) { 
      // below allows you to open the phones gallery 
      Intent intent = new Intent(); 
      intent.setType("image/*"); 
      intent.setAction(Intent.ACTION_GET_CONTENT); 
      startActivityForResult(
        Intent.createChooser(intent, "Complete action using"), 1); 
     } 
     if (v == postWardrobe) { 

       // execute the post request 

       new ImageUploadTask().execute(); 

      } 
     } 

    } 

    /** 
    * Retrives the result returned from selecting image, by invoking the method 
    * <code>selectImageFromGallery()</code> 
    */ 
    public void onActivityResult(int requestCode, int resultCode, Intent data) { 
     if (resultCode == RESULT_OK && requestCode == 1 && null != data) { 

      decodeUri(data.getData()); 
     } 
    } 

    public void decodeUri(Uri uri) { 
     ParcelFileDescriptor parcelFD = null; 
     try { 
      parcelFD = getContentResolver().openFileDescriptor(uri, "r"); 
      FileDescriptor imageSource = parcelFD.getFileDescriptor(); 

      // Decode image size 
      BitmapFactory.Options o = new BitmapFactory.Options(); 
      o.inJustDecodeBounds = true; 
      BitmapFactory.decodeFileDescriptor(imageSource, null, o); 

      // the new size we want to scale to 
      final int REQUIRED_SIZE = 1024; 

      // Find the correct scale value. It should be the power of 2. 
      int width_tmp = o.outWidth, height_tmp = o.outHeight; 
      int scale = 1; 
      while (true) { 
       if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE) { 
        break; 
       } 
       width_tmp /= 2; 
       height_tmp /= 2; 
       scale *= 2; 
      } 

      // decode with inSampleSize 
      BitmapFactory.Options o2 = new BitmapFactory.Options(); 
      o2.inSampleSize = scale; 
      bitmap = BitmapFactory.decodeFileDescriptor(imageSource, null, o2); 

      imageview.setImageBitmap(bitmap); 

      // can take off below just shows path 
      imageTextSelect.setText("select : " + uri); 
     } catch (FileNotFoundException e) { 
      // handle errors 
     } catch (IOException e) { 
      // handle errors 
     } finally { 
      if (parcelFD != null) 
       try { 
        parcelFD.close(); 
       } catch (IOException e) { 
        // ignored 
       } 
     } 
    } 

PART我試圖獲取工作:)

private class ImageUploadTask extends AsyncTask<Void, Void, String> { 



What I need is the uri or the file... 
String fileName = imagepath; 
File sourceFile = new File(imagepath); 


       private String webAddressToPost = "http://10.0.2.2/wardrobe"; 
       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; 


       // private ProgressDialog dialog 
       private ProgressDialog progressDialog = new ProgressDialog(
           wardrobe.this); 

       @Override 
       protected void onPreExecute() { 
         progressDialog.setMessage("Uploading..."); 
         progressDialog.show(); 
       } 

       @Override 
       protected String doInBackground(Void... arg0) { 



if (!sourceFile.isFile()) { 

         progressDialog.dismiss(); 

         Log.e("uploadFile", "Source File not exist :" + imagepath); 

         runOnUiThread(new Runnable() { 
           public void run() { 
             imageTextSelect.setText("Source File not exist :" 
                 + imagepath); 
           } 
         }); 

         return 0; 

       } else { 
         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) { 


                 String msg = "File Upload Completed.\n\n See uploaded file here : \n\n" 
                     + " F:/wamp/wamp/www/uploads"; 
                 imageTextSelect.setText(msg); 
                 Toast.makeText(wardrobe.this, 
                     "File Upload Complete.", Toast.LENGTH_SHORT) 
                     .show(); 

           } 

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

         } catch (MalformedURLException ex) { 

           progressDialog.dismiss(); 
           ex.printStackTrace(); 


               imageTextSelect 
                   .setText("MalformedURLException Exception : check script url."); 
               Toast.makeText(wardrobe.this, "MalformedURLException", 
                   Toast.LENGTH_SHORT).show(); 


           Log.e("Upload file to server", "error: " + ex.getMessage(), ex); 
         } catch (Exception e) { 

           progressDialog.dismiss(); 
           e.printStackTrace(); 


               imageTextSelect.setText("Got Exception : see logcat "); 
               Toast.makeText(wardrobe.this, 
                   "Got Exception : see logcat ", 
                   Toast.LENGTH_SHORT).show(); 

           Log.e("Upload file to server Exception", 
               "Exception : " + e.getMessage(), e); 
         } 


} 
+0

你可以用它代替HTTP發佈FTP。獲取您的位圖像這樣...位圖位圖=((BitmapDrawable)image.getDrawable())。getBitmap(); – elbuild

+0

我寧願使用http,我知道他們之間有很多爭論,但我並沒有試圖進入這個複雜的理由,謝謝,但是,我覺得這個問題必須有一個簡單的答案......人們如何做它大聲笑 – Lion789

回答

0

你必須使用HTTP POST與多數據上傳圖片。

嘗試this link

相關問題