伙计们我想使用android上的node.js&socket.io作为二进制流将图像发送到服务器,任何人都可以帮忙吗?
答案 0 :(得分:0)
Android中有几个库可以上传大文件,例如图像和视频。除非您将其作为学习经验来使用,否则几乎可以肯定使用其中一种会更容易。最近的一些内容包括:
一个较旧的库是apache MultiPartMine库-在此处查看示例,以获取视频而非图像,但适用相同的原理:
//Create a new Multipart HTTP request to upload the video
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(serverURL);
//Create a Multipart entity and add the parts to it
try {
Log.d("VideoUploadTask doInBackground","Building the request for file: " + videoPath);
FileBody filebodyVideo = new FileBody(new File(videoPath));
StringBody title = new StringBody("Filename:" + videoPath);
StringBody description = new StringBody("Test Video");
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("videoFile", filebodyVideo);
reqEntity.addPart("title", title);
reqEntity.addPart("description", description);
httppost.setEntity(reqEntity);
} catch (UnsupportedEncodingException e1) {
//Log the error
Log.d("VideoUploadTask doInBackground","UnsupportedEncodingException error when setting StringBody for title or description");
e1.printStackTrace();
return -1;
}
//Send the request to the server
HttpResponse serverResponse = null;
try {
Log.d("VideoUploadTask doInBackground","Sending the Request");
serverResponse = httpclient.execute( httppost );
} catch (ClientProtocolException e) {
//Log the error
Log.d("VideoUploadTask doInBackground","ClientProtocolException");
e.printStackTrace();
} catch (IOException e) {
//Log the error
Log.d("VideoUploadTask doInBackground","IOException");
e.printStackTrace();
}
//Check the response code
Log.d("VideoUploadTask doInBackground","Checking the response code");
if (serverResponse != null) {
Log.d("VideoUploadTask doInBackground","ServerRespone" + serverResponse.getStatusLine());
HttpEntity responseEntity = serverResponse.getEntity( );
if (responseEntity != null) {
//log the response code and consume the content
Log.d("VideoUploadTask doInBackground","responseEntity is not null");
try {
responseEntity.consumeContent( );
} catch (IOException e) {
//Log the (further...) error...
Log.d("VideoUploadTask doInBackground","IOexception consuming content");
e.printStackTrace();
}
}
} else {
//Log that response code was null
Log.d("VideoUploadTask doInBackground","serverResponse = null");
return -1;
}
此处的完整示例:https://stackoverflow.com/a/32887541/334402
类似地,在节点侧,您可以利用标准库来上传文件。一个例子就是聚会:
Multer是用于处理multipart / form-data的node.js中间件,主要用于上传文件。它是在busboy之上编写的,以实现最大效率。
这里有一个经过测试(尽管几年前..)的示例:https://stackoverflow.com/a/41567587/334402
如果您确实想编写自己的服务器端解析器,则此答案中包含一些最新信息:https://stackoverflow.com/a/23718166/334402