在WebView android中启用附件

时间:2014-12-15 05:38:06

标签: android webview attachment

我一直试图让我的应用让用户从我的应用内部上传webview内的locel驱动器上的图片。

我使用此代码执行弹出式webview:

package com.webview.test;

import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.Button;

public class WebViewDialogActivity extends Activity 
{
    //Create a dialog object, that will contain the WebView
    private Dialog webViewDialog;
    //a WebView object to display a web page
    private WebView webView;

    //The button to launch the WebView dialog
    private Button btLaunchWVD;
    //The button that closes the dialog
    private Button btClose;


    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sliding_menu_categories);

        //Inflate the btLaunchWVD button from the 'main.xml' layout file
        btLaunchWVD = (Button) findViewById(R.id.bt_launchwvd);

        //Set the 35. OnClickListener for the launch button
        btLaunchWVD.setOnClickListener(new OnClickListener() 
        {
            @Override
            public void onClick(View v) 
            {
                //Display the WebView dialog
                webViewDialog.show();
            }
        });

        //Create a new dialog
        webViewDialog = new Dialog(this);
        //Remove the dialog's title
        webViewDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        //Inflate the contents of this dialog with the Views defined at 'webviewdialog.xml'
        webViewDialog.setContentView(R.layout.webviewdialog);
        //With this line, the dialog can be dismissed by pressing the back key
        webViewDialog.setCancelable(true);

        //Initialize the Button object with the data from the 'webviewdialog.xml' file 
        btClose = (Button) webViewDialog.findViewById(R.id.bt_close);
        //Define what should happen when the close button is pressed.
        btClose.setOnClickListener(new OnClickListener() 
        {
            @Override
            public void onClick(View v) 
            {
                //Dismiss the dialog
                webViewDialog.dismiss();
            }
        });

        //Initialize the WebView object with data from the 'webviewdialog.xml' file 
        webView = (WebView) webViewDialog.findViewById(R.id.wb_webview);
        //Scroll bars should not be hidden
        webView.setScrollbarFadingEnabled(false);
        //Disable the horizontal scroll bar
        webView.setHorizontalScrollBarEnabled(false);
        //Enable JavaScript
        webView.getSettings().setJavaScriptEnabled(true);
        //Set the user agent
        webView.getSettings().setUserAgentString("Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.4) Gecko/20100101 Firefox/4.0");
        //Clear the cache
        webView.clearCache(true);
        //Make the webview load the specified URL
        String url = "http://phppot.com/demo/jquery-contact-form-with-attachment-using-php/";

        webView.loadUrl(url);


    }

}

请告诉我应用代码需要哪些修复。

2 个答案:

答案 0 :(得分:0)

以下是已编辑的工作代码:

package com.example.anandsingh.webproject;

import com.example.testweb.R;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

public class TestWeb extends Activity {
/** Called when the activity is first created. */

WebView web;

ProgressBar progressBar;

private ValueCallback<Uri> mUploadMessage;

private final static int FILECHOOSER_RESULTCODE = 1;

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

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    web = (WebView) findViewById(R.id.webView1);

    web = new WebView(this);
    web.getSettings().setJavaScriptEnabled(true);
    web.setScrollbarFadingEnabled(false);
    // Disable the horizontal scroll bar
    web.setHorizontalScrollBarEnabled(false);
    // Enable JavaScript
    web.getSettings().setJavaScriptEnabled(true);
    // Set the user agent
    web.getSettings().setUserAgentString("Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.4) Gecko/20100101 Firefox/4.0");
    // Clear the cache
    web.clearCache(true);
    // Make the webview load the specified URL
    String url = "http://phppot.com/demo/jquery-contact-form-with-attachment-using-php/";

    web.loadUrl(url);
    web.setWebViewClient(new myWebClient());
    web.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) {

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

        }

        // For Android 3.0+
        public void openFileChooser(ValueCallback 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
        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/*");
            startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);

        }

    });

    setContentView(web);

}

public class myWebClient extends WebViewClient {
    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        // TODO Auto-generated method stub
        super.onPageStarted(view, url, favicon);
    }

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        // TODO Auto-generated method stub

        view.loadUrl(url);
        return true;

    }

    @Override
    public void onPageFinished(WebView view, String url) {
        // TODO Auto-generated method stub
        super.onPageFinished(view, url);
    }
}

// flipscreen not loading again
@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
}
}

答案 1 :(得分:0)

尝试实现WebChromeClient以从本地选择图像:

private Uri mCapturedImageURI;
private int FILECHOOSER_RESULTCODE=11;
private ValueCallback<Uri> mUploadMessage;

webView.setWebChromeClient(new WebChromeClient() {

   // openFileChooser for Android 3.0+
   public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType){

        try{
            mUploadMessage = uploadMsg;
            // Create AndroidExampleFolder at sdcard

            File imageStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), getString(R.string.app_name));

            if (!imageStorageDir.exists()) {
                // Create AndroidExampleFolder at sdcard
                imageStorageDir.mkdirs();
            }

            // Create camera captured image file path and name
            File file = new File(imageStorageDir + File.separator + "IMG_" + String.valueOf(System.currentTimeMillis())+ ".jpg");

            mCapturedImageURI = Uri.fromFile(file);

            // Camera capture image intent
            final Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
            captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("image/*");

            // Create file chooser intent
            Intent chooserIntent = Intent.createChooser(i,"Image Chooser");
            // Set camera intent to file chooser
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Parcelable[] { captureIntent });
            // On select image call onActivityResult method of activity
            startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE);

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

   }

   // openFileChooser for Android < 3.0
   public void openFileChooser(ValueCallback<Uri> uploadMsg){
        openFileChooser(uploadMsg, "");
   }

   //openFileChooser for other Android versions
   public void openFileChooser(ValueCallback<Uri> uploadMsg,String acceptType,String capture) {
        openFileChooser(uploadMsg, acceptType);
   }

   // The webPage has 2 filechoosers and will send a
   // console message informing what action to perform,
   // taking a photo or updating the file

   public boolean onConsoleMessage(ConsoleMessage cm) {
        onConsoleMessage(cm.message(), cm.lineNumber(), cm.sourceId());
        return true;
   }

   public void onConsoleMessage(String message, int lineNumber, String sourceID) {
        //Log.d("androidruntime", "Show console messages, Used for debugging: " + message);
   }
});

上传所选图片onActivityResult:

 @Override
 protected void onActivityResult(int requestCode, int resultCode,Intent intent) {
    if(requestCode==FILECHOOSER_RESULTCODE){
       if (null == this.mUploadMessage) {
           return;
       }

       Uri result=null;
       try{
          if (resultCode != RESULT_OK) {
              result = null;
          } else {
              // retrieve from the private variable if the intent is null
              result = intent == null ? mCapturedImageURI : intent.getData();
          }
        }
        catch(Exception e)
        {
           e.printStackTrace();
        }
        mUploadMessage.onReceiveValue(result);
        mUploadMessage = null;
     }
}