需要依赖 httpmime.jar
/** * 上传图片 * * @param url * 上传地址 * @param filepath * 图片路径 * @return */ public String uploadImage(String url, String filepath) { File file = new File(filepath); if (!file.exists()) { Log.i("leslie", "file not exists"); return null; } HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(url); FileBody fileBody = new FileBody(file, "image/jpeg"); MultipartEntity entity = new MultipartEntity(); // image 是服务端读取文件的 key entity.addPart("image", fileBody); post.setEntity(entity); try { HttpResponse response = client.execute(post); int statusCode = response.getStatusLine().getStatusCode(); String result = EntityUtils.toString(response.getEntity(), "utf-8"); if (statusCode == 201) { // upload success // do something } return result; } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; }