0

I want to send image data from android client to the server. But there is a problem, there are times when I send data the received message successfully, but there are times when I send but not receive anything, even though the server has received the data.

function upload

 public void upload()
{
    try
    {
        // nén hình lại và gửi lên server
        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        alteredBitmap.compress(Bitmap.CompressFormat.JPEG, 90, bao);

        // chyển hình ảnh về dạng byte
        byte[] ba = bao.toByteArray();

        // dùng thư viện Base64 chuyển mảng Byte về chuỗi String
        String ba1 = Base64.encodeBytes(ba);

        // Đường dẫn đến server
        String sampleURL = SERVICE_URL + "/uploadimage.php";

        // Tạo mới một lớp CallUrl
        CallUrl wst = new CallUrl(CallUrl.POST_TASK, this, "Uploading data...", 2, "");

        // Thêm data
        wst.addNameValuePair("image", ba1);
        wst.addNameValuePair("mahoadon", mahoadon);

        // Gửi lên server
        wst.execute(new String[] {
                sampleURL
        });
    } catch (Exception e)
    {
        e.printStackTrace();
    }
}

Class Callurl with flag=2

public class CallUrl extends AsyncTask<String, Integer, String> {

public static final int POST_TASK = 1;
public static final int GET_TASK = 2;
private static final String TAG = "WebServiceTask";
// thời gian chờ của một kết nối, tính theo milliseconds (waiting to
// connect)
private static final int CONN_TIMEOUT = 3000;
// thời gian chờ của một socket, tính bằng milliseconds (waiting for data)
private static final int SOCKET_TIMEOUT = 5000;
private int taskType = GET_TASK;
private Context mContext = null;
private String processMessage = "Processing...";
private ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
private int flag = 0;
private String ID;
private ProgressDialog progressDialog;

// Khởi tạo
public CallUrl(int taskType, Context mContext, String processMessage, int flag, String ID) {

    this.taskType = taskType;
    this.mContext = mContext;
    this.processMessage = processMessage;
    this.flag = flag;
    this.ID = ID;
}

@Override
protected void onPostExecute(String response) {

    progressDialog.dismiss();
    // Khai báo các thành phần cần thiết
    TextView txtusername = (TextView) ((Activity) mContext).findViewById(R.id.loginUsername);
    TextView txtpassword = (TextView) ((Activity) mContext).findViewById(R.id.loginPassword);
    CheckBox checkBox = (CheckBox) ((Activity) mContext).findViewById(R.id.checkBox1);
    DB_Adapter mDb = new DB_Adapter(mContext);
    final ArrayList<String> phonenumberArray = new ArrayList<String>();
    final ArrayList<String> codeInvoiceArray = new ArrayList<String>();
    final ArrayList<String> nameArray = new ArrayList<String>();
    final ArrayList<String> addressArray = new ArrayList<String>();
    final ArrayList<String> urlArray = new ArrayList<String>();

    // Nếu flag=0 tương đương với việc lấy thông tin đăng nhập từ server
    if (flag == 0)
    {
        try
        {
            // Dùng Json đọc thông tin nhận được từ server
            JSONObject json_data = new JSONObject(response);
            String result = json_data.getString("result");

            // Nếu kết quả trả về là đúng sẽ hiển thị activity invoice
            if (result.equalsIgnoreCase("User Found"))
            {

                Toast.makeText(mContext, "Đăng nhập thành công",
                        Toast.LENGTH_SHORT).show();

                // đăng nhập thành công sẽ chuyển vào activity Invoice
                Intent j = new Intent(mContext, Invoice.class);
                j.putExtra("ID", txtusername.getText().toString());
                mContext.startActivity(j);
                checkBox.setChecked(false);
            }

            // Nếu sai sẽ yêu cầu nhập lại
            else
            {
                String mess = "Tên đăng nhập hoặc mật khẩu không đúng!Làm ơn nhập lại!";
                Alert alert = new Alert(mContext, mess, false);
                alert.AlertDialog();
                txtpassword.setText("");
                txtusername.setText("");
            }
        } catch (Exception e)
        {
            e.printStackTrace();
        }

        // flag=1 lấy thông tin hóa đơn từ server
    } else if (flag == 1)
    {
        String phonenumber, name, address, url, code, status;
        JSONArray jArray;
        codeInvoiceArray.clear();
        nameArray.clear();
        phonenumberArray.clear();
        addressArray.clear();
        urlArray.clear();
        try
        {
            // kiểm tra chuỗi trả về
            // nếu rỗng thông báo hôm nay chưa có sản phẩm để giao
            // nếu có, dùng Json lấy thông tin nhận được
            if (response.equalsIgnoreCase(""))
            {
                notification("Hôm nay không còn gì để giao!");
            }
            else
            {
                JSONObject json_data = null;
                JSONObject jsonObject = new JSONObject(response);
                jArray = jsonObject.getJSONArray("Orders");
                // Mở kết nối đến database
                mDb.openDB();

                // sử dụng json lấy các giá trị thông qua các key
                // gán nó vào các mảng tương ứng
                for (int i = 0; i < jArray.length(); i++) {
                    json_data = jArray.getJSONObject(i);

                    // Lây thông tin theo mã id của người giao hàng
                    if (json_data.getString("DeliveryId").equalsIgnoreCase(ID))
                    {
                        // Lấy thông tin theo value thông qua các key
                        phonenumber = json_data.getString("PhoneNumber");
                        address = json_data.getString("Address");
                        name = json_data.getString("CustomerName");
                        url = json_data.getString("Url");
                        code = json_data.getString("CodeInvoice");
                        status = json_data.getString("Status");

                        // gán thông tin vào các mảng
                        phonenumberArray.add(phonenumber);
                        codeInvoiceArray.add(code);
                        nameArray.add(name);
                        addressArray.add(address);

                        // Gọi class load thông tin từ mảng lên listview
                        LoadListView load = new LoadListView(mContext, codeInvoiceArray,
                                nameArray, phonenumberArray, addressArray, ID);
                        load.loaddatalistview();
                        // Kiểm tra mã hóa đơn này đã có trong database chưa
                        // nếu chưa sẽ thêm data vào databse
                        // nếu đã có rồi sẽ cập nhật lại thông tin thông qua
                        // mã
                        // hóa đơn
                        if (mDb.test(code) == true)
                        {
                            mDb.insert(code, name, phonenumber, address, url, status,
                                    ID);
                            // Lưu thông tin hình ảnh hóa đơn vào sdcard
                            // save(code, url);
                            new LoadImageInvoice().execute(new String[] {
                                    url, code
                            });

                        }
                        else
                        {
                            // Nếu trùng với thông tin trong database sẽ
                            // edit lại thông tin
                            // Trong trường hợp sửa thông tin trên server
                            mDb.editAll(code, name, phonenumber, address, url, ID, status);

                        }
                    }
                }
                // Thực hiện xong, đóng kết nối
                mDb.closeDB();

            }
        } catch (Exception e)
        {
            e.printStackTrace();
        }
        // Nếu flag=2 tải hình ảnh hóa đơn đã ký lên server, và thông báo
        // gửi thành công
    } else if (flag == 2)
    {
        try
        {
            // thông tin báo thành công được trả về từ server
            JSONObject json_data = new JSONObject(response);
            String result = json_data.getString("str");
            if (result.equalsIgnoreCase("success"))
            {
                // Hiển thị khi tải lên thành công
                String mess = "Tải lên server thành công!";
                Alert alert = new Alert(mContext, mess, true);
                alert.AlertDialog();
            } else if (result.equalsIgnoreCase("faill"))
            {
                // Hiển thị khi tải lên server thất bại
                String mess = "Tải lên server thất bại!";
                Alert alert = new Alert(mContext, mess, false);
                alert.AlertDialog();
            }
        } catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}

// Thông báo dạng Toast
public void notification(String mess)
{
    Toast.makeText(mContext, mess, Toast.LENGTH_SHORT).show();
}

// thêm thông tin cần thiết để gửi lên server
public void addNameValuePair(String name, String value) {

    params.add(new BasicNameValuePair(name, value));
}

// hiển thị dialog trên UI cho người dùng biết app đang trong quá trình làm
// việc
@Override
protected void onPreExecute() {

    // showProgressDialog();
    this.progressDialog = ProgressDialog.show(mContext, "",
            processMessage);
}

// kết nối đến server thông url
protected String doInBackground(String... urls) {
    String url = urls[0];
    String result = "";
    HttpResponse response = doResponse(url);
    if (response == null) {
        return result;
    } else {
        try {

            result = inputStreamToString(response.getEntity().getContent());

        } catch (IllegalStateException e) {
            Log.e(TAG, e.getLocalizedMessage(), e);

        } catch (IOException e) {
            Log.e(TAG, e.getLocalizedMessage(), e);
        }
    }
    return result;
}

// khởi tạo socket và kết nối
private HttpParams getHttpParams() {

    HttpParams htpp = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(htpp, CONN_TIMEOUT);
    HttpConnectionParams.setSoTimeout(htpp, SOCKET_TIMEOUT);
    return htpp;
}

// thao tác xử lý khi kết nối đến server
private HttpResponse doResponse(String url) {

    HttpClient httpclient = new DefaultHttpClient(getHttpParams());
    HttpResponse response = null;

    try {
        switch (taskType) {

            //kiểm tra tác vụ cần thực hiển 
            //post gửi yêu cầu kèm thông tin
            //Get gửi yêu cầu
            case POST_TASK:
                HttpPost httppost = new HttpPost(url);
                // Add parameters
                httppost.setEntity(new UrlEncodedFormEntity(params));
                response = httpclient.execute(httppost);
                break;
            case GET_TASK:
                HttpGet httpget = new HttpGet(url);
                response = httpclient.execute(httpget);
                break;
        }
    } catch (Exception e) {

        Log.e(TAG, e.getLocalizedMessage(), e);

    }

    return response;
}

// Chuyển thông tin nhận về thành dạng chuỗi
private String inputStreamToString(InputStream is) {

    String line = "";
    StringBuilder total = new StringBuilder();
    BufferedReader rd = new BufferedReader(new InputStreamReader(is));
    try {
        // đọc thông tin nhận được cho đến khi kết thúc
        while ((line = rd.readLine()) != null) {
            total.append(line);
        }
    } catch (IOException e) {
        Log.e(TAG, e.getLocalizedMessage(), e);
    }

    // Trả về giá trị chuỗi đầy đủ
    return total.toString();
}

}

error

12-26 14:36:18.539: E/WebServiceTask(9063): null
12-26 14:36:18.539: E/WebServiceTask(9063): java.net.SocketTimeoutException
12-26 14:36:18.539: E/WebServiceTask(9063):     at java.net.PlainSocketImpl.read(PlainSocketImpl.java:491)
12-26 14:36:18.539: E/WebServiceTask(9063):     at java.net.PlainSocketImpl.access$000(PlainSocketImpl.java:46)
12-26 14:36:18.539: E/WebServiceTask(9063):     at java.net.PlainSocketImpl$PlainSocketInputStream.read(PlainSocketImpl.java:240)
12-26 14:36:18.539: E/WebServiceTask(9063):     at org.apache.http.impl.io.AbstractSessionInputBuffer.fillBuffer(AbstractSessionInputBuffer.java:103)
12-26 14:36:18.539: E/WebServiceTask(9063):     at org.apache.http.impl.io.AbstractSessionInputBuffer.readLine(AbstractSessionInputBuffer.java:191)
12-26 14:36:18.539: E/WebServiceTask(9063):     at org.apache.http.impl.conn.DefaultResponseParser.parseHead(DefaultResponseParser.java:82)
12-26 14:36:18.539: E/WebServiceTask(9063):     at org.apache.http.impl.io.AbstractMessageParser.parse(AbstractMessageParser.java:174)
12-26 14:36:18.539: E/WebServiceTask(9063):     at org.apache.http.impl.AbstractHttpClientConnection.receiveResponseHeader(AbstractHttpClientConnection.java:180)
12-26 14:36:18.539: E/WebServiceTask(9063):     at org.apache.http.impl.conn.DefaultClientConnection.receiveResponseHeader(DefaultClientConnection.java:235)
12-26 14:36:18.539: E/WebServiceTask(9063):     at org.apache.http.impl.conn.AbstractClientConnAdapter.receiveResponseHeader(AbstractClientConnAdapter.java:259)
12-26 14:36:18.539: E/WebServiceTask(9063):     at org.apache.http.protocol.HttpRequestExecutor.doReceiveResponse(HttpRequestExecutor.java:279)
12-26 14:36:18.539: E/WebServiceTask(9063):     at org.apache.http.protocol.HttpRequestExecutor.execute(HttpRequestExecutor.java:121)
12-26 14:36:18.539: E/WebServiceTask(9063):     at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:428)
12-26 14:36:18.539: E/WebServiceTask(9063):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
12-26 14:36:18.539: E/WebServiceTask(9063):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
12-26 14:36:18.539: E/WebServiceTask(9063):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
12-26 14:36:18.539: E/WebServiceTask(9063):     at Url.CallUrl.doResponse(CallUrl.java:308)
12-26 14:36:18.539: E/WebServiceTask(9063):     at Url.CallUrl.doInBackground(CallUrl.java:265)
12-26 14:36:18.539: E/WebServiceTask(9063):     at Url.CallUrl.doInBackground(CallUrl.java:1)
12-26 14:36:18.539: E/WebServiceTask(9063):     at android.os.AsyncTask$2.call(AsyncTask.java:264)
12-26 14:36:18.539: E/WebServiceTask(9063):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
12-26 14:36:18.539: E/WebServiceTask(9063):     at java.util.concurrent.FutureTask.run(FutureTask.java:137)
12-26 14:36:18.539: E/WebServiceTask(9063):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
12-26 14:36:18.539: E/WebServiceTask(9063):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
12-26 14:36:18.539: E/WebServiceTask(9063):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
12-26 14:36:18.539: E/WebServiceTask(9063):     at java.lang.Thread.run(Thread.java:856)
12-26 14:36:18.539: W/System.err(9063): org.json.JSONException: End of input at character 0 of 
12-26 14:36:18.539: W/System.err(9063):     at org.json.JSONTokener.syntaxError(JSONTokener.java:450)
12-26 14:36:18.547: W/System.err(9063):     at org.json.JSONTokener.nextValue(JSONTokener.java:97)
12-26 14:36:18.547: W/System.err(9063):     at org.json.JSONObject.<init>(JSONObject.java:154)
12-26 14:36:18.547: W/System.err(9063):     at org.json.JSONObject.<init>(JSONObject.java:171)
12-26 14:36:18.547: W/System.err(9063):     at Url.CallUrl.onPostExecute(CallUrl.java:217)
12-26 14:36:18.547: W/System.err(9063):     at Url.CallUrl.onPostExecute(CallUrl.java:1)
12-26 14:36:18.547: W/System.err(9063):     at android.os.AsyncTask.finish(AsyncTask.java:602)
12-26 14:36:18.547: W/System.err(9063):     at android.os.AsyncTask.access$600(AsyncTask.java:156)
12-26 14:36:18.547: W/System.err(9063):     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:615)
12-26 14:36:18.547: W/System.err(9063):     at android.os.Handler.dispatchMessage(Handler.java:99)
12-26 14:36:18.547: W/System.err(9063):     at android.os.Looper.loop(Looper.java:137)
12-26 14:36:18.547: W/System.err(9063):     at android.app.ActivityThread.main(ActivityThread.java:4514)
12-26 14:36:18.547: W/System.err(9063):     at java.lang.reflect.Method.invokeNative(Native Method)
12-26 14:36:18.547: W/System.err(9063):     at java.lang.reflect.Method.invoke(Method.java:511)
12-26 14:36:18.547: W/System.err(9063):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790)
12-26 14:36:18.547: W/System.err(9063):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
12-26 14:36:18.555: W/System.err(9063):     at dalvik.system.NativeStart.main(Native Method)
BenMorel
  • 34,448
  • 50
  • 182
  • 322
Takeshi Pham
  • 61
  • 1
  • 7

1 Answers1

2

After seeing you whole code and Log I had found few things and had one query.

Query:

1) Why are you using base64 for uploding images to server. There are many other way to upload images to server.

Issue found:

In second Code you had set socket connection Timeout and after seeing your log what I can see is the Connection to the server is taking time so your application is not able to upload anything to server and you are getting this Timeout Exception.

Solution:

1) Increase your Socket Connection Timeout time and then check once again.
2) Use some different way to upload Images to server

Parth Dani
  • 535
  • 4
  • 19
  • May I know why the OP needs to follow a different way apart from Base64? – Kanth Dec 26 '12 at 08:13
  • There are many issue with base64 method one of them is when user tries to upload multiple image using base64 the application get crash automatically due to memory overflow error.So its better to avoid base64 method – Parth Dani Dec 26 '12 at 08:16
  • Takeshi I guess you might need to do some hard work u might had checked on stack and u had got the result..nevet the less I myself had given answer before go to http://stackoverflow.com/questions/9770122/android-upload-image-from-gallery-to-server/9770378#9770378 and over there you will get the solution for your question – Parth Dani Dec 26 '12 at 08:21
  • Also Takeshi if you get your solution then accept my answer by clicking on tick mark next to my answer so that it will help others to solve their issue very easily.. – Parth Dani Dec 26 '12 at 08:22
  • But I never faced such issues while using it. @TakeshiPham What do you mean by guiding myself? Mind the words you utter. – Kanth Dec 26 '12 at 08:25
  • @Appu I had faced that issue when i was trying to upload 20 photos to server. The all the images were captured from camera and as soon as it start uploading 5th image my application was getting crashed.Also after researching for many days I had found that it was due to base64 since it converts images to string and making my memory to get overflow which indirectly cause my application to shut off – Parth Dani Dec 26 '12 at 08:37
  • if not use base64, you can guide me how else to put the image on the optimal server.Thank you very much – should i use ftp or http to upload image? – Takeshi Pham Dec 26 '12 at 08:38
  • @ParthDani Okay. Then which method you used as a counterpart for it? Suggest him the same. :) – Kanth Dec 26 '12 at 08:42
  • here, I just need one to upload an image.I do not upload multiple images at once – Takeshi Pham Dec 26 '12 at 08:44
  • @Appu I had used method which i had already mentioned in the answer at following link. Please go through it. http://stackoverflow.com/questions/9770122/android-upload-image-from-gallery-to-server/9770378#9770378 – Parth Dani Dec 26 '12 at 08:45