多张图片中的Andr​​oid异步上传使用的PhoneGap [英] Multiple Images upload in android asynchronously using phonegap

查看:192
本文介绍了多张图片中的Andr​​oid异步上传使用的PhoneGap的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有多个图像的问题上传到PHP服务器。下面给出的code正常工作为Android 2.X版本,但在同一code没有针对Android 4.x及以上工作。我用Google搜索,并发现该数据发布必须由AsyncTask的异步完成。但我不知道它是如何,必须通过PhoneGap的完成(异步调用任务)的线索。

I have an issue with multiple images upload to php server. The code given below works fine for android 2.x versions, but the same code doesn't work for android 4.x and above. I have googled and found out that the data posting has to be done asynchronously by AsyncTask. But I have no clue about how it has to be done via phonegap(calling of async task).

在这里,我有我的code:

Here I have my code :

package com.mymedlinks.hybrid;

import java.util.TimeZone;

import org.apache.cordova.api.Plugin;
import org.apache.cordova.api.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.ContextWrapper;
import android.provider.Settings;
import android.util.Log;

public class SamplePlugin extends Plugin{
    public String ACTION_POST_DATA="post_data";

    @Override
    public PluginResult execute(String arg0, JSONArray arg1, String arg2) {
        // TODO Auto-generated method stub
        PluginResult pluginRes;
        if(ACTION_POST_DATA.equals(arg0)){
            try {
                pluginResult = imgsUpload(args.getString(0),
                        args.getString(1), args.getString(2));
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } else{
            pluginRes = new PluginResult(PluginResult.Status.INVALID_ACTION);;
        }
        return pluginRes;
    }

    private PluginResult imgsUpload(String date,String time,
             String fileNames) {
             PluginResult pluginResult=null;
        HttpURLConnection conn = null;
        DataOutputStream dos = null;
        DataInputStream inStream = null;
        ByteArrayOutputStream baos = null;
        byte[] imgData = null;
        String urlString = "https://www.mysampledata.com/upload_imgs.php";

                //opening of http connection
                try {
            URL url = new URL(urlString);
            conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("Content-Type",
                    "multipart/form-data;boundary=---------------------------1177141514664");
            String msg = "";
            StringBuffer buffr = new StringBuffer(msg);

            buffr.append("-----------------------------1177141514664");
            buffr.append(CrLf);
            buffr.append("Content-Disposition: form-data; name=\"date\";"
                    + CrLf);
            buffr.append(CrLf);
            buffr.append(date + CrLf);

            buffr.append("-----------------------------1177141514664");
            buffr.append(CrLf);
            buffr.append("Content-Disposition: form-data; name=\"time\";"
                    + CrLf);
            buffr.append(CrLf);
            buffr.append(time + CrLf);

            buffr.append("-----------------------------1177141514664");
            buffr.append(CrLf);
            buffr.append("Content-Disposition: form-data; name=\"MAX_FILE_SIZE\";"
                    + CrLf);
            buffr.append(CrLf);
            buffr.append("100000000072000" + CrLf);

            buffr.append("-----------------------------1177141514664");
            buffr.append(CrLf);
            buffr.append("Content-Disposition: form-data; name=\"method\";"
                    + CrLf);
            buffr.append(CrLf);
            buffr.append("upload.snapshots" + CrLf);

            String msg1 = "";
            StringBuffer buffr1 = new StringBuffer(msg1);
            List<byte[]> byetsInfo = new ArrayList<byte[]>();
            ArrayList<String> filenames = new ArrayList<String>();
            try {
                JSONObject jObj = new JSONObject(new String(fileNames));
                JSONArray jArray = jObj.getJSONArray("snapshot_images");
                String drPath = android.os.Environment
                        .getExternalStorageDirectory().toString();

                for (int i = 0; i < jArray.length(); i++) {
                    String img = jArray.getString(i);
                    Log.e("sample app", " imageName " + img);

                    File f = new File(drPath + "/sample_app_images/" + img);
                    Uri ur = Uri.fromFile(f);
                    filenames.add(img);
                    Bitmap bmp;
                    try {
                        bmp = Media.getBitmap(this.cordova.getActivity()
                                .getContentResolver(), ur);
                        baos = new ByteArrayOutputStream();
                        bmp.compress(CompressFormat.JPEG, 90, baos);

                        imgData = baos.toByteArray();
                        Log.e("sample app", " img data size " + imgData.length);

                    } catch (FileNotFoundException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                    byetsInfo.add(imgData);

                }

            } catch (JSONException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

            String msg3 = "";
            StringBuffer buffr3 = new StringBuffer(msg3);
            buffr3.append(CrLf);
            buffr3.append("-----------------------------4664151417711--");
            buffr3.append(CrLf);

            conn.setChunkedStreamingMode(0);

            for (int i = 0; i < byetsInfo.size(); i++) {
                dos = new DataOutputStream(conn.getOutputStream());

                buffr1.delete(0, buffr1.length());
                buffr1.append("-----------------------------1177141514664");
                buffr1.append(CrLf);
                buffr1.append("Content-Disposition: form-data; name=\"snapshotUpload[]\"; filename=\""
                        + filenames.get(i) + "\"" + CrLf);
                buffr1.append("Content-Type: image/jpeg" + CrLf);
                buffr1.append(CrLf);

                dos.write(buffr.toString().getBytes());
                dos.write(buffr1.toString().getBytes());

                int index = 0;
                int size = 1024;
                do {

                    if ((index + size) < byetsInfo.get(i).length) {
                        size = byetsInfo.get(i).length - index;
                    }
                    dos.write(byetsInfo.get(i), index, size);
                    index += size;
                } while (index < byetsInfo.get(i).length);
                Log.e("file upload ", " written: " + index);

                dos.write(buffr3.toString().getBytes());

            }

            Log.e("Debug", "File is written");
            Log.e("activity upload demo ",
                    " in file upload " + conn.getResponseMessage());
            dos.flush();

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

           String s=null;
        // Read the response
        try {
            inStream = new DataInputStream(conn.getInputStream());
            char buff = 512;
            int len;
            byte[] data = new byte[buff];
            do {
                len = inStream.read(data);
                if (len > 0) {
                    System.out.println(new String(data, 0, len));
                    s+=new String(data, 0, len);
                    Log.e("sample app", "  "
                            + new String(data, 0, len));
                }
            } while (len > 0);
            Log.e("file upload ", " DONE ");

            dos.close();
            inStream.close();

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

                try {
            if(conn.getResponseMessage().equalsIgnoreCase("OK") && s!=null){
                pluginResult = new PluginResult(PluginResult.Status.OK, s);
            } else {
                pluginResult = new PluginResult(PluginResult.Status.ERROR,
                        false);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return pluginResult;

    }

}

在code是文件名,日期和时间,我从JS code将被发送到上面的类获取数据。任何人都可以请我提供有关如何异步任务可以通过PhoneGap的被称为一个例子(即,称这是在imgsUpload())

The data in the code that is filenames, date and time I get from js code which will be sent to the above class. Can anyone please provide me with an example about how the Async Task can be called via Phonegap (i.e., calling it in the imgsUpload())

非常感谢。

推荐答案

我有一个解决方案,它是这里的Multiple使用AsyncTask的使用PhoneGap的图片上传Android中

I have got a solution for this and it's here Multiple Image Upload using AsyncTask in Android using Phonegap

无论哪种方式code似乎在所有设备上正常工作,一旦code的下面一行被删除

Either ways the code seems to work fine on all devices once the following line of code is removed

conn.setChunkedStreamingMode(0);

这篇关于多张图片中的Andr​​oid异步上传使用的PhoneGap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆