webview 上传

来源:互联网 发布:spyder python 编辑:程序博客网 时间:2024/06/03 21:14
package com.example.choosefile;

import java.io.File;

import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.Window;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MainActivity extends Activity {
    private WebView webView;
    private String urlStart = "";
    protected ValueCallback<Uri> mUploadMessage;
    protected int FILECHOOSER_RESULTCODE = 1;
    private String mCameraFilePath;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.d("返回:", mCameraFilePath);
        Log.d("返回:", "mUploadMessage: " + mUploadMessage.toString());
        // if (requestCode == FILECHOOSER_RESULTCODE) {
        if (null == mUploadMessage)
            return;
        Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
        if (result == null && data == null && resultCode == Activity.RESULT_OK) {
            File cameraFile = new File(mCameraFilePath);
            if (cameraFile.exists()) {
                result = Uri.fromFile(cameraFile);
                sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, result));
            }
        }
        mUploadMessage.onReceiveValue(result);
        mUploadMessage = null;
        // }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
            requestWindowFeature(Window.FEATURE_NO_TITLE);
            setContentView(R.layout.activity_main);
            setFinishOnTouchOutside(false);
            webView = (WebView) findViewById(R.id.webView);

            webView.getSettings().setJavaScriptEnabled(true);
            webView.getSettings().setLoadWithOverviewMode(true);
            webView.getSettings().setAllowFileAccess(true);
            webView.loadUrl(urlStart);
        
            webView.setWebChromeClient(new WebChromeClient() {

            // For Android 3.0+
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
                if (mUploadMessage != null)
                    return;
                mUploadMessage = uploadMsg;
                startActivityForResult(createDefaultOpenableIntent(), FILECHOOSER_RESULTCODE);
            }

            // For Android < 3.0
            @SuppressWarnings("unused")
            public void openFileChooser(ValueCallback<Uri> uploadMsg) {
                openFileChooser(uploadMsg, "");
            }

            // For Android > 4.1.1
            @SuppressWarnings("unused")
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
                openFileChooser(uploadMsg, "");
            }

        });
            webView.setWebViewClient(new WebViewClient(){
                @Override

                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    
                    if (url.indexOf("tel:") > -1) {
                        //支持打电话
                        startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse(url)));
                        return true;
                    } else {
                        //调用本webkit
                        view.loadUrl(url);
                        return true;
                    }

                }
            });
            webView.loadUrl("http://superc102.vicp.cc:8080/EBeautyPortal");
        
    }

    private Intent createDefaultOpenableIntent() {
        // Create and return a chooser with the default OPENABLE
        // actions including the camera, camcorder and sound
        // recorder where available.
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("image/*");

        Intent chooser = createChooserIntent(createCameraIntent());
        chooser.putExtra(Intent.EXTRA_INTENT, i);
        return chooser;
    }

    private Intent createChooserIntent(Intent... intents) {
        Intent chooser = new Intent(Intent.ACTION_CHOOSER);
        chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, intents);
        chooser.putExtra(Intent.EXTRA_TITLE, "请选择");
        return chooser;
    }

    private Intent createCameraIntent() {
        // 注意:此处代码主要目的是将拍照文件保存在 browser-photos 文件夹下(非系统默认文件夹)
        // 如不需要这样处理,可以简化代码

        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File externalDataDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
        File cameraDataDir = new File(externalDataDir.getPath() + "/Images/");
        cameraDataDir.mkdirs();
        mCameraFilePath = cameraDataDir.getPath()+ System.currentTimeMillis() + ".jpg";
        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(mCameraFilePath)));
        return cameraIntent;
    }

}





权限:<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
      <uses-permission android:name="android.permission.INTERNET" />





二:------------------------------------------------------------------------------------------

package com.example.ebeauty;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.text.TextUtils;
import android.util.Log;

public class FileUtils {

    /**
     * 把图片压缩到200K
     *
     * @param oldpath
     *            压缩前的图片路径
     * @param newPath
     *            压缩后的图片路径
     * @return
     */
    /**
     * 把图片压缩到200K
     *
     * @param oldpath
     *            压缩前的图片路径
     * @param newPath
     *            压缩后的图片路径
     * @return
     */
    public static File compressFile(String oldpath, String newPath) {
        Bitmap compressBitmap = FileUtils.decodeFile(oldpath);
        Bitmap newBitmap = ratingImage(oldpath, compressBitmap);
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        newBitmap.compress(CompressFormat.PNG, 100, os);
        byte[] bytes = os.toByteArray();
        
        File file = null ;
        try {
            file = FileUtils.getFileFromBytes(bytes, newPath);
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            if(newBitmap != null ){
                if(!newBitmap.isRecycled()){
                    newBitmap.recycle();
                }
                newBitmap  = null;
            }
            if(compressBitmap != null ){
                if(!compressBitmap.isRecycled()){
                    compressBitmap.recycle();
                }
                compressBitmap  = null;
            }
        }
        return file;
    }
    
    private static Bitmap ratingImage(String filePath,Bitmap bitmap){
        int degree = readPictureDegree(filePath);
        return rotaingImageView(degree, bitmap);
    }
    
    /**
     *  旋转图片
     * @param angle
     * @param bitmap
     * @return Bitmap
     */
    public static Bitmap rotaingImageView(int angle , Bitmap bitmap) {
        //旋转图片 动作
        Matrix matrix = new Matrix();;
        matrix.postRotate(angle);
        System.out.println("angle2=" + angle);
        // 创建新的图片
        Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
                bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        return resizedBitmap;
    }
    
    /**
     * 读取图片属性:旋转的角度
     * @param path 图片绝对路径
     * @return degree旋转的角度
     */
    public static int readPictureDegree(String path) {
        int degree  = 0;
        try {
                ExifInterface exifInterface = new ExifInterface(path);
                int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
                switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                        degree = 90;
                        break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                        degree = 180;
                        break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                        degree = 270;
                        break;
                }
        } catch (IOException e) {
                e.printStackTrace();
        }
        return degree;
    }

    /**
     * 把字节数组保存为一个文件
     *
     * @param b
     * @param outputFile
     * @return
     */
    public static File getFileFromBytes(byte[] b, String outputFile) {
        File ret = null;
        BufferedOutputStream stream = null;
        try {
            ret = new File(outputFile);
            FileOutputStream fstream = new FileOutputStream(ret);
            stream = new BufferedOutputStream(fstream);
            stream.write(b);
        } catch (Exception e) {
            // log.error("helper:get file from byte process error!");
            e.printStackTrace();
        } finally {
            if (stream != null) {
                try {
                    stream.close();
                } catch (IOException e) {
                    // log.error("helper:get file from byte process error!");
                    e.printStackTrace();
                }
            }
        }
        return ret;
    }

    /**
     * 图片压缩
     *
     * @param fPath
     * @return
     */
    public static Bitmap decodeFile(String fPath) {
        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inJustDecodeBounds = true;
        opts.inDither = false; // Disable Dithering mode
        opts.inPurgeable = true; // Tell to gc that whether it needs free
        opts.inInputShareable = true; // Which kind of reference will be used to
        BitmapFactory.decodeFile(fPath, opts);
        final int REQUIRED_SIZE = 200;
        int scale = 1;
        if (opts.outHeight > REQUIRED_SIZE || opts.outWidth > REQUIRED_SIZE) {
            final int heightRatio = Math.round((float) opts.outHeight
                    / (float) REQUIRED_SIZE);
            final int widthRatio = Math.round((float) opts.outWidth
                    / (float) REQUIRED_SIZE);
            scale = heightRatio < widthRatio ? heightRatio : widthRatio;//
        }
        Log.i("scale", "scal ="+ scale);
        opts.inJustDecodeBounds = false;
        opts.inSampleSize = scale;
        Bitmap bm = BitmapFactory.decodeFile(fPath, opts).copy(Config.ARGB_8888, false);
        return bm;
    }
    
    
    
    /**
     * 创建目录
     * @param path
     */
    public static void setMkdir(String path)
    {
        File file = new File(path);
        if(!file.exists())
        {
            file.mkdirs();
            Log.e("file", "目录不存在  创建目录    ");
        }else{
            Log.e("file", "目录存在");
        }
    }
    
    /**
     * 获取目录名称
     * @param url
     * @return FileName
     */
    public static String getFileName(String url)
    {
        int lastIndexStart = url.lastIndexOf("/");
        if(lastIndexStart!=-1)
        {
            return url.substring(lastIndexStart+1, url.length());
        }else{
            return null;
        }
    }
    
    /**
     * 删除该目录下的文件
     *
     * @param path
     */
    public static void delFile(String path) {
        if (!TextUtils.isEmpty(path)) {
            File file = new File(path);
            if (file.exists()) {
                file.delete();
            }
        }
    }
}

--------------------------

package com.example.ebeauty;


import java.io.File;




import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Window;
import android.webkit.ValueCallback;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.Toast;

public class MainActivity extends Activity {

private WebView webView;
private String urlStart = "http://superc102.vicp.cc:8080/EBeautyPortal";

//File choser parameters
//private static final int FILECHOOSER_RESULTCODE   = 2888;
private static final int FILECHOOSER_RESULTCODE = 22888;

private static final int REQ_CAMERA = FILECHOOSER_RESULTCODE+1;
/*private static final int REQ_CHOOSE = REQ_CAMERA+1;*/
private ValueCallback<Uri> mUploadMessage;

//Camera parameters
    private Uri mCapturedImageURI = null;
    String mCameraFilePath = "";
@SuppressLint("SetJavaScriptEnabled")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.activity_main);
    setFinishOnTouchOutside(false);
    webView = (WebView) findViewById(R.id.webView);

    webView.getSettings().setJavaScriptEnabled(true);
    webView.getSettings().setLoadWithOverviewMode(true);
    webView.getSettings().setAllowFileAccess(true);
    webView.loadUrl(urlStart);
    webView.setWebViewClient(new webViewClient(){
        @Override

        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            
            if (url.indexOf("tel:") > -1) {
                //支持打电话
                startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse(url)));
                return true;
            } else {
                //调用本webkit
                view.loadUrl(url);
                return true;
            }

        }
    });
    webView.setWebChromeClient(new WebChromeClient() {
        ///------------------
        // 扩展支持alert事件  
         //捕获网页的alert提示
        public boolean onJsAlert(WebView view, String url, String message, JsResult result)
           {
           // TODO Auto-generated method stub
              //对alert的简单封装
             new AlertDialog.Builder(MainActivity.this).  
                     setTitle("易优美提示").setMessage(message).setPositiveButton("确定",new DialogInterface.OnClickListener() {  
                     @Override  
                     public void onClick(DialogInterface arg0, int arg1) {  
                                  //TODO  
                      }  
                     }).create().show();  
             //处理来自用户的确认回复。        
             result.confirm();  
               return true;
           }
        // 3.0 + 调用这个方法
        public void openFileChooser(ValueCallback<Uri> uploadMsg,String acceptType) {
        mUploadMessage = uploadMsg;//mUploadMessage 全局变量
        //跳转系统相册In
        selectImage();
                                                                                                                                           
        }
        
        // For Android  > 4.1.1
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
            openFileChooser(uploadMsg, acceptType);
        }

        // Android < 3.0 调用这个方法
        public void openFileChooser(ValueCallback<Uri> uploadMsg) {
            openFileChooser(uploadMsg, "");

        }
 });
}
//----------------------------
@Override


/**
 * 选择照片后结束
 *
 * @param data
 */
/*private Uri afterChosePic(Intent data) {

    // 获取图片的路径:
    String[] proj = { MediaStore.Images.Media.DATA };
    // 好像是android多媒体数据库的封装接口,具体的看Android文档
    Cursor cursor = managedQuery(data.getData(), proj, null, null, null);
    if(cursor == null ){
        Toast.makeText(this, "上传的图片仅支持png或jpg格式",Toast.LENGTH_SHORT).show();
        return null;
    }
    // 按我个人理解 这个是获得用户选择的图片的索引值
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    // 将光标移至开头 ,这个很重要,不小心很容易引起越界
    cursor.moveToFirst();
    // 最后根据索引值获取图片路径
    String path = cursor.getString(column_index);
    if(path != null && (path.endsWith(".png")||path.endsWith(".PNG")||path.endsWith(".jpg")||path.endsWith(".JPG"))){
        File newFile = FileUtils.compressFile(path, compressPath);
        return Uri.fromFile(newFile);
    }else{
        Toast.makeText(this, "上传的图片仅支持png或jpg格式",Toast.LENGTH_SHORT).show();
    }
    return null;
}
*/

protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
    /*intent=createDefaultOpenableIntent();*/
    
    
    
    
    
    Uri result =null;
    if(requestCode == REQ_CAMERA ){
        afterOpenCamera();
        result = cameraUri;
    }
    else  if (requestCode == FILECHOOSER_RESULTCODE) {
        if (null == mUploadMessage)
        return;
        result = intent == null || resultCode != RESULT_OK ? null : intent.getData();
        if (result == null && intent == null && resultCode == Activity.RESULT_OK) {
            File cameraFile = new File(mCameraFilePath);
            if (cameraFile.exists()) {
                result = Uri.fromFile(cameraFile);
                // Broadcast to the media scanner that we have a new photo
                // so it will be added into the gallery for the user.
                sendBroadcast(
                        new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, result));
                    }
         }
    //
   
   
    }
     mUploadMessage.onReceiveValue(result);
        mUploadMessage = null;
        super.onActivityResult(requestCode, resultCode, intent);
}
public final boolean checkSDcard() {
    boolean flag = Environment.getExternalStorageState().equals(
            Environment.MEDIA_MOUNTED);
    if (!flag) {
        Toast.makeText(this, "请插入手机存储卡再使用本功能",Toast.LENGTH_SHORT).show();
    }
    return flag;
}
String compressPath = "";
protected final void selectImage() {
    
    if (!checkSDcard())
        return;
    String[] selectPicTypeStr = { "拍照","相册" };
    AlertDialog alertDialog =new AlertDialog
    .Builder(this)
            .setItems(selectPicTypeStr,
                    new DialogInterface.OnClickListener() {
                        
                        
                         @Override
                        public void onClick(DialogInterface dialog,
                                int which) {
                            switch (which) {
                            // 相机拍摄
                            case 0:
                                openCarcme();
                                break;
                            // 手机相册
                            case 1:
                                chosePic();
                                break;
                            default:
                                break;
                            }
                            
                            compressPath = Environment
                                    .getExternalStorageDirectory()
                                    .getPath()
                                    + "/EBeautyima";//地址
                            
                            boolean a=new File(compressPath).mkdirs();
                            
                            compressPath = compressPath + File.separator
                                    + "compress.jpg";
                            
                        }
                    }).show();
    alertDialog.setCanceledOnTouchOutside(false);
}

//


protected void chosePic() {
    // TODO 自动生成的方法存根
     Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
     intent.addCategory(Intent.CATEGORY_OPENABLE);
     intent.setType("image/*");// 相片类型
     startActivityForResult(intent,  MainActivity.FILECHOOSER_RESULTCODE);
}
String imagePaths;
Uri  cameraUri;
private void openCarcme() {
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//getAbsolutePath
    imagePaths = Environment.getExternalStorageDirectory().getPath()
            + "/EBeautyima/"//地址
            + (System.currentTimeMillis() + ".jpg");
    
    // 必须确保文件夹路径存在,否则拍照后无法完成回调
    File vFile = new File(imagePaths);
    
    if (!vFile.exists()) {
        File vDirPath = vFile.getParentFile();
        vDirPath.mkdirs();
    } else {
        if (vFile.exists()) {
            vFile.delete();
        }
    }
    cameraUri = Uri.fromFile(vFile);
    Log.i("sql", cameraUri+"");
    intent.putExtra(MediaStore.EXTRA_OUTPUT, cameraUri);
    startActivityForResult(intent, REQ_CAMERA);
}
/**
 * 拍照结束后
 */
private void afterOpenCamera() {
    File f = new File(imagePaths);
    addImageGallery(f);
    File newFile = FileUtils.compressFile(f.getPath(), compressPath);
}


private void addImageGallery(File file) {
    ContentValues values = new ContentValues();
    values.put(MediaStore.Images.Media.DATA, file.getAbsolutePath());
    values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
    getContentResolver().insert(
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
}

//



//
//--------------------
//防止点击back键退出
public boolean onKeyDown(int keyCoder,KeyEvent event){
    if(webView.canGoBack() && keyCoder == KeyEvent.KEYCODE_BACK){
        webView.goBack();   //goBack()表示返回webView的上一页面
             return true;
       }
    return false;
}


}

-----------------------------------------------------

package com.example.ebeauty;

import android.webkit.WebViewClient;

public class webViewClient extends WebViewClient {

}


0 0
原创粉丝点击