js 怎么把blob类型转化为string

JavaScript010

js 怎么把blob类型转化为string,第1张

1、在类中定义大字段:

Java代码

public class informAffiche {

private Blob content

public void setcontent(Blob S_content)

{

content=S_content

}

public Blob getcontent()

{

return content

}

}

2、数据库中读取大字段内容并set进去:

Java代码

while(rs.next())

{

s.setcontent(rs.getBlob("content"))

}

3、在页面得到

Java代码

if (list.size()>0){

s=(informAffiche)list.get(0)

Blob blob= s.getcontent()

if(blob == null || blob.length()==0){

content = ""

}else{

content = new String(blob.getBytes((long)1, (int)blob.length()))

System.out.println("content---->"+content)

}

}

4、页面输出:

<td><%=content %></td>

因为项目需要压缩字符串和二进制,找到了pako这个库:

https://github.com/nodeca/pako

https://gitee.com/renew_old_romance/pako/tree/master

https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/pako/index.d.ts

参考 Javascript 简单实现Gzip 压缩字符串 基于pako.js

因为字符串需要与后端通讯,所以使用了bota/atob进行base64编码。

关于字符串与二进制处理,可以参考 jsmpeg系列一 基础知识 字符处理 ArrayBuffer TypedArray ,其中提到了ArrayBuffer与字符串的互相转换。

ArrayBuffer转为字符串,或者字符串转为ArrayBuffer,有一个前提,即字符串的编码方法是确定的。假定字符串采用UTF-16编码(JavaScript的内部编码方式),可以自己编写转换函数。

但是,ab2str这种写法,在实际使用中,如果buf过大,会有 Maximum call stack size exceeded 堆栈溢出。

可以参考 javascript - js数组转字符串 - 在字符串和ArrayBuffers之间转换 ,改为for的写法: