Android文件上傳可用於Form表單提交方式(適用於全部網絡框架)

參考:參考ajax

將須要上傳的內容轉換成HttpEntity,即可適用於全部的網絡請求框架網絡

(1)轉換成HttpEntity框架

public static HttpEntity makeMultipartEntity(List<NameValuePair> params, final Map<String, File> files) {
	    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
	    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);  //若是有SocketTimeoutException等狀況,可修改這個枚舉
	    //builder.setCharset(Charset.forName("UTF-8")); //不要用這個,會致使服務端接收不到參數
	    if (params != null && params.size() > 0) {
	        for (NameValuePair p : params) {
	            builder.addTextBody(p.getName(), p.getValue(), ContentType.TEXT_PLAIN.withCharset("UTF-8"));
	        }
	    }
	    if (files != null && files.size() > 0) {
	        Set<Entry<String, File>> entries = files.entrySet();
	        for (Entry<String, File> entry : entries) {
	            builder.addPart(entry.getKey(), new FileBody(entry.getValue()));
	        }
	    }
	    return builder.build();
	}

(2)使用此HttpEntity 例子使用AQuery進行測試ide

AQuery aQuery = new AQuery(this);
    	Map<String, File> files = new HashMap<String, File>();
    	files.put(path, file);
    	HttpEntity entity = CommUtil.makeMultipartEntity(null, files);
    	 Map<String, Object> params = new HashMap<String, Object>();
         params.put(AQuery.POST_ENTITY, entity);
    	aQuery.progress(dialog).ajax(CustomURL.POST_API_MEMBER_UPLOADAVATAR, params, JSONObject.class, new AjaxCallback<JSONObject>(){
    		@Override
    		public void callback(String url, JSONObject object,
    				AjaxStatus status) {
    			// TODO Auto-generated method stub
    			super.callback(url, object, status);
    		}
    	});

用到的兩個jar包 : httpcore-4.3.2.jar httpmime-4.3.5.jar測試

相關文章
相關標籤/搜索