我如何使用一个异步任务将文件上传到服务器?

人气:1,104 发布:2022-09-12 标签: java android

问题描述

下面是我的code上传文件到服务器。但我即使经过多次尝试,甚至之后加入严格的方式获得网络异常。我是新来的Andr​​oid和不知道我该如何使用异步任务,并在尽可能多的人建议对这种类型的网络操作。难道任何一个可以告诉我,在这里我错了,在code和我应该在哪里使用异步任务?

 包de.fileuploader;

进口java.io.BufferedReader中;
进口的java.io.File;
进口java.io.InputStreamReader中;

进口org.apache.http.Htt presponse;
进口org.apache.http.client.HttpClient;
进口org.apache.http.client.methods.HttpPost;
进口org.apache.http.entity.mime.HttpMultipartMode;
进口org.apache.http.entity.mime.MultipartEntity;
进口org.apache.http.entity.mime.content.ByteArrayBody;
进口org.apache.http.entity.mime.content.FileBody;
进口org.apache.http.entity.mime.content.StringBody;
进口org.apache.http.impl.client.DefaultHttpClient;
进口org.apache.http.protocol.BasicHttpContext;
进口org.apache.http.protocol.HttpContext;

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

@燮pressWarnings(未使用)
 公共类Android_helloActivity延伸活动{

私人字符串了newName =SMSBackup.txt;
私人字符串uploadFile =/mnt/sdcard/SMSBackup.txt;
私人字符串actionUrl =htt​​p://192.168.1.8:8080/admin/admin/uploads;
//私人字符串
// actionUrl =htt​​p://upload-file.shcloudapi.appspot.com/upload;
私人TextView的mText1;
私人TextView的mText2;
私人按钮mButton;

@覆盖
公共无效的onCreate(包savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.main);
        StrictMode.setThreadPolicy(新StrictMode.ThreadPolicy.Builder()
        .detectDiskReads()
        .detectDiskWrites()
        .detectNetwork()//或.detectAll()的所有检测到的问题
        .penaltyLog()
        。建立());
       StrictMode.setVmPolicy(新StrictMode.VmPolicy.Builder()
        .detectLeakedSqlLiteObjects()
        .detectLeakedClosableObjects()
        .penaltyLog()
        .penaltyDeath()
        。建立());

        mText1 =(TextView中)findViewById(R.id.myText2);
        mText1.setText(上传\ N+ uploadFile);
        mText2 =(TextView中)findViewById(R.id.myText3);
        mText2.setText(目​​标服务器位置\ N+ actionUrl);

        mButton =(按钮)findViewById(R.id.myButton);
        mButton.setOnClickListener(新View.OnClickListener(){
                公共无效的onClick(视图v){
                        /* 上传文件(); * /
                        尝试 {
                                HttpClient的HttpClient的=新DefaultHttpClient();
                                HttpContext的localContext =新BasicHttpContext();
                                HttpPost httpPost =新HttpPost(actionUrl);

                                MultipartEntity实体=新MultipartEntity(
                                                HttpMultipartMode.BROWSER_COMPATIBLE);
                                entity.addPart(名,新StringBody(了newName));
                                档案文件=新的文件(uploadFile);
                                entity.addPart(文件,新FileBody(文件));
                                //entity.addPart("file,新
                                ByteArrayBody(数据myImage.jpg这个参数));
                                entity.addPart(全球定位系统,新StringBody(35.6,108.6));
                                httpPost.setEntity(实体);
                                HTT presponse响应= httpClient.execute(httpPost,
                                                localContext);
                                的BufferedReader读卡器=新的BufferedReader(
                                                新
                               InputStreamReader的(response.getEntity()的getContent()
                                 UTF-8));

                                串sResponse = reader.readLine();
                                Log.i(信息,测试);
                                  }赶上(例外五){
                                // Log.e(异常,e.printStackTrace());
                                 e.printStackTrace();
                                的ShowDialog(+ E);
                               }
                               }
                               });
                               }


                          私人无效的ShowDialog(字符串一塌糊涂){
                新AlertDialog.Builder(Android_helloActivity.this).setTitle(消息)
                         .setMessage(乱)
                        .setNegativeButton(退出,新DialogInterface.OnClickListener(){
                                公共无效的onClick(DialogInterface对话,诠释它){
                                }
                        })。显示();
 }
}
 

请帮我在这方面尽快。

解决方案

  mButton.setOnClickListener(新View.OnClickListener(){
                公共无效的onClick(视图v){

新UploadImageTask()执行()。 //初始化异步任务

}});

//现在实现异步任务


公共类Get_User_Data扩展的AsyncTask<虚空,虚空,虚空> {

            私人最终ProgressDialog对话框=新ProgressDialog(
            MyActivity.this);

    在preExecute保护无效(){
        this.dialog.setMessage(载入中...);
        this.dialog.setCancelable(假);
        this.dialog.show();
    }
        @覆盖
        保护无效doInBackground(虚空...... PARAMS){

                    上传图片(); //在方法内部粘贴您的文件上传code
            返回null;
        }

        保护无效onPostExecute(无效的结果){

            //如果你希望做未来的过程中为前这里。移动到另一个活动在这里做

            如果(dialog.isShowing()){
                dialog.dismiss();
            }

        }
    }
 

有关详细信息,请参阅此链接 HTTP ://vikaskanani.word$p$pss.com/2011/01/29/android-image-upload-activity/

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 and where as many people advised for such kind of network operation. Could any one 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\n" + uploadFile);
        mText2 = (TextView) findViewById(R.id.myText3);
        mText2.setText("To Server Location\n" + 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();
 }
}

Please help me in this regard ASAP.

解决方案

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/

245