使用Phonegap在Android中使用AsyncTask进行多个图像上传

时间:2012-12-10 06:52:49

标签: android cordova file-upload

我在使用Android 3.x及更高版本的多个图片上传时出现此问题。我的应用程序是混合的,它不是纯粹的Android。我必须使用Phonegap界面进行Android编码。所以这是我用AsyncTask编写的代码。这对于Android 2.3来说同样适用,但不适用于Android 3.x及更高版本。我正在分享我的代码。

public class CFileUploader extends Plugin {
    private String ACTION_POST_DATA = "cpost_data";
    private String CrLf = "\r\n";
    String base64Str=null;

    @Override
    public PluginResult execute(String arg0, JSONArray arg1, String arg2) {
        Log.e("Sample App", " IN EXECUTE METHOD ");

        PluginResult pluginResult = null;
        if (ACTION_POST_DATA.equals(arg0)) {
            try {
                upload(arg1.getString(0), arg1.getString(1), arg1.getString(2),
                        arg1.getString(3), arg1.getString(4));

            } catch (JSONException jsonex) {
                jsonex.printStackTrace();
            }
        }
        return pluginResult;
    }

    private PluginResult upload(String token, String date, String time,
            String email, String fileNames) {
        Log.e("Sample App", " IN UPLOAD METHOD ");
        PluginResult pluginres = null;

        final Data obje=new Data(token, date, time, email, fileNames);

        CFileUploader.this.ctx.runOnUiThread(new Runnable(){
            public void run(){
                MyImageTask mTask=new MyImageTask();
                mTask.execute(obje);
            }
        });

        return pluginres;
    }

    class Data {
        String token, date, time, email, fileNames;
        Data(String token, String date, String time, String email, String fileNames){
            this.token=token;
            this.date=date;
            this.time=time;
            this.email=email;
            this.fileNames=fileNames;
        }

    }

    private class MyImageTask extends AsyncTask<Data, String, String>{

        @Override
        protected String doInBackground(Data... params) {               
            HttpURLConnection conn = null;
            DataOutputStream dos = null;
            DataInputStream inStream = null;
            ByteArrayOutputStream baos = null;
            byte[] imgData = null;
            String urlString = "https://www.sampledata.com/myapp/upload_snapshots.php";

            Log.e("Sample App", " token " + params[0].token + " " + "date " + params[0].date + " "
                    + " time " + params[0].time + " " + "email " + params[0].email);
            Log.e("Sample App", " imgPath " + params[0].fileNames);

            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 buffer = new StringBuffer(msg);
                buffer.append("-----------------------------1177141514664");
                buffer.append(CrLf);
                buffer.append("Content-Disposition: form-data; name=\"token\";"
                        + CrLf);
                buffer.append(CrLf);
                buffer.append(params[0].token + CrLf);

                buffer.append("-----------------------------1177141514664");
                buffer.append(CrLf);
                buffer.append("Content-Disposition: form-data; name=\"date\";"
                        + CrLf);
                buffer.append(CrLf);
                buffer.append(params[0].date + CrLf);

                buffer.append("-----------------------------1177141514664");
                buffer.append(CrLf);
                buffer.append("Content-Disposition: form-data; name=\"time\";"
                        + CrLf);
                buffer.append(CrLf);
                buffer.append(params[0].time + CrLf);

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

                buffer.append("-----------------------------1177141514664");
                buffer.append(CrLf);
                buffer.append("Content-Disposition: form-data; name=\"email\";"
                        + CrLf);
                buffer.append(CrLf);
                buffer.append(params[0].email + CrLf);

                buffer.append("-----------------------------1177141514664");
                buffer.append(CrLf);
                buffer.append("Content-Disposition: form-data; name=\"appkey\";"
                        + CrLf);
                buffer.append(CrLf);
                buffer.append("426C3A7D5992B838BAF1BD10594C920C" + CrLf);

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

                String msg1 = "";
                StringBuffer imgBuffer = new StringBuffer(msg1);
                List<byte[]> byetsInfo = new ArrayList<byte[]>();
                ArrayList<String> filenames = new ArrayList<String>();
                try {
                    JSONObject jObj = new JSONObject(new String(params[0].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 + "/myapp_images/" + img);
                        Uri ur = Uri.fromFile(f);
                        filenames.add(img);
                        Bitmap bmp;
                        try {
                            bmp = Media.getBitmap(CFileUploader.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 eofBuffer = new StringBuffer(msg3);
                eofBuffer.append(CrLf);
                eofBuffer.append("-----------------------------4664151417711--");
                eofBuffer.append(CrLf);

                conn.setChunkedStreamingMode(0);

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

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

                    dos.write(buffer.toString().getBytes());
                    dos.write(imgBuffer.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(eofBuffer.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();
            }

            // 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));
                        base64Str += 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")) {
                    return base64Str;
                } else {
                    return null;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
        }

    }

}

我将从js文件中获取的令牌,日期,时间,电子邮件和文件名。

我应该得到一个base64字符串:

Submitted Requests: 
requests={"imageInfo":{"snapshotDateTime":"2012-12-09 22:38:14","snapshots":{"name":["Water lilies.jpg","Sunset.jpg"],"type":["image\/jpeg","image\/jpeg"],"tmp_name":["\/tmp\/phpXmZchs","\/tmp\/phpqylUgX"],"error":[0,0],"size":[83794,71189]}}}

当我在android 3.x及更高版本中运行此代码时,我没有得到它们中的任何一个。

如果我在某个地方出错了,请纠正我。非常感谢。

2 个答案:

答案 0 :(得分:1)

谁回答了很多感谢。经过几天的挣扎,我终于找到了解决方案,它只是一行代码,它正在做所有的混乱。

conn.setChunkedStreamingMode(0);

我删除了上面一行,它在所有设备上运行正常,无论版本如何。

答案 1 :(得分:0)

我猜您正在尝试为多个上传启动多个AsyncTasks。 您假设每个任务都创建了一个不同的线程,这对于预蜂窝版本是正确的,但在蜂窝状态下,之后AsyncTask的行为被更改,并且Asynctask的所有实例都运行单个线程。 看看这个方法真正的并行执行

executeOnExecutor(java.util.concurrent.Executor, Object[]) with THREAD_POOL_EXECUTOR.