0

我有一個問題,將多個圖像上傳到php服務器。下面給出的代碼適用於android 2.x版本,但是相同的代碼不適用於android 4.x及更高版本。我搜索了一下,發現數據發佈必須由AsyncTask異步完成。但我不知道如何通過phonegap完成(調用異步任務)。使用phonegap異步上傳多個圖像

在這裏,我有我的代碼:

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; 

    } 

} 

在文件名是,日期和時間,我從其中將被髮送到上面的類js代碼獲取代碼的數據。任何人都可以請我提供一個關於如何通過Phonegap調用異步任務的例子(即,在imgsUpload()中調用它)

非常感謝。

回答

0

以下是我用於將圖像上傳到可與AsynTask一起使用的服務器的工作代碼。

//this method takes Inputs (Image name and Image file path where it stored) 
//and after upload it returns json response 

public String pushImage(String filepath,String imageName){ 


    Log.v(TAG, "path is:"+filepath); 
    Log.v(TAG, "image name is:"+imageName); 
    HttpURLConnection conn = null; 

    DataInputStream inStream = null; 

    String lineEnd = "\r\n"; 
    String twoHyphens = "--"; 
    String boundary = "---------------------------14737809831466499882746641449"; 
    int bytesRead, bytesAvailable, bufferSize; 
    byte[] buffer; 
    int maxBufferSize = 1*1024*1024; 


    String reponse_data=null; 
    try{ 
     //------------------ CLIENT REQUEST  

     //set request properties 
     // here baseURL is url for uploading image 
     URL url = new URL(baseURL);   
     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="+boundary); 



     //add request body   

     DataOutputStream dos = new DataOutputStream(conn.getOutputStream()); 

     dos.writeBytes(lineEnd+twoHyphens + boundary + lineEnd);   

     dos.writeBytes("Content-Disposition: form-data; name=\"uploaded\";filename=\"" + imageName + "\"" + lineEnd);  

     dos.writeBytes("Content-Type: application/octet-stream\r\n\r\n"); 

     //now add image data 


     FileInputStream fileInputStream = new FileInputStream(new File(filepath)); 

     bytesAvailable = fileInputStream.available(); 
     bufferSize = Math.min(bytesAvailable, maxBufferSize); 
     buffer = new byte[bufferSize]; 
     bytesRead = fileInputStream.read(buffer, 0, bufferSize); 

     while (bytesRead > 0){ 
      dos.write(buffer, 0, bufferSize); 
      bytesAvailable = fileInputStream.available(); 
      bufferSize = Math.min(bytesAvailable, maxBufferSize); 
      bytesRead = fileInputStream.read(buffer, 0, bufferSize); 
     }  

     dos.writeBytes(lineEnd); 
     dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); 


     fileInputStream.close(); 
     dos.flush(); 
     dos.close(); 
    } 
    catch (MalformedURLException ex){ 
     ex.printStackTrace(); 
    } 
    catch (IOException ioe){ 
     ioe.printStackTrace(); 
    } 


    //------------------ read the SERVER RESPONSE 
    try { 
     if(conn !=null){ 
      inStream = new DataInputStream (conn.getInputStream()); 
     } 

     String str=null; 

     if(inStream !=null){ 
      while ((str = inStream.readLine()) != null){ 
       Log.e("Debug","Server Response "+str); 
       reponse_data=str; 
      } 


      inStream.close(); 
     } 


    } 
    catch (IOException ioex){ 
     ioex.printStackTrace(); 
    } 
    return reponse_data; 
} 

你可以從this鏈接

+0

它與我寫的代碼相同...我的代碼是al所以工作。我的問題是如何調用異步任務,因爲它不能在4.x版本@RDC中工作 – Lavanya