我正在尝试使用HttpUrlConnection将图像发送到服务器,因为这是Google推荐的方法。我决定将图像转换为Base64字符串并发送到服务器,然后在服务器上解码为.jpg文件。但是这种方法只适用于小型缩略图,无法发送全尺寸图像。
以下是Android客户端代码:
public static void postData(Bitmap imageToSend) {
try
{
URL url = new URL("http://");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Cache-Control", "no-cache");
conn.setReadTimeout(35000);
conn.setConnectTimeout(35000);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
// writes a compress version of Bitmap to a specified outputstream
imageToSend.compress(Bitmap.CompressFormat.JPEG, 100, bos);
byte[] byteArray = bos.toByteArray();
String imageEncoded = Base64.encodeToString(byteArray, Base64.DEFAULT);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("image", imageEncoded));
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
// getQuery is function for creating a URL encoded string
writer.write(getQuery(params));
System.out.println("Response Code: " + conn.getResponseCode());
InputStream in = new BufferedInputStream(conn.getInputStream());
Log.d("sdfs", "sfsd");
BufferedReader responseStreamReader = new BufferedReader(new InputStreamReader(in));
String line = "";
StringBuilder stringBuilder = new StringBuilder();
while ((line = responseStreamReader.readLine()) != null)
stringBuilder.append(line).append("\n");
responseStreamReader.close();
String response = stringBuilder.toString();
System.out.println(response);
bos.flush();
bos.close();
in.close();
conn.disconnect();
}
catch(MalformedURLException e) {
e.printStackTrace();
}
catch(IOException e) {
e.printStackTrace();
}
}
Node.js 服务器代码:
function base64_decode(base64str,file) {
var bitmap = new Buffer(base64str,'base64');
//writing into an image file
fs.writeFile(file, bitmap);
//write a text file
console.log('File created from base64 encoded string');
}
app.post("/", function (req,res,next) {
//requesting the value of the image key which is urlencoded base 64 string
var image = req.body.image;
console.log(req.body.image);
base64_decode(image,'newImage.jpg');
res.writeHead(200, {'Content-Type':'text/plain'});
res.write('the image is saved');
res.end();
if (req.url != "/")
next();
由于 BufferedWriter 大小限制,我无法对全尺寸图像使用相同的方法 - base64编码的字符串太长了。
另一种方法是使用 HttpPost 和 MultipartEntity,但它们在 API22 中已被弃用,而且我不知道如何在服务器端处理请求。在其他示例中,一些包装器被使用,例如两条破折号、边界、回车换行符,但我找不到原因。
我需要一个使用 HttpUrlConnection 的示例。
非常感谢任何帮助,因为我是 Android 和 node.js 的新手。
HttpURLConnection
打交道,可以看看 DavidWebb。如果你正在使用 Express,则有一个带有 一些示例代码 的测试 API 服务器,展示了如何进行上传。通常我不建议使用 Base64,在所有情况下都可以上传二进制文件。你对这个库和 Express 感兴趣吗? - hgoebl