Android 使用HttpClient和第三方MIME文件上传类库,实现文件上传

转自:http://blog.csdn.net/liwei3gjob/article/details/7870360

MainActivity中定义的方法

private void httpUpload() {
		
    	//定义HttpClient对象
		HttpClient client = new DefaultHttpClient();
		//获得HttpPost对象
		HttpPost post = new HttpPost("http://192.168.1.106:8001/2012/upload.php");
		post.addHeader("charset", HTTP.UTF_8);  
		//实例化
		MultipartEntity me = new MultipartEntity();
		
		try {
			
			me.addPart("content",new StringBody("12cccafasdfasdf"));
			me.addPart("title",new StringBody("csdnliwei"));
			me.addPart("local",new StringBody("beijing"));
			//设置流文件
			me.addPart("file", new InputStreamBody(new FileInputStream("/mnt/sdcard/test.jpg"), "image/pjpeg", "fengjie.jpg"));
			
			post.setEntity(me);
			//获得响应消息
			HttpResponse resp = client.execute(post);
			
			if(resp.getStatusLine().getStatusCode()==200){
				
				Toast.makeText(this, "文件上传文成!", 1).show();
				
			}
			
		} catch (Exception e) {
			
			e.printStackTrace();
		}
    	
	}


服务器端PHP程序:


<?php
header("Content-type:text/html;charset=utf-8");

print_r($_FILES['file']);

$filename = $_FILES['file']['name'];

if(!$_FILES['file']['error']){
	
   if(move_uploaded_file($_FILES['file']['tmp_name'],"./upload/".$filename)){
	   
	     echo "文件上传成功";
	   
	   }else{
		   echo "文件上传失败le";
		   }

}else{
	
	echo "文件上传错误";
	}

 ?>


Android-HttpClient上传信息(包括图片)到服务端

需要下载apache公司下的HttpComponents项目下的HTTPCLIENT

----------地址为http://hc.apache.org/downloads.cgi

主要是用到了httpmime-4.1.2.jar包

android客户端:

以下是请求action的jsp表单(测试用)

<form action="AddFoodStyle" enctype="multipart/form-data" method="post">    
    <div style="width:300px;">
        <s:textfield label="菜式名称" name="foodname"></s:textfield><br/>       
        <s:select name="foodstyle" list="list" label="菜式类别" listKey="Itemid" listValue="itemname"  >

        </s:select><br/>       
        <s:textfield label="菜式价格" name="price"></s:textfield><br/>       
        <s:file label="菜式图片" name="foodimg"></s:file><br/>        
        <s:textarea label="菜式标签" name="foodtab" cols="20"  cssStyle=""></s:textarea><br/>       
        <s:textfield label="菜式状态" name="state"></s:textfield><br/>        
        <s:submit value="添加"/>
        </div>        
    </form>
模拟构造上面的请求表单
    private String url="http://192.168.2.189:8080/MyOrderMeal/AddFoodStyle";
     HttpClient httpclient= new DefaultHttpClient();
     HttpPost httpPost= new HttpPost(url);
     MultipartEntity mulentity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        mulentity.addPart("foodname", new StringBody(foodname.getText().toString().trim()));
        mulentity.addPart("foodstyle", new StringBody(foodstyle.getText().toString().trim()));
        mulentity.addPart("price", new StringBody(foodprice.getText().toString().trim()));  
       //添加图片表单数据        
        FileBody filebody = new FileBody(this.image);        
        mulentity.addPart("foodimg",filebody );    
        mulentity.addPart("foodtab", new StringBody(foodtab.getText().toString().trim()));
        mulentity.addPart("state", new StringBody("1"));         
        httpPost.setEntity(mulentity);
        HttpResponse response =    httpclient.execute(httpPost);
        
        if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK)
        {
            makeToase("上传成功",true);
            if(this.image.exists())
            this.image.delete();
        }
        else
        {
            makeToase("上传失败",true);
        }
服务端:action的配置

  <action name="AddFoodStyle" class="com.ordermeal.xiao.action.AddFoodStyle">
          <result name="success" type="redirect">/ShowAddFoodStyle</result>
     </action>

action的编写


public class AddFoodStyle extends ActionSupport{
    /**
     * 
     */
    private static final long serialVersionUID = -8380963167787044860L;
    
    private String foodname;
    private Integer foodstyle;
    private Double price;
    
   //接收上传文件
    private File foodimg;
    private String foodimgFileName;
    private String foodimgContentType;
    
    private String foodtab;
    private Integer state;
@Override
    public String execute() throws Exception {        
        
        FoodStyleDao fsd = DaoFactory.getFoodStyleDao();
        FoodStyle  foodstyleob= new FoodStyle();        
        foodstyleob.setFoodname(foodname);
        foodstyleob.setMystyletype(foodstyle);
        foodstyleob.setFoodprice(price);
        foodstyleob.setImageurl(foodimgFileName);
        foodstyleob.setFoodtab(foodtab);
        foodstyleob.setFdstystate(state);       
        fsd.addFoodStyle(foodstyleob);
        String path= ServletActionContext.getServletContext().getRealPath("/");
       //保存上传文件
       FileUtil.copyFile(foodimg, path+"/images/"+foodimgFileName);
       return SUCCESS;
    }






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值