Android客户端主要代码:
public ImageHttp(Context context) {
super(context);
filePath = context.getCacheDir().getAbsolutePath();
}
public void uploadUserImg(Bitmap bitmap,
IHttpSenderCallBack<String> callback) {
this.callback = callback;
File file = getFile(bitmap);
// 注意与服务端协商
if (file == null) {
return;
}
List<Parameter> parameters = new ArrayList<Parameter>();
parameters.add(new Parameter("file", file));
uploadFile("uploadImg", parameters);
}
private File getFile(Bitmap bitmap) {
File file = null;
String path = filePath + "/image.jpg";
if (bitmap != null && !StringUtil.emptyOrNull(path)) {
try {
FileOutputStream out = new FileOutputStream(path);
bitmap.compress(Bitmap.CompressFormat.JPEG, 60, out);
out.flush();
out.close();
file = new File(path);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
return file;
}
protected String uploadFile(String methodName, List<Parameter> parameter) {
String errorMsg = "";
try {
String serviceUrl = getPostUrl(methodName);
HttpPost httpPost = new HttpPost(serviceUrl);
//采用http4包,不需要再添加 multipart/form-data表单 ,切记,这儿耽搁了好久
MultipartEntity mpEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE); // 文件传输
if (parameter != null && !parameter.isEmpty()) {
for (int i = 0; i < parameter.size(); i++) {
Parameter p = parameter.get(i);
if ("file".equals(p.getKey())) {
mpEntity.addPart(p.getKey(),
new FileBody(((File) p.getValue())));
} else {
mpEntity.addPart(p.getKey(), new StringBody(p
.getValue().toString()));
}
}
httpPost.setEntity(mpEntity);
}
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(
CoreConnectionPNames.CONNECTION_TIMEOUT, TIMEOUT);
httpclient.getParams().setParameter(
CoreConnectionPNames.SO_TIMEOUT, TIMEOUT);
HttpResponse httpResponse = httpclient.execute(httpPost);
String result = "";
int status = httpResponse.getStatusLine().getStatusCode();
LogUtil.d("httpResponseCode--------->" + status);
if (status == HttpStatus.SC_OK) {
result = EntityUtils.toString(httpResponse.getEntity());
}
parseProperty_(result, methodName);
result = "";
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return errorMsg;
}
原文:http://blog.csdn.net/u010427035/article/details/41699155