Android文件上传和下载 iframe

上传:

@CMPlugin
public class HDFSUpload  extends CMPluginImpl {
    private   String  localFilePath = "0";

    public  void  setLocalFilePath(String  path)
    {

        this.localFilePath = path;
    }
    public   String   getLocalFilePath()
    {
        return this.localFilePath;
    }
    public void postFileMultiPart(String url,Map reqParam,String callback) throws ClientProtocolException, IOException {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            // 创建httpget.
            HttpPost httppost = new HttpPost(url);
            //setConnectTimeout:设置连接超时时间,单位毫秒。setConnectionRequestTimeout:设置从connect Manager获取Connection 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。setSocketTimeout:请求获取数据的超时时间,单位毫秒。 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。
            RequestConfig defaultRequestConfig = RequestConfig.custom().setConnectTimeout(5000).setConnectionRequestTimeout(5000).setSocketTimeout(15000).build();
            httppost.setConfig(defaultRequestConfig);
            MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
            for(Map.Entry param : reqParam.entrySet()){
                multipartEntityBuilder.addPart(param.getKey(), param.getValue());
            }
            HttpEntity reqEntity = multipartEntityBuilder.build();
            httppost.setEntity(reqEntity);

            // 执行post请求.
            CloseableHttpResponse response = httpclient.execute(httppost);

            try {
                // 获取响应实体
                HttpEntity entity = response.getEntity();
                String  ret = getLocalFilePath();

                if (entity != null) {
                        webviewpost(ret,callback);

                }else{
                    webviewpost("error",callback);

                }
            } finally {
                response.close();

            }
        } finally {
            // 关闭连接,释放资源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
    @CMPluginMethod
    public void  upload(JSONObject jsonObj)   {
        // TODO Auto-generated method stub
        String url = "";
        try {
            String localFileName = jsonObj.getString("filepaths");
             String callback = jsonObj.getString("callback");

            Map reqParam = new HashMap();
            if (localFileName.indexOf("data:image/png;base64") > -1) {
                String[] fileNameArr = localFileName.split("&");
                String fileName = fileNameArr[0];
                String file = fileNameArr[1];
                String filenameTemp = fileNameArr[0];
                String dir = fileNameArr[3];

//                url="http://106.3.145.71:49870/DataCenter/service/hadoop/hdfs/uploadFile?path=hxywxt/mobile/"+dir+"&user=hxywxt-tenant";
//              url="http://10.72.95.175:8080/DataCenter/service/hadoop/hdfs/uploadFile?path=hxywxt/mobile/"+dir+"&user=hxywxt-tenant";
              url="http://10.24.19.86:8099/API/uploadFile?path=hxywxt/mobile/"+dir+"&user=hxywxt-tenant";

                reqParam.put("Filename", new StringBody(fileName, ContentType.MULTIPART_FORM_DATA));
                reqParam.put("pictitle", new StringBody(fileName, ContentType.MULTIPART_FORM_DATA));
                reqParam.put("fileName", new StringBody(fileName, ContentType.MULTIPART_FORM_DATA));
                String cacheDir = context.getExternalCacheDir().getPath();
                filenameTemp = cacheDir+"/"+filenameTemp;

                base64ToFile(file,filenameTemp);
                File fileTemp = new File(filenameTemp);
                reqParam.put("upfile", new FileBody(fileTemp));
            } else {
                String[] fileNameArr = localFileName.split("&");
                String fileName = fileNameArr[0];
                String dir = fileNameArr[1];
//            url="http://106.3.145.71:49870/DataCenter/service/hadoop/hdfs/uploadFile?path=hxywxt/mobile/"+dir+"&user=hxywxt-tenant";
              //url="http://10.200.64.94:8099/API/uploadFile?path=hxywxt/mobile/"+dir+"&user=hxywxt-tenant";
              url="http://10.24.19.86:8099/API/uploadFile?path=hxywxt/mobile/"+dir+"&user=hxywxt-tenant";

                reqParam.put("Filename", new StringBody(fileName, ContentType.MULTIPART_FORM_DATA));
                reqParam.put("pictitle", new StringBody(fileName, ContentType.MULTIPART_FORM_DATA));
                reqParam.put("fileName", new StringBody(fileName, ContentType.MULTIPART_FORM_DATA));
                reqParam.put("upfile", new FileBody(new File(fileName)));
            }
            reqParam.put("dir", new StringBody("upload1", ContentType.MULTIPART_FORM_DATA));
            reqParam.put("fileNameFormat", new StringBody("{time}{rand:6}", ContentType.MULTIPART_FORM_DATA));
            reqParam.put("Upload", new StringBody("Submit Query", ContentType.MULTIPART_FORM_DATA));

            try {
                postFileMultiPart(url, reqParam, callback);
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }catch(Exception e)
        {
                        e.printStackTrace();
        }

    }
    private void webviewpost(final String ret,final String callback) {
        if (webView == null || StringUtil.isEmpty(callback)) {
            return;
        }
        webView.post(new Runnable() {
            String ret1 = ret.replaceAll("\\\\r\\\\n", "\n");
            @Override
            public void run() {
                webView.loadUrl(String.format("javascript:"+callback+"('"+ret1+"')"));
            }
        });
    }
    public  void base64ToFile(String base64,String filenameTemp)throws Exception{
        BASE64Decoder decoder = new BASE64Decoder();
        int m=base64.indexOf("base64");
        base64=base64.substring(m+7);
        byte[] bytes = decoder.decodeBuffer(base64);

        OutputStream out=new FileOutputStream(filenameTemp);
        out.write(bytes);
        out.flush();
        out.close();
        setLocalFilePath(filenameTemp);
    }


}
/*
class MutliThread extends Thread{
    String url="";
    String reqParam="";
    String callback="";

    MutliThread(String url,String reqParam,String callback){
        postFileMultiPart(url, reqParam, callback);
    };
    public void run(){
        postFileMultiPart(url, reqParam, callback);
    }
}*/

下载:

@CMPlugin
public class HDFSdownLoad  extends CMPluginImpl {

    //wwl 重写delete方法
    @CMPluginMethod
    public void  delete(JSONObject jsonObj) throws JSONException {
        String localFileName = jsonObj.getString("filepaths");
        String[] fileNameArr = localFileName.split("&");
        String fileName = fileNameArr[0];
        String dir = fileNameArr[1];
    //        String urlPath="http://106.3.145.71:49870/DataCenter/service/hadoop/hdfs/deleteFile?filePath=hxywxt/mobile/"+dir+"/"+fileName+"&recursion=true&user=hxywxt-tenant";
        String urlPath="http://10.24.19.86:8099/API/deleteFile?filePath=hxywxt/mobile/"+dir+"/"+fileName+"&recursion=true&user=hxywxt-tenant";
        String callback = jsonObj.getString("callback");

        //请求的url
        URL url = null;
        //建立的http链接
        HttpURLConnection httpConn = null;
        //请求的输入流
        BufferedReader in = null;
        //输入流的缓冲
        StringBuffer sb = new StringBuffer();
        try{
            url = new URL(urlPath);
            in = new BufferedReader(new InputStreamReader(url.openStream(),"UTF-8") );
            String str = null;
            //一行一行进行读入
            while((str = in.readLine()) != null) {
                sb.append( str );
            }
            String result =sb.toString();
            webviewpost(result,callback,"");
        } catch (Exception ex) {

        } finally{
            try{
                if(in!=null) {
                    in.close(); //关闭流
                }
            }catch(IOException ex) {

            }
        }


    }
    @CMPluginMethod
    public void  downLoad(JSONObject jsonObj) throws JSONException {
        String localFileName = jsonObj.getString("filepaths");
        String target  =  jsonObj.getString("target");
        String wjlj  =  jsonObj.getString("wjlj");
//        String urlPath="http://106.3.145.71:49870/DataCenter/service/hadoop/hdfs/download?src=hxywxt/mobile/"+wjlj+"/"+localFileName+"&user=hxywxt-tenant";
        String urlPath="http://10.24.19.86:8099/API/download?src=hxywxt/mobile/"+wjlj+"/"+localFileName+"&user=hxywxt-tenant";
        String httpRes = null;
        String callback = jsonObj.getString("callback");
        String media = jsonObj.getString("media");
        try {
            URL url = new URL(urlPath);
            try {
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestProperty("accept", "*/*");
                conn.setRequestProperty("connection", "Keep-Alive");
                conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
                conn.setDoOutput(true);
                conn.setDoInput(true);

                InputStream is = conn.getInputStream();
                String headFileName = conn.getHeaderField("Content-disposition");

                String cacheDir = context.getExternalCacheDir().getPath();
                String full = "";
                if (media != null && !"".equals(media)){
                    full = target;
                } else {
                    full = cacheDir+"/"+target;
                }

                //构造一个字符流缓存
                String folderPath = full.substring(0,full.lastIndexOf("/"));
                File folder = new File(folderPath);
                folder.mkdirs();
                File file  = new File(full);
                if (!file.exists()){
                    file.createNewFile();
                }
                FileOutputStream fos = new FileOutputStream(file);
                byte[] buffer = new byte[1024];
                String str = "";
                int len = 0;
                while ((len = is.read(buffer)) != -1) {
                    fos.write(buffer,0,len);
                }
                FileInputStream fis = new FileInputStream(full);
                while( fis.read(buffer)  > 0){
                    String strBuff =  new String(buffer).substring(0,5);
                    if (strBuff.startsWith("true")||strBuff.startsWith("false"))
                    {
                        file.delete();
                        webviewpost("0",callback,media);
                        return;
                    }
                    // System.out.println(buffer);
                }
                //关闭流
                is.close();
                //断开连接,最好写上,disconnect是在底层tcp socket链接空闲时才切断。如果正在被其他线程使用就不切断。
                //固定多线程的话,如果不disconnect,链接会增多,直到收发不出信息。写上disconnect后正常一些。
                conn.disconnect();
                webviewpost(full,callback,media);
               // System.out.println("完整结束");
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 下载头像
     * @param jsonObj
     * @throws JSONException
     */
    @CMPluginMethod
    public void  downLoadTx(JSONObject jsonObj) throws JSONException {
        String wjlj  =  jsonObj.getString("wjlj");
//        String urlPath="http://106.3.145.71:49870/DataCenter/service/hadoop/hdfs/download?src=hxywxt/mobile/"+wjlj+"/"+localFileName+"&user=hxywxt-tenant";
    //    String urlPath="http://10.200.64.94:8099/API/downloadTx?src=hxywxt/mobile/"+wjlj+""+"&user=hxywxt-tenant";
        String urlPath="http://10.24.19.86:8099/API/downloadTx?src=hxywxt/mobile/"+wjlj+""+"&user=hxywxt-tenant";
        String httpRes = null;
        String callback = jsonObj.getString("callback");
      //  String media = jsonObj.getString("media");
        try {
            URL url = new URL(urlPath);
            try {
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestProperty("accept", "*/*");
                conn.setRequestProperty("connection", "Keep-Alive");
                conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
                conn.setDoOutput(true);
                conn.setDoInput(true);

                InputStream is = conn.getInputStream();
                String headAllFileName = conn.getHeaderField("Content-disposition");
                String headFileName =    headAllFileName.substring("attachementfilename=".length()+2,headAllFileName.length()-1);
                String cacheDir = context.getExternalCacheDir().getPath();
                String full = "";

                full = cacheDir+"/tx/"+headFileName;


                //构造一个字符流缓存
                String folderPath = full.substring(0,full.lastIndexOf("/"));
                File folder = new File(folderPath);
                folder.mkdirs();
                File file  = new File(full);
                if (!file.exists()){
                    file.createNewFile();
                }
                FileOutputStream fos = new FileOutputStream(file);
                byte[] buffer = new byte[1024];
                String str = "";
                int len = 0;
                while ((len = is.read(buffer)) != -1) {
                    fos.write(buffer,0,len);
                }
                FileInputStream fis = new FileInputStream(full);
                while( fis.read(buffer)  > 0){
                    String strBuff =  new String(buffer).substring(0,5);
                    if (strBuff.startsWith("true")||strBuff.startsWith("false"))
                    {
                        file.delete();
                        webviewpost("0",callback,"0");
                        return;
                    }
                    // System.out.println(buffer);
                }
                //关闭流
                is.close();
                //断开连接,最好写上,disconnect是在底层tcp socket链接空闲时才切断。如果正在被其他线程使用就不切断。
                //固定多线程的话,如果不disconnect,链接会增多,直到收发不出信息。写上disconnect后正常一些。
                conn.disconnect();
                webviewpost(full,callback,"0");
                // System.out.println("完整结束");
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    private void webviewpost(final String ret,final String callback,final String media) {
        if (webView == null || StringUtil.isEmpty(callback)) {
            return;
        }
        webView.post(new Runnable() {
            String ret1 = ret.replaceAll("\\\\r\\\\n", "\n");
            @Override
            public void run() {
                webView.loadUrl(String.format("javascript:"+callback+"('"+ret1+"','"+media+"')"));
            }
        });
    }


}

获取iframe中的元素

//iiframe加载完成之后执行,修改iframe元素的属性,屏蔽点击事件,如果不屏蔽的话,跳转到相应的网页,不能返回到app中
function  finishLoad(){
    var test = document.getElementById('tianqiiframe').contentWindow.document.getElementsByTagName("a");
    console.log(test);
    for (var i = 0;i < test.length;i++){
        if (test[i].innerHTML == "更换城市" || test[i].innerHTML == "返回" ){
            ;
        }
        else{
               test[i].setAttribute("href","javascript:void(0)");
               test[i].setAttribute("target","");
        }
    }
}

你可能感兴趣的:(Android平台,Java)