简体   繁体   English

在Android Webview上上传文件

[英]File upload on android webview

Am a novice at android app development, trying to develop a web view app, but cant seem to get the file upload working... Please help 我是android应用程序开发的新手,正在尝试开发网络视图应用程序,但似乎无法使文件上传正常进行。请帮助

Here is my web view code 这是我的网络视图代码

package com.example.project;

public class WebActivity extends Activity { 公共类WebActivity扩展了Activity {

private WebView wv;

private String LASTURL = "";

Menu myMenu = null;
private ProgressDialog dialog;
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;  
 }
 }  




/**
 * Called when the activity is first created.
 */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.getWindow().requestFeature(Window.FEATURE_PROGRESS);

    if (!InternetConnection.checkNetworkConnection(this)) {
        showAlert(this, "No Data Connection", "This Application requires an internet connection");
    } else {

        setContentView(R.layout.web_view);

        wv = (WebView) findViewById(R.id.web_view);

        WebSettings webSettings = wv.getSettings();
        webSettings.setSavePassword(true);
        webSettings.setSaveFormData(true);
        webSettings.setJavaScriptEnabled(true);
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setSupportZoom(false);


        final Activity activity = this;

        // start ProgressDialog with "Page loading..."
        dialog = new ProgressDialog(activity);
        dialog.setMessage("Loading...");
        dialog.setIndeterminate(true);
        dialog.setCancelable(true);
        dialog.show();

        wv.setWebChromeClient(new WebChromeClient() {


            public void onProgressChanged(WebView view, int progress) {
                // set address bar and progress
                // activity.setTitle( " " + LASTURL );
                // activity.setProgress( progress * 100 );

                if (progress == 100) {
                    // stop ProgressDialog after loading
                    dialog.dismiss();

                    // activity.setTitle( " " + LASTURL );
                }
            }
        });


        wv.setWebViewClient(new WebViewClient() {
            public void onReceivedError(WebView view, int errorCode,
                    String description, String failingUrl) {
                Toast.makeText(getApplicationContext(),
                        "Error: " + description + " " + failingUrl,
                        Toast.LENGTH_LONG).show();
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url.indexOf("mycitygist") <= 0) {
                    // the link is not for a page on my site, so launch
                    // another Activity that handles URLs
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri
                            .parse(url));
                    startActivity(intent);
                    return true;
                }
                return false;
            }
            /*****************************************************************/
            /*  Here the load of the page will start so we must launch the  */
            /*  ProgressDialog                                              */
            /*****************************************************************/                                             
            public void onPageStarted(WebView view, String url,
                    Bitmap favicon) {

                // this is what we should do
                dialog.setMessage("Loading...");
                dialog.setIndeterminate(true);
                dialog.setCancelable(true);
                dialog.show();
                //
                LASTURL = url;
                view.getSettings().setLoadsImagesAutomatically(true);
                view.getSettings().setBuiltInZoomControls(true);
            }
            /*****************************************************************/
            /*  Here the load of the page will stop so we must dismiss the  */
            /*  ProgressDialog                                              */
            /*****************************************************************/ 
            public void onPageFinished(WebView view, String url) {
                // this is what we should do
                dialog.dismiss();

            }
        });
        wv.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
        wv.setScrollbarFadingEnabled(false);
        wv.loadUrl("http://app.mycitygist.com/overview/");

    }

}

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if ((keyCode == KeyEvent.KEYCODE_BACK) && wv.canGoBack()) {
        wv.goBack();
        return true;
    }
    return super.onKeyDown(keyCode, event);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);

    this.myMenu = menu;
    MenuItem item = menu.add(0, 1, 0, "Home");
    item.setIcon(R.drawable.home);
    MenuItem item2 = menu.add(0, 2, 0, "Back");
    item2.setIcon(R.drawable.arrowleft);
    MenuItem item3 = menu.add(0, 3, 0, "Reload");
    item3.setIcon(R.drawable.s);
    MenuItem item4 = menu.add(0, 4, 0, "Share");
    item4.setIcon(R.drawable.share);
    MenuItem item5 = menu.add(0, 5, 0, "Rate");
    item5.setIcon(R.drawable.vote);
    MenuItem item6 = menu.add(0, 6, 0, "Exit");
    item6.setIcon(R.drawable.close);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case 1:
        wv.loadUrl("http://http://app.mycitygist.com/overview/");
        break;
    case 2:
        if (wv.canGoBack()) {
            wv.goBack();
        }
        break;
    case 3:
        wv.loadUrl(LASTURL);
        break;
    case 4:
        Intent sharingIntent = new Intent(Intent.ACTION_SEND);
        sharingIntent.setType("plain/text");
        sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, "Check out this app I found.");
        startActivity(Intent.createChooser(sharingIntent,"Share using"));
        break;
    case 5:

        Intent marketIntent2 = new Intent(Intent.ACTION_VIEW, Uri.parse(
                "http://market.android.com/details?id=" + getPackageName()));
              startActivity(marketIntent2);
            break;

    case 6:
        finish();
        break;

    }

    return true;
}



/**
 * Display a simple alert dialog with the given text and title.
 * 
 * @param context
 *            Android context in which the dialog should be displayed
 * @param title
 *            Alert dialog title
 * @param text
 *            Alert dialog message
 */
public void showAlert(Context context, String title, String text) {
    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);

    // set title
    alertDialogBuilder.setTitle( title);

    // set dialog message
    alertDialogBuilder
    .setMessage( text )
    .setCancelable(false)
    .setPositiveButton("OK",new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog,int id) {
            // if this button is clicked, close
            // current activity
            finish();
        }
    })
    .create().show();

}

} }

So i added this code under wv. 所以我在wv下添加了此代码。 setWebChromeClient //The undocumented magic method override setWebChromeClient //未记录的魔术方法覆盖
//Eclipse will swear at you if you try to put @Override here //如果您尝试将@Override放在此处,Eclipse会发誓
// For Android 3.0+ public void openFileChooser(ValueCallback uploadMsg) { //对于Android 3.0以上版本,public void openFileChooser(ValueCallback uploadMsg){

         mUploadMessage = uploadMsg;  
         Intent i = new Intent(Intent.ACTION_GET_CONTENT);  
         i.addCategory(Intent.CATEGORY_OPENABLE);  
         i.setType("image/*");  
         WebActivity.this.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("*/*");
        WebActivity.this.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/*");  
            WebActivity.this.startActivityForResult( Intent.createChooser( i, "File Chooser" ), WebActivity.FILECHOOSER_RESULTCODE );

        }

    });  


    setContentView(wv);  


    }

    }

Cant seem to compile the app with this line of code included, buh without it, d app compiles fine and works well but without file upload capabilities Cant似乎使用包含的这一行代码来编译应用程序,但是没有它,d应用程序可以很好地编译并且运行良好,但是没有文件上传功能

Please see this code , i am using file choose button to select file and later will use upload in my jsp 请参阅此代码,我正在使用“文件选择”按钮来选择文件,以后将在我的jsp中使用上载

AndroidManifest.xml:
-------------------
 <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.MANAGE_DOCUMENTS"
        tools:ignore="ProtectedPermissions" />
MainActivity.java:
--------------------

package com.example.satis.image_text;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MainActivity extends AppCompatActivity {
    private static final int INPUT_FILE_REQUEST_CODE = 1;
    private static final int FILECHOOSER_RESULTCODE = 1;
    private static final String TAG = MainActivity.class.getSimpleName();
    private WebView webView;
    private WebSettings webSettings;
    private ValueCallback<Uri> mUploadMessage;
    private Uri mCapturedImageURI = null;
    private ValueCallback<Uri[]> mFilePathCallback;
    private String mCameraPhotoPath;
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            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;
        } else if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
            if (requestCode != FILECHOOSER_RESULTCODE || mUploadMessage == null) {
                super.onActivityResult(requestCode, resultCode, data);
                return;
            }
            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 = data == null ? mCapturedImageURI : data.getData();
                    }
                } catch (Exception e) {
                    Toast.makeText(getApplicationContext(), "activity :" + e,
                            Toast.LENGTH_LONG).show();
                }
                mUploadMessage.onReceiveValue(result);
                mUploadMessage = null;
            }
        }
        return;
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        webView = (WebView) findViewById(R.id.webview);
        webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setAllowFileAccess(true);
        webView.setWebViewClient(new Client());
        webView.setWebChromeClient(new ChromeClient());
        if (Build.VERSION.SDK_INT >= 19) {
            webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
        }
        else if(Build.VERSION.SDK_INT >=11 && Build.VERSION.SDK_INT < 19) {
            webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        }
        webView.loadUrl("http://ec2-107-23-105-200.compute-1.amazonaws.com:8080/Action_file.jsp"); //change with your website
    }
    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,  /* prefix */
                ".jpg",         /* suffix */
                storageDir      /* directory */
        );
        return imageFile;
    }
    public class ChromeClient extends WebChromeClient {
        // For Android 5.0
        public boolean onShowFileChooser(WebView view, ValueCallback<Uri[]> filePath, WebChromeClient.FileChooserParams fileChooserParams) {
            // Double check that we don't have any existing callbacks
            if (mFilePathCallback != null) {
                mFilePathCallback.onReceiveValue(null);
            }
            mFilePathCallback = filePath;
            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            if (takePictureIntent.resolveActivity(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;
        }
        // openFileChooser for Android 3.0+
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
            mUploadMessage = uploadMsg;
            // Create AndroidExampleFolder at sdcard
            // Create AndroidExampleFolder at sdcard
            File imageStorageDir = new File(
                    Environment.getExternalStoragePublicDirectory(
                            Environment.DIRECTORY_PICTURES)
                    , "AndroidExampleFolder");
            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);
        }
        // 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);
        }
    }
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // Check if the key event was the Back button and if there's history
        if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
            webView.goBack();
            return true;
        }
        // If it wasn't the Back key or there's no web page history, bubble up to the default
        // system behavior (probably exit the activity)
        return super.onKeyDown(keyCode, event);
    }
    public class Client extends WebViewClient {
        ProgressDialog progressDialog;
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            // If url contains mailto link then open Mail Intent
            if (url.contains("mailto:")) {
                // Could be cleverer and use a regex
                //Open links in new browser
                view.getContext().startActivity(
                        new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                // Here we can open new activity
                return true;
            }else {
                // Stay within this webview and load url
                view.loadUrl(url);
                return true;
            }
        }
        //Show loader on url load
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            // Then show progress  Dialog
            // in standard case YourActivity.this
            if (progressDialog == null) {
                progressDialog = new ProgressDialog(MainActivity.this);
                progressDialog.setMessage("Loading...");
                progressDialog.show();
            }
        }
        // Called when all page resources loaded
        public void onPageFinished(WebView view, String url) {
            try {
                // Close progressDialog
                if (progressDialog.isShowing()) {
                    progressDialog.dismiss();
                    progressDialog = null;
                }
            } catch (Exception exception) {
                exception.printStackTrace();
            }
        }
    }
}

    enter code here

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM