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:filelabel="菜式图片"name="foodimg"></s:file><br/>
<s:textarealabel="菜式标签"name="foodtab"cols="20"cssstyle=""></s:textarea><br/>
<s:textfieldlabel="菜式状态"name="state"></s:textfield><br/>
<s:submitvalue="添加"/>
</div>
</form>模拟构造上面的请求表单:
private String url="http://192.168.2.189:8080/MyOrderMeal/AddFoodStyle";
HttpClient httpclient= new DefaultHttpClient();
HttpPosthttpPost=newHttpPost(url);
MultipartEntitymulentity=newMultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
mulentity.addPart("foodname",newStringBody(foodname.getText().toString().trim()));
mulentity.addPart("foodstyle",newStringBody(foodstyle.getText().toString().trim()));
mulentity.addPart("price", new StringBody(foodprice.getText().toString().trim()));//添加图片表单数据
FileBodyfilebody=newFileBody(this.image);
mulentity.addPart("foodimg",filebody);
mulentity.addPart("foodtab",newStringBody(foodtab.getText().toString().trim()));
mulentity.addPart("state",newStringBody("1"));
httpPost.setEntity(mulentity);
HttpResponseresponse=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">
<resultname="success"type="redirect">/ShowAddFoodStyle</result>
</action>
action的编写public class AddFoodStyle extends ActionSupport{/**
*
*/
privatestaticfinallongserialVersionUID=-8380963167787044860L;
privateStringfoodname;
privateIntegerfoodstyle;
privateDoubleprice;
//接收上传文件
private File foodimg;privateStringfoodimgFileName;
privateStringfoodimgContentType;
privateStringfoodtab;
private Integer state;
、、、、省略get set方法
@OverridepublicStringexecute()throwsException{
FoodStyleDaofsd=DaoFactory.getFoodStyleDao();
FoodStylefoodstyleob=newFoodStyle();
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;
}
相关推荐
创建一个 HttpClient 实例,这个实例需要调用 Dispose 方法释放资源,这里使用了 using 语句。接着调用 GetAsync,给它传递要调用的方法的地址,向服务器发送 Get 请求。