目前我正在做一个需要将数据发布到服务器数据库的项目。
在这里,我发布了 name
、id
、image
等数据。
我想将图像作为二进制数据传递。为此,我将图像转换为 base64 字符串,然后发布数据, 但由于图像分辨率较大或 HTTP 连接大小,我收到 413 错误代码,表明 URL 过大。
谁能给我解决这个问题的方法吗? 在这里,我给你我已经实现的代码。
值(value)观
Bitmap b1 = (Bitmap) data.getExtras().get("data");
b1=Bitmap.createScaledBitmap(b1, 100,100, true);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
b1.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
String base64String = Base64.encodeBytes(b);
Log.e("Base 64 conversion of image--------", base64String);
response = webService.doNetworkConnection("{\"method\":\"EventUploadPhoto\",\"data\":{\"ClientCode\":"
+ "\""
+ Util.clientCode
+ "\""
+ ",\"EventID\":"
+ "\""
+ itemId
+ "\""
+ ",\"ImageName\":"
+ "\""
+ filename
+ System.currentTimeMillis()
+ "\""
+ ",\"ImageData\":"
+ "\""
+ imgData
+ "\""
+ ",\"UserName\":"
+ "\""
+ username
+ "\""
+ ",\"TokenId\":"
+ "\""
+ tokenid
+ "\"" + "}}", "POST");
做网络连接
public String doNetworkConnection(String request, String methodType) throws IOException {
String str = java.net.URLEncoder.encode(request, "UTF-8");
String resultstring = "";
System.out.println("string request:" + request);
int response = -1;
try {
URL url = new URL((mContext.getResources()
.getString(R.string.WebServiceUrl))
+ "" + str);
System.out.println("url:" + url);
URLConnection conn = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
httpConn.connect();
response = httpConn.getResponseCode();
System.out.println("response code:" + response);
if (response == HttpURLConnection.HTTP_OK) {
InputStream is = httpConn.getInputStream();
resultstring = convertinputStreamToString(is);
} else {
resultstring = "";
}
} catch (Exception e) {
resultstring = "";
}
System.out.println("result string:" + resultstring);
return resultstring;
}
这里的HTTP响应码是413,说明URL太大,不能POST图片。
最佳答案
如果您在 HTTP 上设置:因为它只是一个字符串,您可以将它分解成单独的字符串并单独发布它们。然后在另一边将它们连接在一起。
否则,您可以使用 FTP 或降低并通过 TCP/IP 流式传输。有像 this one 这样的 Java 库.
关于android - 如何在android中使用base64发布大图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6596593/