2013-12-18 3 views
0

안녕하세요 저는 카메라 이미지가 포함 된 앱을 개발 중입니다. PHP 서버로 캡쳐하는 동안 이미지를 보내야합니다. 설정에 "AutoUploadPic"과 같은 부울 옵션이 있습니다. 스위치를 '예'로 설정하면 서버에만 업로드해야합니다. , 아니요로 설정하면 업로드해서는 안됩니다. 이걸 좀 도와 주실 래요?캡처 한 이미지를 서버로 보내는 방법은 무엇입니까?

위의 쿼리에 대한 아이폰 코드는 다음과 같습니다. 안드로이드에서도 같은 결과를 얻을 수 있습니다.

+0

지금까지 사용해 본 Raghu는 무엇입니까? –

+0

글쎄, PHP와 아마도 웹 서버를 사용하기 때문에 http 업로드를 구현해야한다. 여기에 어떤 질문이 있습니까? – arkascha

답변

1

왜 비트 맵을 바이트 배열로 변환하여 서버로 전달할 수 없습니까? 다음은 서버에 비트 맵을 보내는 코드입니다.

AsyncTask에서 이러한 작업을 수행하십시오.

public class UploadPicture extends AsyncTask<Void, Void, Void> { 

    @Override 
    protected void onPreExecute() { 
     // TODO Auto-generated method stub 
     super.onPreExecute(); 
     // show your progress bar 

    } 

    @Override 
    protected Void doInBackground(Void... params) { 
     // TODO Auto-generated method stub 

     // wrap up all your upload code here.. 

     return null; 
    } 

    @Override 
    protected void onPostExecute(Void result) { 
     // TODO Auto-generated method stub 
     super.onPostExecute(result); 
     // stop your progress bar 
    } 
} 

전화하여 부울을 확인한 후이 클래스 :

if(AutoUploadPic) 
{ 
new UploadPicture().execute(); 
} 
else 
{ 
// Your code here.. 
} 

//하여 doInBackground 클래스에서 다음을 수행하십시오

try { 
    ByteArrayOutputStream bos = new ByteArrayOutputStream(); 

// Preview_bitmap은 당신이 보낼 필요 하나입니다 서버. 나는 여기에 압축 및 서버에이를 보내고있다 :

HttpPost postRequest = new HttpPost(Constant.uploadImagesAPI 
      + Constant.mDeviceID); 

    ByteArrayBody bab = new ByteArrayBody(data, ".jpg"); 
    MultipartEntity reqEntity = new MultipartEntity(
      HttpMultipartMode.BROWSER_COMPATIBLE); 
    reqEntity.addPart("image", bab); 
    postRequest.setEntity(reqEntity); 
    HttpResponse response = httpClient.execute(postRequest); 
    BufferedReader reader = new BufferedReader(new InputStreamReader(
      response.getEntity().getContent(), "UTF-8")); 
    String sResponse; 
    StringBuilder mUploadResponse = new StringBuilder(); 

    while ((sResponse = reader.readLine()) != null) { 
     mUploadResponse = mUploadResponse.append(sResponse); 
    } 

    JSONObject mUploadResponseObject = new JSONObject(
      mUploadResponse.toString()); 

    mUploadResponseObject.getJSONArray("response"); 

    try { 
     JSONArray jsonArray = mUploadResponseObject 
       .getJSONArray("response"); 
     for (int i = 0; i < jsonArray.length(); i++) { 
      uploadStatus = jsonArray.getJSONObject(i) 
        .getJSONObject("send").getString("message"); 
      uploadPhotoID = jsonArray.getJSONObject(i) 
        .getJSONObject("send").getString("id"); 
      Constant.imageUploadedFlag = true; 
     } 
    } catch (Exception e) { 
     serverUploadException = true; 

    } 

} catch (Exception e) { 

} 

// PHP 코드 :

$to = $_REQUEST['deviceid']; 
      //$timestamp = $_REQUEST['timestamp']; 
      $path=PATH.'upload/'; 
      //$path1=PATH.'newupload/'; 
      //$name = $_FILES['image']['name']; 
      //$str=explode(".",$name); 
      //$imname=$str[0]; 
      $filename=upload::save($_FILES['image']);     
      $file_name1= basename($filename); 
      $docroot= $_SERVER['DOCUMENT_ROOT'];  
      //$root=$docroot.'/newupload/'; 
      $roots=$docroot.'/upload/'; 
      $url = $path.$file_name1; 
         $send = $this->api->upload_images($to,$url); 
        if($send) 
           { 



             $json_response[] = array("send" => 
               array("id"=> $send, 
              "message"=>"Message Sent Successfully", 
              "status"=>1)); 
                  } 
                   echo json_encode(array ('response' =>$json_response)); 


     break; 
+0

어떻게 내 부울 조건을 사용할 수 있습니까? –

+0

업데이트 된 답변을 확인하십시오. –

0

업로드 이미지

preview_bitmap.compress(CompressFormat.JPEG, 100, bos); 
    byte[] data = bos.toByteArray(); 

    HttpClient httpClient = new DefaultHttpClient(); 

// constant.uploadImagesAPI는 서버 URL이 멀티 파트 파일 업로드를 통해 서버에 전송할 수 있습니다.

import java.io.File; 
import java.io.IOException; 

import org.apache.http.HttpEntity; 
import org.apache.http.HttpResponse; 
import org.apache.http.HttpStatus; 
import org.apache.http.ParseException; 
import org.apache.http.client.ClientProtocolException; 
import org.apache.http.client.HttpClient; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.entity.mime.MultipartEntity; 
import org.apache.http.entity.mime.content.ContentBody; 
import org.apache.http.entity.mime.content.FileBody; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.apache.http.util.EntityUtils; 

import android.content.Context; 
import android.content.res.Resources.NotFoundException; 
import android.os.AsyncTask; 


public class MultiPartFileUpload { 

    private String filePath; 
    private String fileMimeType; 
    private String url; 
    private String attribute; 
    private AfterImageUploaded afterResult; 
    private CustomExceptions exception = null; 
    byte[] buffer; 
    byte[] data; 
    private Context context; 
    /** 
    * Provide mechanism to upload file with multi-part approach 
    * 
    * @param filePath 
    *   : Absolute path of file 
    * @param fileMimeType 
    *   : File mime-type e.g. image/jpeg 
    * @param url 
    *   : URL to upload file 
    * @param attribute 
    *   : Attribute where file would be placed 
    * @param afterResult 
    *   : Implement this interface to receive result/errors 
    */ 
    public MultiPartFileUpload(Context context,String filePath, String fileMimeType, 
      String url, String attribute, AfterImageUploaded afterResult) { 
     this.context=context; 
     this.filePath = filePath; 
     this.fileMimeType = fileMimeType; 
     this.url = url; 
     this.attribute = attribute; 
     this.afterResult = afterResult; 

     UploadFileAsync uploadasynctask = new UploadFileAsync(); 
     uploadasynctask.execute(url); 
    } 

    class UploadFileAsync extends AsyncTask<String, Integer, String> { 

     @Override 
     protected void onProgressUpdate(Integer... values) { 
      // TODO Auto-generated method stub 
      super.onProgressUpdate(values[0]); 
     } 

     @Override 
     protected String doInBackground(String... params) { 
      try { 
       String result = null; 
       ContentBody cbFile = null; 
       HttpClient httpclient = new DefaultHttpClient(); 

       System.out.println("url:"+url); 

       HttpPost httppost = new HttpPost(url); 

       httppost.setHeader("partnerKey", 
            "39f1a112ed3b4a3537c1e05766e91d2f425a8d97"); 


       MultipartEntity mpEntity = new MultipartEntity(); 
       mpEntity.addPart("image", new FileBody(new File(filePath))); 
         } 



       try { 
        httppost.setEntity(mpEntity); 

        HttpResponse response = httpclient.execute(httppost); 
        HttpEntity resEntity = response.getEntity(); 



       System.out.println("response>>>>::"+ response.getStatusLine()); 
        System.out.println("--------------------------------------"); 

        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { 
         if (resEntity != null) { 
          result = EntityUtils.toString(resEntity); 
         } 

        } else { 
         throw new CustomExceptions("Connection error: " 
           + response.getStatusLine().getStatusCode() 
           + ":" + response.getStatusLine()); 
        } 
       } catch (ClientProtocolException e) { 
        throw new CustomExceptions("Protocol Exception"); 
       } catch (ParseException e) { 
        throw new CustomExceptions("Parse Exception"); 
       } catch (IOException e) { 
        e.printStackTrace(); 
        throw new CustomExceptions("IO Exception"); 
       } 

       httpclient.getConnectionManager().shutdown(); 

       return result; 


       // return postFile(); publishProgress(10) 

      } catch (NotFoundException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 


      return null;} 

     @Override 
     protected void onPostExecute(String result) { 
      super.onPostExecute(result); 
      afterResult.doAfterResult(result, exception); 
     } 

    } 

    public interface AfterImageUploaded { 
     public void doAfterResult(String result, Exceptions e); 
    } 

} 
관련 문제