1

我想将视频文件从用 java 编写的服务器发送到 Web 浏览器客户端。套接字连接工作正常,发送文本也没有问题。我用来制作套接字服务器的库是这个https://github.com/TooTallNate/Java-WebSocket

这是发送文件的代码

public void sendFile(WebSocket conn,String path)
{
 try
   {    
     File file = new File(path);
     byte[] data = new byte[(int)file.length()];
     DataInputStream stream = new DataInputStream(new FileInputStream(file));
     stream.readFully(data);
     stream.close();
     conn.send(data);
     ..snip catch statements..

这是我用于捕获文件的 javascript 代码

function connect()
{
 conn = new WebSocket('ws://localhost:8887');
 conn.onopen = function(){alert("Connection Open");};
 conn.onmessage = function(evt){if(evt.data instanceof Blob){readFile(evt);}else{alert(evt.data);}};
 conn.onclose = function(){alert('connection closed');};
}
function readFile(file_data)
{
 var video = document.getElementById('area');
 video.src = window.URL.createObjectURL(file_data.data);
}

..skip to html element for playing the file..

<video id='area' controls="controls"></video>

我希望能够在浏览器中接收文件并播放它。

我在尝试将 webm 视频文件发送到 fireox 时遇到的错误是:不支持“application/octet-stream”的 HTTP“Content-Type”。加载媒体资源 blob:794345a5-4b6d-4585-b92b-3acb51612a6c 失败。

是否可以从 websocket 接收视频文件并播放?我执行错了吗?

4

1 回答 1

1

视频元素需要正确的内容类型,ws Blob 带有通用的内容类型,而且(对我而言)似乎没有办法将其设置为服务器端或客户端。
幸运的是,Blob 有slice(start, end, contentType)方法:

var rightBlob = originalBlob.slice(0, originalBlob.size, 'video/webm')
于 2012-07-04T04:02:06.390 回答