2012-06-10 5 views
0

Я делаю приложение, которое будет загружать изображение, которое берется с телефона Android. В моем текущем коде одно из моих условий if становится истинным, что возвращает 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; }.

Как я могу решить эту проблему, загрузить изображение, которое снимается с камеры?

Update

Вот мой 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());

Здесь вы отправляете Bitmap String. Не отправляйте путь к изображениям. поэтому эта строка (! sourceFile.isFile()) не обнаружит пути к файлу.

Я думаю, что проблема.

вы отлаживаете код, который поможет вам найти проблему.

Благодаря

+0

после отладки я получаю эту [email protected] в sourceFileUri – 2619

+0

Это не файл URL. если вы хотите проверить наличие файла или нет, вам необходимо сохранить его в памяти телефона или SD-карте после съемки. Лучше загружать фотографию без сохранения. –

+0

Да, это именно то, что я хочу. Как загрузить изображение без сохранения на телефон? Я буду признателен за любой пример кода, который вы можете предоставить. – 2619

Смежные вопросы