码迷,mamicode.com
首页 > Web开发 > 详细

上传文件之至客户端处理http请求

时间:2014-12-03 17:14:52      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:上传图片 文件


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请求

标签:上传图片 文件

原文地址:http://blog.csdn.net/u010427035/article/details/41699155

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!