异步上传文件

Posted zhongyinghe

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了异步上传文件相关的知识,希望对你有一定的参考价值。

 1 package com.example.asyncuploadfile;
 2 
 3 import java.io.File;
 4 import java.io.FileNotFoundException;
 5 
 6 import org.apache.http.Header;
 7 
 8 import com.loopj.android.http.AsyncHttpClient;
 9 import com.loopj.android.http.AsyncHttpResponseHandler;
10 import com.loopj.android.http.RequestParams;
11 
12 import android.os.Bundle;
13 import android.app.Activity;
14 import android.view.Menu;
15 import android.view.View;
16 import android.widget.EditText;
17 import android.widget.Toast;
18 
19 public class MainActivity extends Activity {
20 
21     private EditText et_path;
22     @Override
23     protected void onCreate(Bundle savedInstanceState) {
24         super.onCreate(savedInstanceState);
25         setContentView(R.layout.activity_main);
26         et_path = (EditText)findViewById(R.id.et_path);
27     }
28 
29     public void upload(View view){
30         String file_path = et_path.getText().toString().trim();
31         
32         AsyncHttpClient client = new AsyncHttpClient();
33         String url = "http://202.96.2.149/android/upload.php";
34         
35         File file = new File(file_path);
36         RequestParams params = new RequestParams();
37         params.put("username", "zhangsan");
38         params.put("password", "123456");
39         try {
40             params.put("myfile", file);
41         } catch (FileNotFoundException e) {
42             // TODO Auto-generated catch block
43             e.printStackTrace();
44             return;
45         }
46         client.post(url, params, new AsyncHttpResponseHandler(){
47 
48             @Override
49             public void onSuccess(int statusCode, Header[] headers,
50                     byte[] responseBody) {
51                 // TODO Auto-generated method stub
52                 String result = new String(responseBody);
53                 Toast.makeText(MainActivity.this, result, 0).show();
54                 
55             }
56 
57             @Override
58             public void onFailure(int statusCode, Header[] headers,
59                     byte[] responseBody, Throwable error) {
60                 // TODO Auto-generated method stub
61                 Toast.makeText(MainActivity.this, "请求失败!", 0).show();
62                 
63             }
64             
65         });
66     }
67 
68 }

 

以上是关于异步上传文件的主要内容,如果未能解决你的问题,请参考以下文章

求一段JS或Jquery异步上传图片的代码

ajax springMvc 异步 上传 文件

利用ajaxfileupload.js异步上传文件

摒弃FORM表单上传图片,异步批量上传照片

阿里巴巴文件异步上传

Alamofire 文件上传出现错误“JSON 文本未以数组或对象开头,并且允许未设置片段的选项”