2012-06-10 240 views
0

我正在製作一個應用程序,將上傳從android手機拍攝的圖像。在我當前的代碼中,我的if條件中的一個成爲true,返回0,並且由於我的函數停止工作,它也不會將圖像上載到服務器。上傳圖片拍攝從android手機

這是我的代碼

public class Camera extends Activity { 
ImageView ivUserImage; 
Button bUpload; 
Intent i; 
int CameraResult = 0; 
Bitmap bmp; 

int serverResponseCode = 0; 
ProgressDialog dialog = null; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    // TODO Auto-generated method stub 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.camera); 

    ivUserImage = (ImageView)findViewById(R.id.ivUserImage); 
    bUpload = (Button)findViewById(R.id.bUpload); 
    openCamera(); 
} 

private void openCamera() { 
    i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); 
    startActivityForResult(i, CameraResult); 
} 

@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) { 

    super.onActivityResult(requestCode, resultCode, data); 

    if(resultCode == RESULT_OK) { 
     Bundle extras = data.getExtras(); 
     //Log.e("Image: ", data.toString()); 
     bmp = (Bitmap) extras.get("data"); 
     ivUserImage.setImageBitmap(bmp); 

     bUpload.setOnClickListener(new View.OnClickListener() { 

      public void onClick(View v) { 
       dialog = ProgressDialog.show(Camera.this, "", "Uploading file...", true); 
       new Thread(new Runnable() { 
         public void run() { 
          runOnUiThread(new Runnable() { 
           public void run() { 
            //tv.setText("uploading started....."); 
            Toast.makeText(getBaseContext(), "File is uploading...", Toast.LENGTH_LONG).show(); 
           } 
          }); 
         int response= uploadFile(bmp.toString()); 
         //Log.e("Response: ", response); 
         System.out.println("RES : " + response); 
         } 
         }).start(); 
       } 
     }); 
    } 
} 

public int uploadFile(String sourceFileUri) { 

    String upLoadServerUri = "http://www.example.info/androidfileupload/index.php"; 
    String fileName = sourceFileUri; 
    //Toast.makeText(getApplicationContext(), sourceFileUri, Toast.LENGTH_LONG).show(); 
    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); 
    if (!sourceFile.isFile()) { 
     Log.e("uploadFile", "Source File Does not exist"); 
     return 0; 
    } 

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

     bytesAvailable = fileInputStream.available(); // create a buffer of maximum size 

     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() { 
        //tv.setText("File Upload Completed."); 
        Toast.makeText(Camera.this, "File Upload Complete.", Toast.LENGTH_SHORT).show(); 
       } 
      }); 
     }  

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

    } catch (MalformedURLException ex) { 
     dialog.dismiss(); 
     ex.printStackTrace(); 
     Toast.makeText(Camera.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(Camera.this, "Exception : " + e.getMessage(), Toast.LENGTH_SHORT).show(); 
     Log.e("Upload file to server Exception", "Exception : " + e.getMessage(), e); 
    } 

    dialog.dismiss(); 
    return serverResponseCode; 
} 

} 

以我uploadFile()方法這個條件變爲真if (!sourceFile.isFile()) { Log.e("uploadFile", "Source File Does not exist"); return 0; }

我該如何解決這個問題,從攝像頭拍攝的上傳圖像?

更新

,這裏是我的logcat

06-10 16:30:08.595: D/CLIPBOARD(27966): Hide Clipboard dialog at Starting input: finished by someone else... ! 
06-10 16:30:10.305: D/PhoneWindow(27966): couldn't save which view has focus because the focused view [email protected] has no id. 
06-10 16:30:10.980: D/CLIPBOARD(27966): Hide Clipboard dialog at Starting input: finished by someone else... ! 
06-10 16:30:11.015: W/IInputConnectionWrapper(27966): showStatusIcon on inactive InputConnection 
06-10 16:32:18.005: D/PhoneWindow(27966): couldn't save which view has focus because the focused view [email protected] has no id. 
06-10 16:32:38.890: D/dalvikvm(27966): GC_EXTERNAL_ALLOC freed 101K, 46% free 3097K/5639K, external 879K/1025K, paused 37ms 
06-10 16:37:19.145: D/PhoneWindow(27966): couldn't save which view has focus because the focused view [email protected] has no id. 
06-10 16:39:01.805: E/uploadFile(27966): Source File Does not exist 
06-10 16:39:01.805: I/System.out(27966): RES : 0 
06-10 16:39:09.185: D/PhoneWindow(27966): couldn't save which view has focus because the focused view [email protected] has no id. 
06-10 16:39:09.475: D/CLIPBOARD(27966): Hide Clipboard dialog at Starting input: finished by someone else... ! 

回答

0

我怎樣才能解決這個問題,這是從 相機拍攝上傳圖像的?

以下代碼將幫助您。

public void UploadImage(Bitmap bm) throws Exception { 
     try { 
      ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
      bm.compress(CompressFormat.JPEG, 75, bos); 
      byte[] data = bos.toByteArray(); 
      HttpClient httpClient = new DefaultHttpClient(); 
      HttpPost postRequest = new HttpPost(
        "http://www.example.info/androidfileupload/index.php"); 
      ByteArrayBody bab = new ByteArrayBody(data, "forest.jpg"); 

      MultipartEntity reqEntity = new MultipartEntity(
        HttpMultipartMode.BROWSER_COMPATIBLE); 
      reqEntity.addPart("uploaded", bab); 
      reqEntity.addPart("photoCaption", new StringBody("sfsdfsdf")); 
      postRequest.setEntity(reqEntity); 
      HttpResponse response = httpClient.execute(postRequest); 
      BufferedReader reader = new BufferedReader(new InputStreamReader(
        response.getEntity().getContent(), "UTF-8")); 
      String sResponse; 
      StringBuilder s = new StringBuilder(); 

      while ((sResponse = reader.readLine()) != null) { 
       s = s.append(sResponse); 
      } 
      System.out.println("Response: " + s); 
     } catch (Exception e) { 
      // handle exception here 
      Log.e(e.getClass().getName(), e.getMessage()); 
     } 
    } 
0

你從這個線發送位圖串

INT響應= uploadFile(bmp.toString());

在這裏您發送位圖字符串。不要發送圖像的路徑。所以這個(!sourceFile.isFile())行沒有找到任何文件路徑。

我認爲這是一個問題。

你調試你的代碼,幫助你找到問題。

感謝

+0

調試運行後,我得到這個[email protected]在sourceFileUri – 2619

+0

它不是文件的URL。如果你想檢查文件是否存在,那麼你需要在拍照後將其保存在手機內存或SD卡中。最好不要保存就上傳照片。 –

+0

是的,這正是我想要的。如何上傳圖片而不保存到手機中?我將不勝感激任何您可以提供的代碼示例。 – 2619

相關問題