I'd recommend uploading binary data. You could place image meta-data (like name, type, user-id, ...) as url parameters or custom http-headers (X-...).
Android client code (not tested!):
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("
");
responseStreamReader.close();
String response = stringBuilder.toString();
System.out.println(response);
conn.disconnect();
}
catch(MalformedURLException e) {
e.printStackTrace();
}
catch(IOException e) {
e.printStackTrace();
}
}
Node.js, Express code:
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);
}
});
I'll try to explain the node.js part:
The function rawBody
acts as Express middleware. When a POST
request is made, this function gets called with the request object. It registers listeners for data
, end
and error
events. The data
events append all incoming chunks of data to a buffer. When end
fires, the property rawBody
is created in the request object and contains the binary data (your image blob). rawBody()
then transfers control to the next handler which can now save the blob to your database or filesystem.
When dealing with really big data blobs, this kind of processing is not the best way. It would be better to stream the data to a file or to the database to save memory.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…