上传图片 - 发送请求到PHP脚本 - Android

时间:2013-07-25 09:06:48

标签: php android post upload request

我想通过将图像发送到php脚本来上传图像。如果互联网连接良好,它工作正常。但有时它不起作用。例如。当互联网连接缓慢。 所以我正在寻找一种通过慢速连接上传图像的方法。 我能做什么?文件大小已经非常小,大约40kb。 代码应该尝试上传图像直到完成。

修改:上传代码:

public void upload(String uploadImage){
     SharedPreferences settings = getSharedPreferences("App", 0);
     String emailaddress = settings.getString("mailaddress", null);
     ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
     nameValuePairs.add(new BasicNameValuePair("image",uploadImage));
     nameValuePairs.add(new BasicNameValuePair("email", emailaddress));
     try{
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new
            HttpPost("http://domain.de/uploadImage.php");
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();
     }catch(Exception e){
            try {
            Thread.sleep( 10000 );
            }catch (InterruptedException e1) {
            e1.printStackTrace();
            }
            upload(uploadImage);
     }
}

1 个答案:

答案 0 :(得分:0)

使用AsyncTask在后台运行上传过程..您可以在加载操作时显示进度条。

public class UploadProgress extends AsyncTask<Void, Void, Void>
{  
@Override
protected void onPreExecute()
{  
super.onPreExecute();
dialog.setMessage("Please wait...");
dialog.setCancelable(false);
dialog.show(); 
} 
@Override 
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
// Things to be done while execution of long running operation is in progress. For example updating ProgessDialog
}

@Override 
protected void onPostExecute(Void result) 
{ 
  //Post Execute
   dialog.cancel();
}
@Override
protected Void doInBackground(Void... params) {

// Your operation..Dont Edit Any Views here
boolean isDataSubmitted = false;
        while (!isDataSubmitted) {
            count++;
            if (count < 2)//Count depends on you {
                try {
                   //Call your upload  method here 
                   //If its success your dataSubmitted will go true

                   isDataSubmitted = true;
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
        }

return null;
}