android-HttpClient上傳信息(包括圖片)到服務端
需要下載apache公司下的HttpComponents項目下的HTTPCLIENT
----------地址為https://hc.apache.org/downloads.cgi
主要是用到了httpmime-4.1.2.jar包
android客戶端:
以下是請求action的jsp表單(測試用)
<form action="AddFoodStyle" enctype="multipart/form-data" method="post"> <div > <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="https://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" >
<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; 、、、、省略get set方法 @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; }
最後更新:2017-04-03 22:30:57