android4.0下用httpclient访问服务器上传文件

mainactivity.java

package com.example.android_camera_upload;

import java.io.ByteArrayOutputStream;

import org.apache.http.util.ByteArrayBuffer;

import com.example.android_camera_upload.R;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class MainActivity extends Activity {
private Button button1;
private Button button2;
private ImageView imageview1;
private byte[] image_data; // 存儲圖片的數據
private final String upload_pathString="http://166.111.82.103:8080/uploadImage"
+ "/"+"/servlet/UploadAction";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);
imageview1 = (ImageView) findViewById(R.id.imageView1);
button1.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 1000);
}
});
button2.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.i("调试信息","执行post");
HttpPostUtils.sendFormByPost(upload_pathString, image_data, "aa.png");
}
});

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1000 && resultCode == RESULT_OK) {
Bundle bundle = data.getExtras();
Bitmap bm = (Bitmap) bundle.get("data");
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 50, outputStream);
image_data = outputStream.toByteArray();
imageview1.setImageBitmap(bm);

}
}

}

下面是一个工具类,其中的调试信息可以注册掉

package com.example.android_camera_upload;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.impl.client.DefaultHttpClient;

import android.util.Log;

public class HttpPostUtils {
public static void sendFormByPost(final String path,
final byte[] fileBody, final String fileName) {
boolean flag = false;
new Thread(new Runnable() {

@Override
public void run() {
// TODO Auto-generated method stub
try {
HttpClient httpClient=new DefaultHttpClient();
Log.i("調試信息","111");
HttpPost httpPost=new HttpPost(path);
Log.i("調試信息","2");
MultipartEntity entity=new MultipartEntity();
Log.i("調試信息","3");
entity.addPart("myfile",new ByteArrayBody(fileBody, fileName));
Log.i("調試信息","4");
httpPost.setEntity(entity);
Log.i("調試信息","5");
HttpResponse httpResponse=httpClient.execute(httpPost);
Log.i("htttp返回状态",(httpResponse.getStatusLine().getStatusCode())+"i");
if(httpResponse.getStatusLine().getStatusCode()==HttpStatus.SC_OK)
{
Log.i("調試信息","6");
Log.i("調試信息","76");
}
} catch (Exception e) {
Log.i("調試信息","错误");
e.printStackTrace();
// TODO: handle exception
}
}
}).start();
// return flag;
}
}

下面是在myeclipse下写的服务器端servlet:

package com.image.upload;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class UploadAction extends HttpServlet {


public UploadAction() {

super();
}


public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}


public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

this.doPost(request, response);


}


public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String path = request.getContextPath();

//实例化一个磁盘文件工厂,用来配置上传组件ServletFileUpload
DiskFileItemFactory factory = new DiskFileItemFactory();
//System.out.println("调试信息2");
//用上面的工厂实例化上传组件
ServletFileUpload fileUpload = new ServletFileUpload(factory);

//fileUpload.setFileItemFactory(factory);

fileUpload.setSizeMax(4 * 1024 * 1024);
fileUpload.setFileSizeMax(2 * 1024 * 1024);

List<FileItem> list = null;

try {

//解析request,处理客户端传来的所有表单数据,返回list(包括file和非file类型)
list = fileUpload.parseRequest(request);

for (FileItem item : list) {
// 判断客户端传来的form表单中 是否是一个file类型
//文件类型
if(!item.isFormField())
{
//得到文件的名称
String imageString = item.getName();

String file_upload_path=request.getRealPath("/upload")+"/"+imageString;
System.out.println("图片上传路径-------》"+file_upload_path);

item.write(new File(file_upload_path));
}
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}


}


public void init() throws ServletException {
// Put your code here
}

}

最后一定要记得在manifest中加入网络访问权限。

android4.0下用httpclient访问服务器上传文件,布布扣,bubuko.com

android4.0下用httpclient访问服务器上传文件

上一篇:Android四大基本组件介绍与生命周期


下一篇:Android特性与系统架构