[原创]Android提交表单并上传图片到web服务器

Android提交表单并上传图片到web服务器,直接上代码

用到了Apache的HttpClient.jar

 

	/**
	 * 提交表单并上传文件到网站
	 * @param url 提交的接口
	 * @param param 参数 <键,值>
	 * @param bitmap 图片内容
	 */
	public static String postForm(String url,Map<String, String> param, Bitmap bitmap)
	{
		try {
			url="http://localhost:4657" +
                    "/api/SaveNeed";
			HttpPost post = new HttpPost(url);

			HttpClient client = new DefaultHttpClient();
			String BOUNDARY = "*****"; // 边界标识
			MultipartEntity entity = new MultipartEntity(
					HttpMultipartMode.BROWSER_COMPATIBLE, BOUNDARY, null);
			if (param != null && !param.isEmpty()) {

				entity.addPart("needList", new StringBody(
						param.get("needList"), Charset.forName("UTF-8")));

			}

			saveImageFile(bitmap);
			String path = Environment.getExternalStorageDirectory()
					+ "/temple/temp.jpg";
			File file = new File(path);
			// 添加文件参数
			if (file != null && file.exists()) {

				entity.addPart("file", new FileBody(file));
			}

			post.setEntity(entity);

			HttpResponse response;

			response = client.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();
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
赞(0) 打赏
分享到: 更多 (0)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏