Ani*_*Ani 2 typescript angular angular-forms
我有一个要求,需要将所选图像(表单组的一部分)转换为字节数组,该数组需要作为发布请求的一部分发送到后端。
HTML 组件:
<div class="form-group">
<label>Image</label>
<input type="file" accept="image/*" class="form-control" formControlName="productImage" onchange="displaySelectedImageFunc(this);">
<img *ngIf="displaySelectedImage" src="{{selectedImageUrl}}">
<span class="error-message" *ngIf="itemRegistrationForm.controls.productImage.dirty && itemRegistrationForm.controls.productImage.errors">Select Image of the product</span>
</div>
Run Code Online (Sandbox Code Playgroud)
尝试使用
function convertDataURIToBinary(dataURI) {
var base64Index = dataURI.indexOf(';base64,') + ';base64,'.length;
var base64 = dataURI.substring(base64Index);
var raw = window.atob(base64);
var rawLength = raw.length;
var array = new Uint8Array(new ArrayBuffer(rawLength));
for(i = 0; i < rawLength; i++) {
array[i] = raw.charCodeAt(i);
}
return array;
}
function upload() {
const file = document.querySelector('input[type=file]').files[0];
const preview = document.getElementById('preview');
const reader = new FileReader();
let byteArray;
reader.addEventListener("loadend", function () {
// convert image file to base64 string
console.log('base64', reader.result);
preview.src = reader.result;
byteArray = convertDataURIToBinary(reader.result);
console.log('byte array', byteArray);
}, false);
if (file) {
reader.readAsDataURL(file);
}
}Run Code Online (Sandbox Code Playgroud)
<input type="file" id="file" accept="image/*" width="300" height="300" />
<submit onClick="upload()">Upload</submit>
<img id="preview"></img>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17318 次 |
| 最近记录: |