发送图像套接字io和android

时间:2017-05-23 09:40:14

标签: javascript java android sockets socket.io

我是socket.io的初学者。我用过了一个库

https://www.npmjs.com/package/socket.io-stream

我们使用浏览器成功上传了图片。但现在,我想从Android应用程序上传图像。如果有人有Android代码请给我..

https://github.com/socketio/socket.io-client-java/issues/29

我一直在google上搜索,但没找到任何合适的解决方案。

3 个答案:

答案 0 :(得分:3)

   var imageBuffer = customJs.decodeBase64Image(base64Data);
   var imageTypeDetected = imageBuffer.type.match(/\/(.*?)$/);
   var filename = 'profile-' + Date.now() + '.' + imageTypeDetected[1];
   // config.uploadImage --- Folder path where you want to save.
   var uploadedImagePath = config.uploadImage + filename;
   try {
       fs.writeFile(uploadedImagePath, imageBuffer.data, function () {
       dbMongo.updateImage({email: decoded.email, user_id: decoded.userId, 'profile_picture': config.showImagePath + filename}, function (res) {
       if (res.error) { 
       socket.emit('set_update_image', {'error': 1, 'message': 'Error!' + res.message, 'data': null, 'status': 400});
       } else {
         console.log(res);
         socket.emit('set_update_image', res);
       }
       });
     });
      } catch (e) {
           socket.emit('set_update_image', {'error': 1, 'message': 'Internal server error ' + e, 'data': null, 'status': 400});
      }

从其他文件调用函数

exports.decodeBase64Image = function decodeBase64Image(dataString) {
var matches = dataString.match(/^data:([A-Za-z-+\/]+);base64,(.+)$/);
var response = {};

if (matches.length !== 3)
{
    return new Error('Invalid input string');
}

response.type = matches[1];
response.data = new Buffer(matches[2], 'base64');

return response;
}

答案 1 :(得分:0)

对于使用socket的android上传图片,你需要将图像作为base64字符串发送,

以下是将Image转换为base64的示例,然后您发送与另一个参数相同的数据。

String base64Image = getBase64Data(dirPath + "/" + fileName);

public String getBase64Data(String filePath) {
        try {
            InputStream inputStream = new FileInputStream(filePath);//You can get an inputStream using any IO API
            byte[] bytes;
            byte[] buffer = new byte[8192];
            int bytesRead;
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            try {
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    output.write(buffer, 0, bytesRead);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            bytes = output.toByteArray();
            return "data:image/jpeg;base64," + Base64.encodeToString(bytes, Base64.DEFAULT);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

答案 2 :(得分:0)

在android中,您需要使用Base64

对图像进行编码
 @RequestMapping(value="/save", method = RequestMethod.POST)
public ResponseEntity<?> saveTemp(@RequestParam("file") MultipartFile file) throws Exception{
    String nomFichier=file.getOriginalFilename();

    try {
        byte[] bytes = file.getBytes();
        File fi=new File(tempRepo+nomFichier);
        fi.getParentFile().mkdirs();
        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream((new FileOutputStream(fi)));
        bufferedOutputStream.write(bytes);
        bufferedOutputStream.close();



    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
    }
    return new ResponseEntity<>(HttpStatus.OK);
}

在服务器端,接收图像并对其进行解码

public save(file:any){

 const formData = new FormData();
 formData.append("file", file);

 return this._http
  .post('http://localhost:8081/save', formData)
  .catch(this._errorhandler);
}