1保存图片
<input type="file" name="avatar-file" id="avatar-file" accept='image/*' />
/** * base64转换为文件流 */ datatoBlob(data) { const arr = data.split(','); const mime = arr[0].match(/:(.*?);/)[1]; const bstr = atob(arr[1]); let n = bstr.length; const u8arr = new Uint8Array(n); while (n--) { u8arr[n] = bstr.charCodeAt(n); } return new Blob([u8arr], { type: mime }); }
this.croppedImage是Base64
const formData = new FormData(); const name = (document.getElementById('avatar-file') as HTMLInputElement).files[0].name || 'blob.png'; const file = new File(this.datatoBlob(this.croppedImage)), name); formData.append('file', file);
IE 不支持new file() 的写法,改为formData.append('file', blob, filename);
const formData = new FormData(); const name = (document.getElementById('avatar-file') as HTMLInputElement).files[0].name || 'blob.png'; const idx = name.indexOf('.');
// this.datatoBlob(this.croppedImage) 好像把图片数据转为png了,所以把文件名后缀也改为 xxx.png
formData.append('file', this.datatoBlob(this.croppedImage), name.substring(0, idx) + '.png');
使用第三方插件
Plupload上传插件中文帮助文档
文件转为base64
filesAddInner(ev) { const file = ev.files[0].getNative(); let reader = new FileReader(); reader.readAsDataURL(file); const that = this; reader.onload = function() { that.imgSrc = this.result; }; reader.onloadend = function() { reader = null; }; }
WebUploader API文档
readAsDataURL 方法会读取指定的 Blob 或 File 对象 读取操作完成的时候,会触发 onload 事件 result 属性将包含一个data:URL格式的字符串(base64编码)以表示所读取文件的内容。
文件转为base64
filesAddInner(ev) { const file = ev.files[0]; let reader = new FileReader(); reader.readAsDataURL(file.source.source); const that = this; reader.onload = function() { that.imgSrc = this.result; }; reader.onloadend = function() { reader = null; }; }
浙公网安备 33010602011771号