java 使用MultipartEntity Builder进行图像上传

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 使用MultipartEntity Builder进行图像上传相关的知识,希望对你有一定的参考价值。

private String updateProfile(Map map) {
	File image = (File) map.get(KEY_IMAGE);
	File background = (File) map.get(KEY_BACKGROUND);
	FCUser user = (FCUser) map.get(KEY_USER);

	String userJsonString = user.toJSONUpdate().toString();

	// TODO : Change HTTPClient to HttpUrlConnection or Android Async HTTP and Upload Image

	HttpClient httpClient = new DefaultHttpClient();
	HttpPost httpPost = new HttpPost(FlipCardClient.API_PROFILE);
	HttpResponse httpResponse;
	HttpEntity httpEntity;
	String response = "";

	try {
		MultipartEntityBuilder builder = MultipartEntityBuilder.create();

		builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

		// Image
		if (image != null) {
			FileBody fileBodyImage = new FileBody(image);
			builder.addPart(KEY_IMAGE, fileBodyImage);
		}

		// Background
		if (background != null) {
			FileBody fileBodyBackground = new FileBody(background);
			builder.addPart(KEY_BACKGROUND, fileBodyBackground);
		}

		// User ID
		String userId = String.valueOf(user.getId());
		builder.addTextBody(KEY_USER_ID, userId, ContentType.TEXT_PLAIN);

		// User Profile JSON String
		builder.addTextBody(KEY_PROFILE, userJsonString, ContentType.TEXT_PLAIN);

		HttpEntity entity = builder.build();
		httpPost.setEntity(entity);
		httpResponse = httpClient.execute(httpPost);
		httpEntity = httpResponse.getEntity();
		response = EntityUtils.toString(httpEntity);

	} catch (ClientProtocolException e) {
		e.printStackTrace();
	} catch (IOException e) {
		Log.v(TAG, "Something wrong with I/O operation");
		e.printStackTrace();
	}

	return response;
}

以上是关于java 使用MultipartEntity Builder进行图像上传的主要内容,如果未能解决你的问题,请参考以下文章

MultipartEntity 类型已弃用

如何使用 MultipartEntity 在 servlet 中获取实体?

Android 错误:MultipartEntity,客户端发送的请求在语法上不正确

HTTPclient使用MultipartEntity怎么上传文件

HTTPclient使用MultipartEntity怎么上传文件

Android - MultipartEntity 和依赖项