我建议上传二进制数据。您可以将图像元数据(例如名称,类型,用户ID等)放置为url参数或自定义HTTP标头(X -…)。
Android客户端代码(未经测试!):
public static void postData(Bitmap imageToSend) { try { URL url = new URL("http://myserver/myapp/upload-image"); 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); // directly let .compress write binary image data // to the output-stream OutputStream os = conn.getOutputStream(); imageToSend.compress(Bitmap.CompressFormat.JPEG, 100, os); os.flush(); os.close(); 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); conn.disconnect(); } catch(MalformedURLException e) { e.printStackTrace(); } catch(IOException e) { e.printStackTrace(); }}Node.js,快速代码:
function rawBody(req, res, next) { var chunks = []; req.on('data', function(chunk) { chunks.push(chunk); }); req.on('end', function() { var buffer = Buffer.concat(chunks); req.bodyLength = buffer.length; req.rawBody = buffer; next(); }); req.on('error', function (err) { console.log(err); res.status(500); });}app.post('/upload-image', rawBody, function (req, res) { if (req.rawBody && req.bodyLength > 0) { // TODO save image (req.rawBody) somewhere // send some content as JSON res.send(200, {status: 'OK'}); } else { res.send(500); }});我将尝试解释node.js部分:该函数
rawBody充当Express中间件。发出
POST请求时,该函数将与请求对象一起调用。它注册了听众
data,
end和
error事件。这些
data事件将所有传入的数据块追加到缓冲区。当
end火灾,该属性
rawBody在请求对象被创建并包含二进制数据(图像斑点)。
rawBody()然后将控制权转移到下一个处理程序,该处理程序现在可以将blob保存到您的数据库或文件系统中。
当处理真正的大数据斑点时,这种处理方法不是最佳方法。最好将数据流传输到文件或数据库以节省内存。



