使用MultipartEntity上传单张图片。用了下面的代码,但是图片没有上传,也没有任何错误提示。
我将所有的数据库都加载了。
try { HttpClient httpClient = new DefaultHttpClient(); HttpPost postRequest = new HttpPost( "http://192.168.1.6/uploadimg.php"); httpClient.getParams().setParameter( CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); File f = null; FileBody fo = null; MultipartEntity reqEntity = new MultipartEntity( HttpMultipartMode.BROWSER_COMPATIBLE); //ContentBody cb = new ByteArrayBody(by, System.currentTimeMillis() + ".jpg");//字节上传用 // code for send image using post method f = new File("/mnt/sdcard/a.png"); fo = new FileBody(f); reqEntity.addPart("uploaded", fo); Log.i("uploaded", "image added Parameter added"); postRequest.setEntity(reqEntity); HttpResponse response = httpClient.execute(postRequest); BufferedReader reader = new BufferedReader(new InputStreamReader( response.getEntity().getContent(), "UTF-8")); String sResponse; StringBuilder s = new StringBuilder(); while ((sResponse = reader.readLine()) != null) { s = s.append(sResponse); } Log.v("Upload photo", "Response" + s); // return getUploadResponce(s.toString()); // Log.i("Response ", ); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }
项目中的一个方法,仅供参考
KeyValue 是一个只有key和value的基础类,values中是存储所有要发送的文件的地址【ArrayList】
/**
* 发送文件和基础数据
*
* @param netpath
* @return
*/
@SuppressWarnings("rawtypes")
public boolean sendForm(String netpath) {
String path = netpath;
boolean res = false;
try {
HttpPost httpPost = new HttpPost(path);
MultipartEntityBuilder entityBuilder = MultipartEntityBuilder
.create();
// 设置为浏览器兼容模式
entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
// 设置请求的编码格式
// entityBuilder.setCharset(Charset.forName(HTTP.UTF_8));
entityBuilder.setCharset(Charset.forName(HTTP.UTF_8));
for (KeyValue keyValue : beanData.getKeyvalues()) {
entityBuilder.addTextBody(
keyValue.getKey(),
keyValue.getValue(),
ContentType.create("text/plain",
Charset.forName(this.charset)));
}
// Iterator it = paths.entrySet().iterator();
// while(it.hasNext()){
// Entry entry = (Entry) it.next();
// entityBuilder.addBinaryBody("file", new File((String)
// entry.getValue()));
// paths.remove(entry.getKey());
// }
for (int i = 0; i < values.size(); i++) {
entityBuilder.addBinaryBody("file", new File(values.get(i)));
}
httpPost.setEntity(entityBuilder.build());
// httpPost.setHeader("Content-type", "text/html;charset=UTF-8");
HttpResponse response = new DefaultHttpClient().execute(httpPost);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
res = true;
resultString = EntityUtils.toString(response.getEntity(),
HTTP.UTF_8);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return res;
}