Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
236 views
in Technique[技术] by (71.8m points)

java - How can I use an Async Task to upload a file to the server?

Below is my code for uploading a file to the server. But I'm getting network exceptions even after several tries and even after adding strict mode.

I'm new to Android and don't know how can I use the async task, which many people advised for such kind of network operation. Could anyone tell me that where I'm wrong in the code and where should I use async task?

package de.fileuploader;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

@SuppressWarnings("unused")
 public class Android_helloActivity extends Activity {

private String newName = "SMSBackup.txt";
private String uploadFile = "/mnt/sdcard/SMSBackup.txt";
private String actionUrl = "http://192.168.1.8:8080/admin/admin/uploads";
// private String
// actionUrl="http://upload-file.shcloudapi.appspot.com/upload";
private TextView mText1;
private TextView mText2;
private Button mButton;

@Override
public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()  
        .detectDiskReads()  
        .detectDiskWrites()  
        .detectNetwork()   // or .detectAll() for all detectable problems  
        .penaltyLog()  
        .build());  
       StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()  
        .detectLeakedSqlLiteObjects()  
        .detectLeakedClosableObjects()  
        .penaltyLog()  
        .penaltyDeath()  
        .build()); 

        mText1 = (TextView) findViewById(R.id.myText2);
        mText1.setText("Upload
" + uploadFile);
        mText2 = (TextView) findViewById(R.id.myText3);
        mText2.setText("To Server Location
" + actionUrl);

        mButton = (Button) findViewById(R.id.myButton);
        mButton.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                        /* uploadFile(); */
                        try {
                                HttpClient httpClient = new DefaultHttpClient();
                                HttpContext localContext = new BasicHttpContext();
                                HttpPost httpPost = new HttpPost(actionUrl);

                                MultipartEntity entity = new MultipartEntity(
                                                HttpMultipartMode.BROWSER_COMPATIBLE);
                                entity.addPart("name", new StringBody(newName));
                                File file=new File(uploadFile);
                                entity.addPart("file", new FileBody(file));
                                //entity.addPart("file", new
                                ByteArrayBody(data,"myImage.jpg"));
                                entity.addPart("gps", new StringBody("35.6,108.6"));
                                httpPost.setEntity(entity);
                                HttpResponse response = httpClient.execute(httpPost,
                                                localContext);
                                BufferedReader reader = new BufferedReader(
                                                new  
                               InputStreamReader(response.getEntity().getContent(), 
                                 "UTF-8"));

                                String sResponse = reader.readLine();
                                Log.i("info", "test");
                                  } catch (Exception e) {
                                // Log.e("exception", e.printStackTrace());
                                 e.printStackTrace();
                                showDialog("" + e);
                               } 
                               }
                               });
                               }


                          private void showDialog(String mess) {
                new AlertDialog.Builder(Android_helloActivity.this).setTitle("Message")
                         .setMessage(mess)
                        .setNegativeButton("Exit", new  DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which)      {
                                }
                        }).show();
 }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
mButton.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {

new UploadImageTask().execute(); // initialize asynchronous task

}});

//Now implement Asynchronous Task


public class Get_User_Data extends AsyncTask<Void, Void, Void> {

            private final ProgressDialog dialog = new ProgressDialog(
            MyActivity.this);

    protected void onPreExecute() {
        this.dialog.setMessage("Loading...");
        this.dialog.setCancelable(false);
        this.dialog.show();
    }
        @Override
        protected Void doInBackground(Void... params) {

                    uploadImage(); // inside the method paste your file uploading code
            return null;
        }

        protected void onPostExecute(Void result) {

            // Here if you wish to do future process for ex. move to another activity do here

            if (dialog.isShowing()) {
                dialog.dismiss();
            }

        }
    }

For more information refer this link http://vikaskanani.wordpress.com/2011/01/29/android-image-upload-activity/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...