Android -- 文件上传到服务器

1. 文件上传的两种方式

(1) HttpClient

(2)AsyncHttpClient (开源框架: https://github.com/loopj/android-async-http

 

示例代码(2)最简单

public void upload(View v){
		String path = et_path.getText().toString().trim();
		File file = new File(path);
		String uri = "http://192.168.1.100:8080/TestLogin/servlet/UploadFile";
		if(file.exists() && file.length()>0){
			AsyncHttpClient client = new AsyncHttpClient();
			RequestParams params = new RequestParams();
			try {
				params.put("profile_picture", file);
			} catch (FileNotFoundException e) {			
				e.printStackTrace();
			}
			client.post(uri, params, new AsyncHttpResponseHandler(){

				@Override				
				public void onFailure(Throwable error, String content) {
					Toast.makeText(MainActivity.this, "上传失败", Toast.LENGTH_SHORT).show();
				}

				@Override
				public void onSuccess(String content) {
					Toast.makeText(MainActivity.this, "上传成功", Toast.LENGTH_SHORT).show();
				}
				
			});					
		}else{
			Toast.makeText(this, "文件不存在", Toast.LENGTH_SHORT).show();
		}
	}


示例代码(1)

public void upload(View viwe){
		HttpClient client = new HttpClient();
		 PostMethod filePost = new PostMethod("http://192.168.1.100:8080/web/UploadServlet");;
    	try {
			String path = et_path.getText().toString().trim();
			File file = new File(path);
			if(file.exists()&&file.length()>0){
				Part[] parts = {new StringPart("nameaaaa", "valueaaa"), 
					  new StringPart("namebbb", "valuebbb"), 
					  new FilePart("pic", new File(file.getAbsolutePath()))};
			  filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
			  client.getHttpConnectionManager().getParams()
			      .setConnectionTimeout(5000);
			  int status = client.executeMethod(filePost);
			  if(status ==200){
				  Toast.makeText(this, "上传成功", 1).show();
			  }else{
				  Toast.makeText(this, "上传失败", 1).show();
			  }
			  
			}
			else{
				Toast.makeText(this, "上传的文件不存在", 0).show();
			}
		} catch (Exception e) {
			e.printStackTrace();
			filePost.releaseConnection();
		}
    	
    }


 

posted @ 2014-03-28 10:12  今晚打酱油_  阅读(213)  评论(0编辑  收藏  举报