简体   繁体   中英

How to save an array buffer to a local file on disk using javascript

I'm practicing in programming with websocket, i'm building a java websocket server and want to send a binary data to websocket client, then client side can get that data through websocket and save it to a local file on disk, but i don't know what way using javascript to write an arraybuffer into a file. My example code is shown below

 var ws = new WebSocket(URL); ws.binaryType = "arraybuffer"; ws.onmessage = function(evt) { if (evt.data instanceOf ArrayBuffer) { // binary message is riecieved from server and i want to save it as a local file } };

Thank you for any help

You can create a textual/string representation that can be saved to and read from a file:

// returns String
function getArrayBufferString(arrayBuffer) {
  return new Uint8Array(arrayBuffer).toString()
}

// returns ArrayBuffer
function parseArrayBufferString(string) {
  return new Uint8Array(string.split(',')).buffer
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM