如何将字节数组转换为base64编码格式?
how to convert byte array to base64 encoded format?
我有一个页面可以从 Postgres 数据库下载文件。现在我可以点击 URL 查看数据库中的文件内容(以字节形式存储)-HTTP://sandbox4.wootz.io:8080/api/blob/1/UploadFile/hope%20real.txt
由于数据存储在 bytes(字节数组)类型的列中,当我单击下载按钮时,它会下载文件,当我看到它的内容时,它显示为字节数组。
file.txt(内容)
[\x58595a5052415445454b3123473b4c534e44204e474f49574853474849444748445348474d70253335]
下载功能
axios({
url: 'api/store/blob/UploadFile/' + data.chosenfile,
method: 'GET',
headers: {'session_id': data.sessionid},
responseType: 'arraybuffer'
}).then(response => {
console.log(response.data); //displays nothing (empty)
var fileURL = window.URL.createObjectURL(new Blob([response.data]));
console.log('fileURL is'+fileURL)
var fileLink = document.createElement('a');
console.log('fileLink is'+fileLink)
fileLink.href = fileURL;
fileLink.setAttribute('download', data.chosenfile);
document.body.appendChild(fileLink);
fileLink.click();
)
响应对象console.log
{"data":{},"status":200,"statusText":"OK","headers":{"access-control-allow-origin":"*","connection":"keep-alive","content-length":"86","content-type":"text/html; charset=utf-8","date":"Mon, 06 Jul 2020 18:22:23 GMT","etag":"W/\"56-Vaz0hG1/FIgtEurgvK+wOU+4F4M\"","x-powered-by":"Express"},"config":{"url":"api/store/blob/UploadFile/hope real.txt","method":"get","headers":{"Accept":"application/json, text/plain, */*","Access-Control-Allow-Origin":"http://localhost","session_id":"c5b3b878-771e-4472-84eb-6de15686effa"},"transformRequest":[null],"transformResponse":[null],"timeout":0,"responseType":"arraybuffer","xsrfCookieName":"XSRF-TOKEN","xsrfHeaderName":"X-XSRF-TOKEN","maxContentLength":-1},"request":{}}
我的代码的上传文件部分(这是文件上传到数据库的方式)
function readFileAsync(file) {
return new Promise((resolve, reject) => {
let reader = new FileReader();
reader.onload = () => {
var base64Url = reader.result;
console.log(base64Url) //ENITRE BASE64 URL
resolve(base64Url.substr(base64Url.indexOf(',') + 1)); //will return only the base64string part from the base64 url
};
reader.onerror = reject;
reader.readAsDataURL(file);
})
}
async function uploadFile(path, data) {
try {
let base64string = await readFileAsync(data.chosenfile);
console.log('base64 content is'+ base64string)
let response = await axios({
method: 'post',
url: 'api/store/blob' + path,
headers: {'session_id': data.sessionid},
data: {"id":data.chosenfile.name, "file": base64string }
});
if (response.status == 200) {
console.log(response.status);
}
return response.data;
} catch (err) {
console.error(err);
}
}
我做错了什么?为什么我得到的文件内容为 [\x58595a5052415445454b3123473b4c534e44204e474f49574853474849444748445348474d70253335] ?我应该怎么做才能在下载的文件中获取实际文件的内容?
注意:关于上传部分,我对所有类型的文件(excel 文档、txt 文件等)使用相同的策略,在将其传递到axios post payload.Now 这个有效载荷被传递给另一个名为数据管理器的项目(与 postgres 数据库交互)。所以当这个数据管理器项目收到我发送的有效载荷时,它会转换在插入 bytea.So 类型的 table 列之前,它会被写入 bytes [] 最终,当我从此 table 下载任何文件时,我也会以 bytea 格式获取文件内容。
您的文件是正确的 ASCII 文本文件,内容 [\x58595a5052415445454b3123473b4c534e44204e474f49574853474849444748445348474d70253335]
字面意思。
当你下载它时得到这个内容是非常好的,因为它就是这个文件的内容。
您想要的是从他们用于实际 ArrayBuffer 的十六进制表示中解析该内容,最终将其再次读取为 UTF-8 文本(或任何关于 ASCII 的编码)。
这必须在下载文件并以文本形式阅读后完成。
您首先从 [\x
- ]
包装器中将实际字节序列提取为十六进制,然后在每两个字符处拆分结果字符串以获得每个字节的十六进制值,最后将其解析为 Uint8Array取回原始数据:
// for StackSnippet we need to hardcode the response
// OP would have to make its request return that string
const response = { data: String.raw`[\x58595a5052415445454b3123473b4c534e44204e474f49574853474849444748445348474d70253335]` };
// .then( (response) => {
const encoded_text = response.data;
// remove leading "[\x" and final "]"
const encoded_data = encoded_text.slice( 3, -1 );
// split at every two chars, so we can get 0xNN, 0xNN
const hex_bytes = encoded_data.match( /.{2}/g );
// as numbers (0 - 255)
const num_bytes = hex_bytes.map( (hex) => parseInt( hex, 16 ) );
// wrap in an Uint8Array
const view = new Uint8Array( num_bytes );
// from there you can generate the Blob to save on disk
download( new Blob( [ view ] ), "file.txt" );
// but if you want to read it as UTF-8 text, you can:
const as_text = new TextDecoder().decode( view );
console.log( as_text );
// } );
function download( blob, filename ) {
const anchor = document.createElement( "a" );
anchor.href = URL.createObjectURL( blob );
anchor.download = filename;
anchor.textContent = "click to download";
document.body.append( anchor );
}
我有一个页面可以从 Postgres 数据库下载文件。现在我可以点击 URL 查看数据库中的文件内容(以字节形式存储)-HTTP://sandbox4.wootz.io:8080/api/blob/1/UploadFile/hope%20real.txt
由于数据存储在 bytes(字节数组)类型的列中,当我单击下载按钮时,它会下载文件,当我看到它的内容时,它显示为字节数组。
file.txt(内容)
[\x58595a5052415445454b3123473b4c534e44204e474f49574853474849444748445348474d70253335]
下载功能
axios({
url: 'api/store/blob/UploadFile/' + data.chosenfile,
method: 'GET',
headers: {'session_id': data.sessionid},
responseType: 'arraybuffer'
}).then(response => {
console.log(response.data); //displays nothing (empty)
var fileURL = window.URL.createObjectURL(new Blob([response.data]));
console.log('fileURL is'+fileURL)
var fileLink = document.createElement('a');
console.log('fileLink is'+fileLink)
fileLink.href = fileURL;
fileLink.setAttribute('download', data.chosenfile);
document.body.appendChild(fileLink);
fileLink.click();
)
响应对象console.log
{"data":{},"status":200,"statusText":"OK","headers":{"access-control-allow-origin":"*","connection":"keep-alive","content-length":"86","content-type":"text/html; charset=utf-8","date":"Mon, 06 Jul 2020 18:22:23 GMT","etag":"W/\"56-Vaz0hG1/FIgtEurgvK+wOU+4F4M\"","x-powered-by":"Express"},"config":{"url":"api/store/blob/UploadFile/hope real.txt","method":"get","headers":{"Accept":"application/json, text/plain, */*","Access-Control-Allow-Origin":"http://localhost","session_id":"c5b3b878-771e-4472-84eb-6de15686effa"},"transformRequest":[null],"transformResponse":[null],"timeout":0,"responseType":"arraybuffer","xsrfCookieName":"XSRF-TOKEN","xsrfHeaderName":"X-XSRF-TOKEN","maxContentLength":-1},"request":{}}
我的代码的上传文件部分(这是文件上传到数据库的方式)
function readFileAsync(file) {
return new Promise((resolve, reject) => {
let reader = new FileReader();
reader.onload = () => {
var base64Url = reader.result;
console.log(base64Url) //ENITRE BASE64 URL
resolve(base64Url.substr(base64Url.indexOf(',') + 1)); //will return only the base64string part from the base64 url
};
reader.onerror = reject;
reader.readAsDataURL(file);
})
}
async function uploadFile(path, data) {
try {
let base64string = await readFileAsync(data.chosenfile);
console.log('base64 content is'+ base64string)
let response = await axios({
method: 'post',
url: 'api/store/blob' + path,
headers: {'session_id': data.sessionid},
data: {"id":data.chosenfile.name, "file": base64string }
});
if (response.status == 200) {
console.log(response.status);
}
return response.data;
} catch (err) {
console.error(err);
}
}
我做错了什么?为什么我得到的文件内容为 [\x58595a5052415445454b3123473b4c534e44204e474f49574853474849444748445348474d70253335] ?我应该怎么做才能在下载的文件中获取实际文件的内容?
注意:关于上传部分,我对所有类型的文件(excel 文档、txt 文件等)使用相同的策略,在将其传递到axios post payload.Now 这个有效载荷被传递给另一个名为数据管理器的项目(与 postgres 数据库交互)。所以当这个数据管理器项目收到我发送的有效载荷时,它会转换在插入 bytea.So 类型的 table 列之前,它会被写入 bytes [] 最终,当我从此 table 下载任何文件时,我也会以 bytea 格式获取文件内容。
您的文件是正确的 ASCII 文本文件,内容 [\x58595a5052415445454b3123473b4c534e44204e474f49574853474849444748445348474d70253335]
字面意思。
当你下载它时得到这个内容是非常好的,因为它就是这个文件的内容。
您想要的是从他们用于实际 ArrayBuffer 的十六进制表示中解析该内容,最终将其再次读取为 UTF-8 文本(或任何关于 ASCII 的编码)。
这必须在下载文件并以文本形式阅读后完成。
您首先从 [\x
- ]
包装器中将实际字节序列提取为十六进制,然后在每两个字符处拆分结果字符串以获得每个字节的十六进制值,最后将其解析为 Uint8Array取回原始数据:
// for StackSnippet we need to hardcode the response
// OP would have to make its request return that string
const response = { data: String.raw`[\x58595a5052415445454b3123473b4c534e44204e474f49574853474849444748445348474d70253335]` };
// .then( (response) => {
const encoded_text = response.data;
// remove leading "[\x" and final "]"
const encoded_data = encoded_text.slice( 3, -1 );
// split at every two chars, so we can get 0xNN, 0xNN
const hex_bytes = encoded_data.match( /.{2}/g );
// as numbers (0 - 255)
const num_bytes = hex_bytes.map( (hex) => parseInt( hex, 16 ) );
// wrap in an Uint8Array
const view = new Uint8Array( num_bytes );
// from there you can generate the Blob to save on disk
download( new Blob( [ view ] ), "file.txt" );
// but if you want to read it as UTF-8 text, you can:
const as_text = new TextDecoder().decode( view );
console.log( as_text );
// } );
function download( blob, filename ) {
const anchor = document.createElement( "a" );
anchor.href = URL.createObjectURL( blob );
anchor.download = filename;
anchor.textContent = "click to download";
document.body.append( anchor );
}