JS中使用base64编码上传下载文件
下载文件:使用FileSaver.js https://github.com/eligrey/FileSaver.js/blob/master/README.md
手机端UC浏览器无法下载 安卓火狐浏览器可上传、下载
import * as fileSave from 'file-saver';
download(spath: string, swjm: string) {
this.tableService.getwjnrws(spath).subscribe(data => {
const content = data.swjnr;
if (content) {
console.log('下载' + content);
const index = swjm.lastIndexOf('.');
const fileType = swjm.substring(index);
const mime = {
...... // MIME 参考手册: http://www.w3school.com.cn/media/media_mimeref.asp
'.zip': 'application/zip',
'.json': 'application/json'
};
if (fileType in mime) {
const myFile = this.createFile(content, mime[fileType]);
// const file = new File([myFile], swjm, { type: mime[fileType] });
fileSave.saveAs(myFile, swjm);
}
}
});
}
createFile(data, type) {
const bytes = window.atob(data);
let n = bytes.length;
const u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bytes.charCodeAt(n); // 返回在指定的位置的字符的 Unicode 编码
}
return new Blob([u8arr], { type: type });
}
上传文件:
upload(files: FileList, service: HiswsService) {
function getDateStr(d:Date){ ......//格式化日期代码省略…… return `${year}/${mouthStr}/${dayStr} ${hourStr}:${minuteStr}:${secondStr}`; } if (files.length) { const file = files[0]; // const fileType = file.type; const reader = new FileReader(); // new一个FileReader实例 reader.onload = function (e) { const t: any = e.target; console.log('上传:' + t.result); let wjnr = ''; const d = t.result.split('base64,')[1]; if (d) { wjnr = d; } else { wjnr = t.result; } const today = new Date(); const sygid = sessionStorage.getItem('currentUser'); const data = new FileBean('', file.name, '', `${file.size}`, '1', file.name, getDateStr(today), wjnr, sygid); service.wjsave(data).subscribe( s => { console.log('wjsave:' + s); if (s.state) { alert('上传文件成功!'); } else { alert('上传失败:' + s.errorMsg); } } ); }; reader.readAsDataURL(file); // 返回一个基于Base64编码的data-uri对象 } }
service所做的事情就是发get 或 post请求给后端
return this.http.post<SaveOutputBean>(surl, fileBean, httpOptions) //上传 return this.http.get<FileContent>(lurl) //下载
浙公网安备 33010602011771号