Input type file does not work in webview

Asked

Viewed 1,682 times

7

I have an HTML page that has a form of upload imaging in Chrome on pc or any browser works but in my app that has a WebView that opens this page then click on Choose file he does nothing.

It is possible to fix this to choose a file or open the camera of the device ?

( just choose the file already solves )

Follow the code of my fragment:

public class F_Adm extends Fragment implements AdvancedWebView.Listener {

    private AdvancedWebView mWebView;

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

        mWebView = (AdvancedWebView) rootView.findViewById(R.id.webview);
        mWebView.setListener(getActivity(), this);

        mWebView.loadUrl("http://desapegogames.com.br/area-administrativa");

        return rootView;
    }

    @SuppressLint("NewApi")
    @Override
    public void onResume() {
        super.onResume();
        mWebView.onResume();
    }

    @SuppressLint("NewApi")
    @Override
    public void onPause() {
        mWebView.onPause();
        super.onPause();
    }

    @Override
    public void onDestroy() {
        mWebView.onDestroy();
        super.onDestroy();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        mWebView.onActivityResult(requestCode, resultCode, intent);
    }

    @Override
    public void onPageStarted(String url, Bitmap favicon) {
    }

    @Override
    public void onPageFinished(String url) {
    }

    @Override
    public void onPageError(int errorCode, String description, String failingUrl) {
        mWebView.loadUrl("file:///android_asset/offline.html");
    }

    @Override
    public void onDownloadRequested(String url, String suggestedFilename, String mimeType, long contentLength, String contentDisposition, String userAgent) {
    }

    @Override
    public void onExternalPageRequest(String url) {
    }
}
  • you want your website have the possibility to open a method in your android code?

  • nay. I just want to upload files by input Tyle='file' that has in an html page so by my webview does not work but by cell phone Chrome yes.

  • The webview javascritp is enabled?

  • yes ta active. it even opens to select the file but when you select it does not fill in the input

  • tried switching to this https://github.com/delight-im/Android-AdvancedWebView tbm from the same thing you choose the file and the field is not filled.

  • It’s been a long time since I’ve had one webview but I remember I had a similar case and needed to import the engine Webkit, with this my webview ran as if it were the Chrome. I don’t know if it’s your solution, but anything you tell me.

  • Have you seen the answers to this question in the Soen?

  • tried tbm use i Webkit from Chrome and did not rolled I will post my Cod here.

Show 3 more comments

1 answer

7


I will assist you according to the documentation of Webview. Following image scheme of the visual component WebView:

inserir a descrição da imagem aqui

Defining variables:

private static final String TAG = TestActivity.class.getSimpleName();
public static final int INPUT_FILE_REQUEST_CODE = 1;
private WebView meuWebView;
private ValueCallback<Uri[]> mFilePathCallback;
private String diretorioFotoImagem;

Defining a method for temporarily storing image armazenarImagemTemp():

 private File armazenarImagemTemp() 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,  /* prefix */
            ".jpg",         /* suffix */
            storageDir      /* directory */
    );
    return imageFile;
}

Defining a method to adapt the default settings of WebView with the name setWebview:

 private void setWebview(WebView webView) {
    WebSettings set = webView.getSettings();

    // habilita javascript
    set.setJavaScriptEnabled(true);

    if(Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB) {
        // oculta zoom no sdk HONEYCOMB+
        set.setDisplayZoomControls(false);
    }

    // habilita debugging remoto via chrome {inspect}
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        WebView.setWebContentsDebuggingEnabled(true);
    }
    meuWebView.setWebViewClient(new WebViewClient());
}

There can only be one method onActivityResult() in each Activity. This method is called after each call to startActivityForResult. When calling the method startActivityForResult is passed, in the second parameter, a requestCode. Behold:

@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;

    // verifica se a resposta esta ok com a variável estática {RESULT_OK} do Activity
    if(resultCode == Activity.RESULT_OK) {
        if(data == null) {
            // se não houver dados solicitará que tire uma foto
            if(diretorioFotoImagem != null) {
                results = new Uri[]{Uri.parse(diretorioFotoImagem)};
            }
        } else {
            String dataString = data.getDataString();
            if (dataString != null) {
                results = new Uri[]{Uri.parse(dataString)};
            }
        }
    }

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

Ending with the onCreate() which is the method responsible for loading the layouts and other start-up operations.

 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_test);

    // referencia o webview no layout/activity_main.xml
    meuWebView = (WebView) findViewById(R.id.webview);

    // define as configurações basicas
    setWebview(meuWebView);

    if (savedInstanceState != null) {
        // retaura o webview
        meuWebView.restoreState(savedInstanceState);
    }

    meuWebView.setWebChromeClient(new WebChromeClient() {
        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(getPackageManager()) != null) {
                // cria local onde a foto deve ir
                File photoFile = null;
                try {
                    photoFile = armazenarImagemTemp();
                    takePictureIntent.putExtra("PhotoPath", diretorioFotoImagem);
                } 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) {
                    diretorioFotoImagem = "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;
        }
    });

    // carrega a URL
    if(meuWebView.getUrl() == null) {
        meuWebView.loadUrl("http://192.168.0.3:8080/api.finan.com/");
    }
} 

Obs.: do not forget to create the WebView in his XLM.

To improve the code, check out more details in the documentation.

EDIT

How you pointed out in the comments the question of the possibility to work on Fragment, do the download here of the adaptation basic to work.

  • only one thing if possible can guide how to adapt this your Cod to run within a Fragment? or if you can send me an ex please?

  • 1

    @Jasarorion basically you have to check two things, that would be the question of the view, because instead of this, it is put getActivity() and the question of onActivityResult() to your Fragment that is a little different. Try to make the modifications, if you can not, I can check later for you. You got to test?!

  • ok today anoite I’ll move on that and I’ll report back . thank you very much

  • 1

    @Jasarorion made here for you, I will make available on a link can be?! Otherwise the answer gets too big!

  • Thank you so much thank you . I am beginner on android this is my first app a look at the dispassionations.com.br

  • I am already testing. I have one last question. in case of offline or error where I insert the option to load an html file that is there in asstes?

  • @Jasarorion my dear, perhaps you’d better add another question, because in this case it’s already out of context.

  • 1

    guy worked out here thank you very much I added you in skype if you have time would like to know how much is your time for consulting.

  • 1

    I managed to implement the error tbm hugs. as soon as release I already reward you for the help thank you very much again.

  • 1

    @Jasarorion very well expensive. In my spare time I try to help people, repaying for the many doubts I have had and helped me.

Show 5 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.