1. 首先到Appache官网下载第三方jar包httpmime(可以到这里下载http://download.csdn.net/detail/likesidehu/9651525,这个jar包配合下面代码验证没问题)
2. 服务器地址: http://localhost:8080/xxx/xxx/xxx
3. 本地图片地址/sdcard/Pictures/abc.png
4.具体代码:
private class UploadTask extends AsyncTask<String, Integer, String> { private Activity mContext; public UploadTask(Activity context) { this.mContext = context; } @Override protected String doInBackground(String... urls) { for (String url : urls) { uploadFile(url); } return null; } protected void onPostExecute(String result) { } protected void onProgressUpdate(Integer... progress) { } // upload photos public void uploadFile(String uploadFile) { try{ HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(UPLOAD_SERVER); MultipartEntity mpEntity = new MultipartEntity(); File file = new File(uploadFile); ContentBody cbFile = new FileBody(file); mpEntity.addPart("imgFile", cbFile); mpEntity.addPart("user_id", new StringBody("123")); mpEntity.addPart("pic_note", new StringBody("test", Charset.forName("utf-8"))); mpEntity.addPart("pic_address", new StringBody("test", Charset.forName("utf-8"))); httppost.setEntity(mpEntity); HttpResponse response = httpclient.execute(httppost); int statusCode=response.getStatusLine().getStatusCode(); if(200 == statusCode){ showToast(getString(R.string.upload_ok)); String result = EntityUtils.toString(response.getEntity()); } httpclient.getConnectionManager().shutdown(); }catch(Exception e){ e.printStackTrace(); } } }
UploadTask ut = new UploadTask(SpotsActivity.this); ut.execute(urls); //urls为本地图片路径数组