2017-03-15 1 views
0

이미지와 비디오를 청크로 웹 서버에 업로드하려합니다. 청크를 업로드 한 후에 다음 청크를 전송하기 위해 outputstream을 다시 호출해야합니다. 내가 가진 방법이 있습니다. 한 번만 outstream에 대한 호출합니다. 그때 그것은 왜 chunk를 업로드 한 후에 매번 outputstream을 호출하는 것이 필수적입니다. 내 코드 현재 코드가큰 파일을 android에서 웹 서버로 업로드하는 방법

header('Content-type:bitmap;charset=utf-8'); 
$super_parent_dir=$_POST["spd"];//super parent dic 
$parent_dir=$_POST["pd"];//parent dic 
$child_dir=$_POST["cd"];//super_child dic 
$host_no=$_POST["queue_num"];//child_dic 
$image_name=$_POST["image_name"];//file 

$spd_path=$super_parent_dir; 
$pd_path=$spd_path."/".$parent_dir; 
$ch_path=$pd_path."/".$child_dir; 
$f_folder=$ch_path."/".$host_no; 

if(!is_dir($f_folder)) 
mkdir($f_folder, 0777);//echo $f_folder; 

if(isset($_POST["Image_data"])){ 

$econded_string=$_POST["Image_data"]; 
$decode_string=base64_decode($econded_string); 
$path=$f_folder.'/'.$image_name; 
$file=fopen($path,'a'); 
$is_written=fwrite($file,$decode_string); 
fclose($file); 

if($is_written>0){ 
    $connection=mysqli_connect("localhost","root","","imgae_db"); 
    $query="insert into photos values('','$path','$image_name')"; 
    $result= mysqli_query($connection,$query); 

}} 

공용 클래스 Media_uploader가 {

private String image_file; 
public Media_uploader(File image){ 
    this.image_file= String.valueOf(image); 
} 

@Override 
protected void onPreExecute() { 
    super.onPreExecute(); 
} 

@Override 
protected Void doInBackground(Void... params) { 
    Bitmap bitmap= BitmapFactory.decodeFile(image_file); 
    ByteArrayOutputStream stream=new ByteArrayOutputStream(); 
    bitmap.compress(Bitmap.CompressFormat.JPEG,100,stream); 

    byte[] array=stream.toByteArray(); 
    String a= Base64.encodeToString(array,Base64.DEFAULT); 


    try { 
     URL url=new URL("http://192.168.1.1**/db_mager/Medaia_Downloader.php"); 
     HttpURLConnection httpURLConnection=(HttpURLConnection)url.openConnection(); 

     httpURLConnection.setDoOutput(true); 
     OutputStream stream1=httpURLConnection.getOutputStream(); 
     BufferedWriter bufferedWriter=new BufferedWriter(new OutputStreamWriter(stream1,"UTF-8")); 

     String data= URLEncoder.encode("spd","UTF-8")+"="+URLEncoder.encode(Session_Data.getMyDatabase(),"UTF-8")+"&"+ 
        URLEncoder.encode("pd","UTF-8")+"="+URLEncoder.encode(Session_Data.getMyCity(),"UTF-8")+"&"+ 
        URLEncoder.encode("cd","UTF-8")+"="+URLEncoder.encode(Session_Data.getMyID(),"UTF-8")+"&"+ 
        URLEncoder.encode("queue_num","UTF-8")+"="+URLEncoder.encode(String.valueOf(Session_Data.getActivity_Record()),"UTF-8")+"&"+ 
        URLEncoder.encode("image_name","UTF-8")+"="+URLEncoder.encode(image_file,"UTF-8")+"&"+ 
        URLEncoder.encode("Image_data","UTF-8")+"="+URLEncoder.encode(a,"UTF-8"); 

     bufferedWriter.write(data); 
     bufferedWriter.flush(); 
     bufferedWriter.close(); 
     stream1.close(); 

     InputStream inputStream=httpURLConnection.getInputStream(); 
     inputStream.close(); 

    } catch (java.io.IOException e) { 
     e.printStackTrace(); 
    } 

    return null; 
} 
+0

멀티 파트 데이터 업로드에 대해 들었습니까? –

+0

예 멀티 파트로 더 좋은 옵션을 시도하십시오 – Saveen

+0

지금까지 가지고있는 코드를 제공해주십시오. http://stackoverflow.com/help/how-to-ask 방문 – Olaia

답변

0

이 코드는 서버에 안드로이드에서 멀티 업로드를 사용하는 예입니다 AsyncTask를 확장입니다 - 다른 라이브러리는 것이다있다 이것을 지원하여 어느 것이 당신에게 가장 적합한 지 결정할 수있는 연구를 해 줄 가치가 있지만 아래는 테스트를 거쳐 작동합니다.

public class VideoUploadTask extends AsyncTask<String, String, Integer> { 
    /* This Class is an AsynchTask to upload a video to a server on a background thread 
    * 
    */ 

    private VideoUploadTaskListener thisTaskListener; 
    private String serverURL; 
    private String videoPath; 

    public VideoUploadTask(VideoUploadTaskListener ourListener) { 
     //Constructor 
     Log.d("VideoUploadTask","constructor"); 

     //Set the listener 
     thisTaskListener = ourListener; 
    } 

    @Override 
    protected Integer doInBackground(String... params) { 
     //Upload the video in the background 
     Log.d("VideoUploadTask","doInBackground"); 

     //Get the Server URL and the local video path from the parameters 
     if (params.length == 2) { 
      serverURL = params[0]; 
      videoPath = params[1]; 
     } else { 
      //One or all of the params are not present - log an error and return 
      Log.d("VideoUploadTask doInBackground","One or all of the params are not present"); 
      return -1; 
     } 


     //Create a new Multipart HTTP request to upload the video 
     HttpClient httpclient = new DefaultHttpClient(); 
     HttpPost httppost = new HttpPost(serverURL); 

     //Create a Multipart entity and add the parts to it 
     try { 
      Log.d("VideoUploadTask doInBackground","Building the request for file: " + videoPath); 
      FileBody filebodyVideo = new FileBody(new File(videoPath)); 
      StringBody title = new StringBody("Filename:" + videoPath); 
      StringBody description = new StringBody("test Video"); 
      MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); 
      reqEntity.addPart("videoFile", filebodyVideo); 
      reqEntity.addPart("title", title); 
      reqEntity.addPart("description", description); 
      httppost.setEntity(reqEntity); 
     } catch (UnsupportedEncodingException e1) { 
      //Log the error 
      Log.d("VideoUploadTask doInBackground","UnsupportedEncodingException error when setting StringBody for title or description"); 
      e1.printStackTrace(); 
      return -1; 
     } 

     //Send the request to the server 
     HttpResponse serverResponse = null; 
     try { 
      Log.d("VideoUploadTask doInBackground","Sending the Request"); 
      serverResponse = httpclient.execute(httppost); 
     } catch (ClientProtocolException e) { 
      //Log the error 
      Log.d("VideoUploadTask doInBackground","ClientProtocolException"); 
      e.printStackTrace(); 
     } catch (IOException e) { 
      //Log the error 
      Log.d("VideoUploadTask doInBackground","IOException"); 
      e.printStackTrace(); 
     } 

     //Check the response code 
     Log.d("VideoUploadTask doInBackground","Checking the response code"); 
     if (serverResponse != null) { 
      Log.d("VideoUploadTask doInBackground","ServerRespone" + serverResponse.getStatusLine()); 
      HttpEntity responseEntity = serverResponse.getEntity(); 
      if (responseEntity != null) { 
       //log the response code and consume the content 
       Log.d("VideoUploadTask doInBackground","responseEntity is not null"); 
       try { 
        responseEntity.consumeContent(); 
       } catch (IOException e) { 
        //Log the (further...) error... 
        Log.d("VideoUploadTask doInBackground","IOexception consuming content"); 
        e.printStackTrace(); 
       } 
      } 
     } else { 
      //Log that response code was null 
      Log.d("VideoUploadTask doInBackground","serverResponse = null"); 
      return -1; 
     } 

     //Shut down the connection manager 
     httpclient.getConnectionManager().shutdown(); 
     return 1; 
    } 

    @Override 
    protected void onPostExecute(Integer result) { 
     //Check the return code and update the listener 
     Log.d("VideoUploadTask onPostExecute","updating listener after execution"); 
     thisTaskListener.onUploadFinished(result); 
    } 

} 
관련 문제