js bytes文件转图片显示和转pdf预览和上传
一、图片显示
img = data:application/pdf;base64,${res.bytes};
二、pdf预览
使用base64编码和Data URI Scheme:将字节数组进行base64编码,然后将生成的base64字符串和Data URI Scheme(以"data:application/pdf;base64,"为开头)组合成一个URL
const res = { bytes:'...' }
// 转换
const updatWordParam = async () => {
fetch(`data:application/pdf;base64,${res.bytes}`).then(async (reBytes) => {
const blob = await reBytes.blob();
const newBlob = new Blob([blob], { type: 'application/pdf' });
const file = new File([newBlob], '文件.pdf', { type: 'application/pdf' });
const url = `${window.URL.createObjectURL(newBlob)}#toolbar=0`
downUrlFile(url,'文件.pdf')
uploadFile(file)
});
}
// 下载
const downUrlFile = async (url, filename) => {
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', filename);
link.click();
};
// 上传
const uploadFile = async (file) => {
const formData = new FormData();
formData.append('file', file);
fetch('http://example.com/upload', {
method: 'POST',
body: formData
})
.then(response => {
console.log('Success:', response);
})
.catch(error => {
console.error('Error:', error);
});
};