Android

안드로이드 OkHttp3를 활용한 동영상 전송

Machine_웅 2018. 7. 18. 14:38
728x90
반응형
Uri video_URI;

 

 

// 동영상 앨범 열기
public void getVideoFromGallery() {
ImageView getVideoBtn = (ImageView) findViewById(R.id.getVideoBtn);
getVideoBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {


//갤러리 동영상 호출
Uri uri = Uri.parse("content://media/external/images/media");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setType("video/*");
startActivityForResult(intent, VIDEOFILE_REQUEST);


}
});

}

 

 

 

// 서버에 전송
public void sendVideoContentToServer() {


class sendDataToHttp extends AsyncTask<Void, Void, String> {
String serverUrl = "서버주소";
OkHttpClient client = new OkHttpClient();

Context context;

public sendDataToHttp(Context context) {
this.context = context;
}

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

@Override
protected String doInBackground(Void... voids) {
ContentResolver contentResolver = context.getContentResolver();
final String contentType = contentResolver.getType(video_URI);
final AssetFileDescriptor fd;
try {
fd = contentResolver.openAssetFileDescriptor(video_URI, "r");

if (fd == null) {
throw new FileNotFoundException("could not open file descriptor");
}


RequestBody videoFile = new RequestBody() {
@Override
public long contentLength() {
return fd.getDeclaredLength();
}

@Override
public MediaType contentType() {
return MediaType.parse(contentType);
}

@Override
public void writeTo(BufferedSink sink) throws IOException {
try (InputStream is = fd.createInputStream()) {
sink.writeAll(Okio.buffer(Okio.source(is)));
}
}
};

RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("loginUserId", loginUserId)
.addFormDataPart("file", "fname",videoFile)
.build();

Request request = new Request.Builder()
.url(serverUrl)
.post(requestBody)
.build();

client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
try {
fd.close();
} catch (IOException ex) {
e.addSuppressed(ex);
}
Log.d("실패", "failed", e);
}

@Override
public void onResponse(Call call, Response response) throws IOException {
String result = response.body().string();
Log.d("결과",""+result);
fd.close();
}
});

} catch (FileNotFoundException e) {
e.printStackTrace();
}


return null;
}

@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}

}

sendDataToHttp sendData = new sendDataToHttp(this);
sendData.execute();
}

 

 

 

 

PHP

 

 


 $userId  = $_POST['loginUserId'];
 $videosFile = $_FILES['file']['name'];
 $data = date("Ymdhi");
 $file_path = "/Video_dir/";

// 저장할 경로 + 새로운 이름을 지정한다.
 $file_name = $_SERVER['DOCUMENT_ROOT'].$file_path.$userId.$data.".mp4";


 if(isset($videosFile)){

// 임시폴더에서  위에서 작성한 경로로  새로운 이름으로  보내준다.
  if( move_uploaded_file($_FILES['file']['tmp_name'], $file_name)){
    echo "업로드 성공";
  }else{

    echo "업로드 실패";
  }

 }else{
  echo "실패";
 }

 

 

출처 : https://stackoverflow.com/questions/45123696/android-how-to-upload-video-in-chunks-using-okhttp


--------------------------------------------------------------------------------------------------------------------------------------------------------

 

 

 

이외의 작업하면서 알게된 자잘한것들..

 

// 전송 파일 종류 추출
private String getMimeType(String path) {
String extension = MimeTypeMap.getFileExtensionFromUrl(path);
return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
}
728x90
반응형