본문 바로가기

IT/Android

WebView를 이용한 파일 첨부 하기

웹뷰에선 버전별로 파일 첨부 코드를 생성해 줘야 한다.

*다른 버전은 문제 없는거 같은데 4.2.2 버전에서는 안된다.(이유는 모르겠다.)


permission 추가

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />


변수 선언

private static final int FILECHOOSER_RESULTCODE   = 1;
private final static int FILECHOOSER_LOLLIPOP_REQ_CODE = 2;
private ValueCallback<Uri> mUploadMessage = null;
private ValueCallback<Uri[]> filePathCallbackLollipop;


WebView setWebChromeClient 부분

// For Android 3.0-
@SuppressWarnings("unused")
public void openFileChooser(ValueCallback<Uri> uploadMsg) {
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
//i.setType("image/*");
i.setType("*/*");
startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);
}

// For Android 3.0+
@SuppressWarnings("unused")
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("*/*");
startActivityForResult(Intent.createChooser(i, "File Browser"), FILECHOOSER_RESULTCODE);
}

// For Android 4.1+
@SuppressWarnings("unused")
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
//i.setType("image/*");
i.setType("*/*");
startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);
}

// For Android 5.0+
public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback,
WebChromeClient.FileChooserParams fileChooserParams) {
Log.d("MainActivity", "5.0+");
if (filePathCallbackLollipop != null) {
filePathCallbackLollipop.onReceiveValue(null);
filePathCallbackLollipop = null;
}
filePathCallbackLollipop = filePathCallback;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_LOLLIPOP_REQ_CODE);

return true;
}


결과값 처리

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == FILECHOOSER_RESULTCODE) {
if (null == mUploadMessage)
return;
Uri result = intent == null || resultCode != RESULT_OK ? null : intent.getData();
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
} else if (requestCode == FILECHOOSER_LOLLIPOP_REQ_CODE) {
if (filePathCallbackLollipop == null) return ;
filePathCallbackLollipop.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, intent));
filePathCallbackLollipop = null;
}
}


'IT > Android' 카테고리의 다른 글

Android Studio 설치  (0) 2015.08.25
Android 액정크기에 맞게 자동화면 맞추기  (0) 2011.10.27
fill_parent와 Wrap_content의 차이  (0) 2011.10.26
DroidDraw(안드로이드 UI 개발툴)  (2) 2011.01.28
센서 데이터 처리과정  (1) 2011.01.24