安卓中,对图片用表单上传方式去上传到服务器,一直都是我心中的痛....开始的时候,在上传文本的http请求服务器的方式去提交,提交图片失败,后来,使用了第三方的框架去做这个事情成功了,再后来,回归到自己用原生的代码去写这个提交图片,今天当是做一个总结吧。把一件重要的事情记录下来,给它画上句号吧。
图片表单上传方法:
1、
// modified by LPY
//表单方式上传图片及其它参数
private void doUploadImage() {
try {
String url = RequestUrl.BASE_WEB_URL + "imageupload.do?";
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
ContentBody fileBody = new FileBody(photoFile, "image/jpeg");
MultipartEntity entity = new MultipartEntity();
// TODO : mobile字符串该则么传要确认下
entity.addPart("mobile", new StringBody(mobile));
entity.addPart("key", new StringBody("WZDFKYT++"));
entity.addPart("file", fileBody);
post.setEntity(entity);
HttpResponse response = client.execute(post);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
String result = EntityUtils.toString(response.getEntity(), "utf-8");
JSONObject jsonObject = new JSONObject(result);
logo = jsonObject.getString("path");
Log.i("LPY_DEBUG","拍照后上传返回的网络图片路径logo = " + logo);
Message msg = new Message();
msg.what = jsonObject.getInt("result");
msg.obj = jsonObject.getString("path");
bindhandler.sendMessage(msg);
} else {
bindhandler.sendEmptyMessage(-1);
}
client.getConnectionManager().shutdown();
} catch (Exception e) {
bindhandler.sendEmptyMessage(-1);
// e.printStackTrace();
}
}
private Handler bindhandler = new Handler() {
public void handleMessage(android.os.Message msg) {
// progressDialog.dismiss();
if (msg.what == 1) {}
}
};
2、把方法提取出来
/**
* 提交参数里有文件的数据
*
* @param url
* 服务器地址
* @param param
* 参数
* @return 服务器返回结果
* @throws Exception
*/
public static String uploadSubmit(String url, Map<String, String> param,
File file) throws Exception {
HttpPost post = new HttpPost(url);
MultipartEntity entity = new MultipartEntity();
if (param != null && !param.isEmpty()) {
for (Map.Entry<String, String> entry : param.entrySet()) {
if (entry.getValue() != null
&& entry.getValue().trim().length() > 0) {
entity.addPart(entry.getKey(),
new StringBody(entry.getValue()));
}
}
}
// 添加文件参数
if (file != null && file.exists()) {
entity.addPart("file", new FileBody(file));
}
post.setEntity(entity);
HttpResponse response = httpClient.execute(post);
int stateCode = response.getStatusLine().getStatusCode();
StringBuffer sb = new StringBuffer();
if (stateCode == HttpStatus.SC_OK) {
HttpEntity result = response.getEntity();
if (result != null) {
InputStream is = result.getContent();
BufferedReader br = new BufferedReader(
new InputStreamReader(is));
String tempLine;
while ((tempLine = br.readLine()) != null) {
sb.append(tempLine);
}
}
}
post.abort();
return sb.toString();
}