0

Need to implement on Android Webview on upload only for image, file accept ext: .png, .jpg, .jpeg. I have this code:

public class MainFragment extends Fragment {

private static final String TAG = MainFragment.class.getSimpleName();

public static final int INPUT_FILE_REQUEST_CODE = 1;
public static final String EXTRA_FROM_NOTIFICATION = "EXTRA_FROM_NOTIFICATION";

private WebView mWebView;
private ValueCallback<Uri[]> mFilePathCallback;
private String mCameraPhotoPath;


public MainFragment() {


}





@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_main, container, false);

    // Get reference of WebView from layout/activity_main.xml
    mWebView = (WebView) rootView.findViewById(R.id.fragment_main_webview);



        setUpWebViewDefaults(mWebView);

        // Check whether we're recreating a previously destroyed instance
        if(savedInstanceState!=null)

        {
            // Restore the previous URL and history stack
            mWebView.restoreState(savedInstanceState);
        }

        mWebView.setWebChromeClient(new

        WebChromeClient() {
            //The undocumented magic method override
            //Eclipse will swear at you if you try to put @Override here
            // For Android 3.0+


            public void openFileChooser (ValueCallback < Uri > uploadMsg) {

                ValueCallback mUploadMessage = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("image/*");
                getActivity().startActivityForResult(Intent.createChooser(i, "File Chooser"), 1000);

            }

            // For Android 3.0+

        public void openFileChooser(ValueCallback uploadMsg, String acceptType) {
            ValueCallback mUploadMessage = uploadMsg;
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("*/*");
            getActivity().startActivityForResult(
                    Intent.createChooser(i, "File Browser"),
                    1000);
        }

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

        }


        public boolean onShowFileChooser(
                WebView webView, ValueCallback<Uri[]> filePathCallback,
                WebChromeClient.FileChooserParams fileChooserParams) {
            if (mFilePathCallback != null) {
                mFilePathCallback.onReceiveValue(null);
            }
            mFilePathCallback = filePathCallback;

            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) {
                // Create the File where the photo should go
                File photoFile = null;
                try {
                    photoFile = createImageFile();
                    takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
                } catch (IOException ex) {
                    // Error occurred while creating the File
                    Log.e(TAG, "Unable to create Image File", ex);
                }

                // Continue only if the File was successfully created
                if (photoFile != null) {
                    mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
                    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                            Uri.fromFile(photoFile));
                } else {
                    takePictureIntent = null;
                }
            }

            Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
            contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
            contentSelectionIntent.setType("image/*");

            Intent[] intentArray;
            if (takePictureIntent != null) {
                intentArray = new Intent[]{takePictureIntent};
            } else {
                intentArray = new Intent[0];
            }

            Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
            chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
            chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);

            startActivityForResult(chooserIntent, INPUT_FILE_REQUEST_CODE);

            return true;
        }
    });

    // Load the local index.html file
    if(mWebView.getUrl() == null) {
        mWebView.loadUrl("http://www.mywebapp.com/");


    }



    return rootView;
}

/**
 * More info this method can be found at
 * http://developer.android.com/training/camera/photobasics.html
 *
 * @return
 * @throws IOException
 *
 *
 */
private File createImageFile() throws IOException {
    // Create an image file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = "JPEG_" + timeStamp + "_";

    File storageDir = Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_PICTURES);
    File imageFile = File.createTempFile(
            imageFileName,
            ".jpg",
            storageDir
    );
    return imageFile;
}

/**
 * Convenience method to set some generic defaults for a
 * given WebView
 *
 * @param webView
 */
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void setUpWebViewDefaults(WebView webView) {
    WebSettings settings = webView.getSettings();

    // Enable Javascript
    settings.setJavaScriptEnabled(true);

    // Use WideViewport and Zoom out if there is no viewport defined
    settings.setUseWideViewPort(true);
    settings.setLoadWithOverviewMode(true);

    // Enable pinch to zoom without the zoom buttons
    settings.setBuiltInZoomControls(true);

    if(Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB) {
        // Hide the zoom controls for HONEYCOMB+
        settings.setDisplayZoomControls(false);
    }

    // Enable remote debugging via chrome://inspect
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        WebView.setWebContentsDebuggingEnabled(true);
    }

    // We set the WebViewClient to ensure links are consumed by the WebView rather
    // than passed to a browser if it can
    mWebView.setWebViewClient(new WebViewClient());
}

@Override
public void onActivityResult (int requestCode, int resultCode, Intent data) {
    if(requestCode != INPUT_FILE_REQUEST_CODE || mFilePathCallback == null) {
        super.onActivityResult(requestCode, resultCode, data);
        return;
    }

    Uri[] results = null;

    // Check that the response is a good one
    if(resultCode == Activity.RESULT_OK) {
        if(data == null) {
            // If there is not data, then we may have taken a photo
            if(mCameraPhotoPath != null) {
                results = new Uri[]{Uri.parse(mCameraPhotoPath)};
            }
        } else {
            String dataString = data.getDataString();
            if (dataString != null) {
                results = new Uri[]{Uri.parse(dataString)};
            }
        }
    }

    mFilePathCallback.onReceiveValue(results);
    mFilePathCallback = null;
    return;
}

}

It work good for .jpg but how can create array with all extension i need?

zaGooX
  • 1
  • 3
  • You forgot to tell what tour code has to do with a webview. Or with uploading and for what you need an array with extensions and why you cannot make an array with extensions. – greenapps Mar 11 '15 at 12:35
  • hi mach, i create an input file on webview using Fragment, so i need that when user click input file uploading images only with format ext .png, .jpg. jpeg. – zaGooX Mar 11 '15 at 13:09
  • `i create an input file on webview` ? I have no idea what you are talking about. And further you did not tell when and where you call that function createImageFile(). For what do you need to create a file? – greenapps Mar 11 '15 at 13:32
  • i built an webapp and load it from webview using Fragment. Input file on html doesn't work so i create public void openFileChooser (ValueCallback < Uri > uploadMsg) for enable input file. User need to upload some image on my webapp. My question is: how can i able upload from webview of only image png, jpg and jpeg. – zaGooX Mar 11 '15 at 13:41
  • I repeat: `And further you did not tell when and where you call that function createImageFile()`? – greenapps Mar 11 '15 at 14:22
  • function is call on MainFragment public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) when user click on html input file. But my question is: how can fix code to upload ".jpg, .png, .jpeg"? – zaGooX Mar 11 '15 at 14:33
  • createImageFile() creates an empty file with a datetime in the filename. For what do you need that? `how can fix code to upload`. Sorry but you did not show any code for that so how can we tell how you could fix it? – greenapps Mar 11 '15 at 14:36
  • i need that user can upload all format image: png, jpg, jpeg. How can i do? – zaGooX Mar 11 '15 at 14:42
  • So you want to use openFileChooser of a WebChromeClient. And you did not mention that before. And you are constantly talking about uploading a file where you probably mean choosing a file. It seems that the user of your app can only choose a jpg file? If that is the problem then state it as such first. – greenapps Mar 11 '15 at 15:21
  • yes greenapps! Any solution to able user to choose png, jpeg, .jpg file? – zaGooX Mar 11 '15 at 17:09
  • Well i don't believe you. You ultimately use a normal intent where the user can choose for instance from the Gallery. The Gallery lets you pick .png's from the screen dumps. – greenapps Mar 11 '15 at 18:13
  • i'm trying like this: private File createImageFile() throws IOException { // Create an image file name String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); String imageFileName = "JPEG_" + timeStamp + "_"; String[] typeAllowed = {".jpg",".png",".jpeg"}; File storageDir = Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_PICTURES); File imageFile = File.createTempFile( imageFileName, typeAllowed[0], storageDir ); return imageFile; } – zaGooX Mar 11 '15 at 18:13
  • Again: for what do you need that code that creates an empty file? What does it have to do with the user picking a file? I asked that before. – greenapps Mar 11 '15 at 18:15
  • this is only way that i've found to enable input file from html on webview! – zaGooX Mar 11 '15 at 18:23
  • What do you mean by 'enabling input file`? We were talking about picking a file. Is there anything more? – greenapps Mar 11 '15 at 18:48
  • http://stackoverflow.com/questions/19882331/html-file-input-in-android-webview-android-4-4-kitkat – zaGooX Mar 11 '15 at 18:54

0 Answers0