file,blob,Promise,存储,base64中的编码/解码。

问题描述 投票:0回答:1

function selectImagesToUpload() { const input = document.getElementById("product_pics"); const preview = document.querySelector(".preview"); const images = preview.querySelectorAll("div.preview > p"); images.forEach(async item => { let fn = item.innerText.split(';')[0]; let ext = fn.slice(fn.lastIndexOf('.') + 1, fn.length); let p = await fetch(fn).then(response => response.blob()); let b = await p.arrayBuffer(); let f0 = new File(new Uint8Array(b), fn, { type: `image/${ext}` }); var reader = new FileReader(); reader.onload = function (e) { var image = document.createElement("img"); image.src = e.target.result; document.body.appendChild(image); } reader.readAsDataURL(f0); }); }
这是一个相对URL的示例段落(我将其设置在项目的资产中):

img/prodotto7.jpg;

< p >这是附加到DOM的结果:< /p >emptyimage

有人可以帮我吗?这就像一个测试一样,我必须努力继续我的项目。 对一些疯狂的技巧进行评估,我得到了“无效的chalidcharactererror:未能在'窗口'上执行'atob':要解码的字符串未正确编码。”在“ ATOB(e.target.result)”的行中;因此,fileReader做得不正确。

let fn = item.innerText.split(';')[0]; let ext = fn.slice(fn.lastIndexOf('.') + 1, fn.length); let p = await fetch(fn).then(response => response.blob()); let b = await p.arrayBuffer(); let ua = new Uint8Array(b) let u64 = ua.toBase64; let f0 = new File( ua , fn, { type: `image/${ext}` }); console.log(f0); const para = document.createElement("p"); para.textContent = item.textContent; preview.appendChild(para); var reader = new FileReader() reader.onload = function (e) { var image = document.createElement("img"); image.src = e.target.result; console.log(image.src); var bs = atob(e.target.result); var buffer = new ArrayBuffer(bs.length); var ba = new Uint8Array(buffer); for (var i = 0; i < bs.length; i++) { ba[i] = bs.charCodeAt(i); } var blob = new Blob([ba], { type: "image/jpg" }); document.body.appendChild(URL.createObjectURL(blob)); } reader.readAsDataURL(f0);

    
溶解(我需要文件变量的机制 - 转换图像,然后将它们恢复 - 将图像存储到filelist中,然后在formdata变量中存储,并在最终的范围内发布并通过微服务器获得消息,任务完整!)

.ts部分

javascript angular file
1个回答
0
投票

... formData !: FormData; fileTypes = [ "image/apng", "image/bmp", "image/gif", "image/jpeg", "image/pjpeg", "image/png", "image/svg+xml", "image/tiff", "image/webp", "image/x-icon", ]; ... selectImagesToUpload($event : any) { const fl = new Promise<File[]>( (resolve, reject) => { console.log('promise'); const input = document.getElementById("product_pics"); const preview = document.querySelector(".preview"); const images = preview?.querySelectorAll("div.preview > p"); let fl: File[] = new Array(); console.log(fl); images?.forEach(async item => { if (preview?.firstChild === undefined) { /* *** TODO *** console.log('primo'); const para = document.createElement("p"); console.log(item.innerText); para.textContent = item.textContent; preview.appendChild(para); fl[i] = */ } else { console.log('secondo'); console.log(item.textContent); let fn = item?.textContent?.split(';')[0]; let ext = fn?.slice(fn.lastIndexOf('.') + 1, fn.length); if (fn) { let p = await fetch(fn).then(response => response.blob()); let b = await p.arrayBuffer(); let ua = new Uint8Array(b) //console.log(ua) //let b64 = ua.toBase64(); //it does not work in some of the most widely-used browsers. const bin = []; for (let i = 0; i < ua.length; i++) { bin.push(String.fromCharCode(ua[i])); } const b64encoded = btoa(bin.join("")); //console.log(b64encoded); const trimmedString = b64encoded.replace('dataimage/jpegbase64', ''); const imageContent = atob(trimmedString); const buffer = new ArrayBuffer(imageContent.length); const view = new Uint8Array(buffer); for (let n = 0; n < imageContent.length; n++) { view[n] = imageContent.charCodeAt(n); } const type = `image/${ext}`; const blob = new Blob([buffer], { type }); let f0 = new File([blob], fn, { lastModified: new Date().getTime(), type }); var image = document.createElement("img"); image.src = `data:image/png;base64, ${b64encoded}`; //console.log(image.src) console.log(f0); document.body.appendChild(image); //image shown this.Main(f0); //file shown const para = document.createElement("p"); console.log(`filename : ${fn};`); para.textContent = `${fn};`; preview.appendChild(para); fl.push(f0); } } }); while (preview?.firstChild) { preview.removeChild(preview.firstChild); } const curFiles = (<HTMLInputElement>input)?.files; if (curFiles?.length === 0) { } else { if (curFiles) { for (const file of curFiles) { if (this.validFileType(file)) { let filename = String(file.name); let image = filename.slice(0, filename.lastIndexOf('.')); if (this.validImage(image)) { const para = document.createElement("p"); console.log(`filename : ${file.name};`); para.textContent = `${filename};`; preview?.appendChild(para); fl.push(file); this.Main(file); //file shown } } } } } resolve(fl); }); fl.then( (fl) => { let fd = new FormData(); console.log('1then'); console.log(fl); for (let i = 0; i < fl.length; i++) { fd.append(fl[i].name, fl[i]); } this.formData = fd; }, (err) => { console.log('errore'); console.log(err); }).then( resolve => { console.log('2then'); for (const pair of this.formData.entries()) { console.log(pair[0], pair[1]); } }); } clearValues($event: any) { this.clearAllImages(); } validFileType(file: File) { return this.fileTypes.includes(file.type); } validImage(image: string) { return !image.includes(';') && !image.includes('.'); } clearAllImages() { const preview = document.querySelector(".preview"); const images = preview?.querySelector("div.preview > p"); while (preview?.firstChild) { preview.removeChild(preview.firstChild); } } async Main(file: any) { const toBase64 = (file: any) => new Promise((resolve, reject) => { const reader = new FileReader(); reader.readAsDataURL(file); reader.onload = () => { resolve(reader.result); } reader.onerror = reject; }); let b64 = await toBase64(file); //console.log(b64); var image = document.createElement("img"); image.src = String(b64); //let u8 = Uint8Array.fromBase64(b64); //it does not work in some of the most widely-used browsers. document.body.appendChild(image); }

HTML部分

<section class="content-main main d-flex flex-column justify-content-center"> <div class="content-header d-flex flex-column"> <h2 class="content-title d-flex justify-content-center">{{title}}</h2> <div> <button class="btn btn-outline-danger" (click)="abort()"> × Annulla></button> </div> </div> <div class="scheda d-flex align-items-center justify-content-around"> <div class="card"> <form (ngSubmit)="artForm.valid && Salva()" #artForm="ngForm" enctype="multipart/form-data"> <!-- Codice, Barcode --> <div class="row gx-2"> <div class="col-sm-6 mb-3"> <label for="codArt" class="form-label">Codice Articolo:</label> <input id="codArt" name="codart" type="text" placeholder="" class="form-control" [(ngModel)]="articolo.codprod" required minlength="5" maxlength="30" #codice="ngModel"> <span style="color:red" *ngIf="codice.invalid && (codice.dirty || codice.touched)"> Il codice articolo deve essere compreso fra 5 e 30 caratteri </span> </div> </div> <!--Descrizione --> <div class="mb-4"> <label class="form-label">Descrizione Articolo</label> <textarea placeholder="" name="descr" class="form-control" rows="2" [(ngModel)]="articolo.descrizione" required minlength="6" maxlength="80" #desart="ngModel"></textarea> <span style="color:red" *ngIf="desart.invalid && (desart.dirty || desart.touched)"> Il codice articolo deve essere compreso fra 6 e 80 caratteri </span> </div> <!--Unità di misura, Iva --> <div class="row gx-2"> <div class="col-sm-6 mb-3"> <label class="form-label">Unità di Misura</label> <select class="form-select" name="um" [(ngModel)]="articolo.um"> <option value="pz"> Pezzi </option> <option value="kg"> Kilogrammi </option> </select> </div> <div class="col-sm-6 mb-3"> <label class="form-label">Iva</label> <select class="form-select" name="iva" [(ngModel)]="articolo.iva.idIva"> <option value="-1" class="text-primary font-weight-bolder">--- Seleziona IVA ---</option> <option [ngValue]="iva.idIva" *ngFor="let iva of Iva"> {{iva.descrizione}} </option> </select> </div> </div> <!-- row.// --> <!-- Pezzi per cartone, Peso, Prezzo, Valuta --> <div class="mb-4"> <label class="form-label">Pezzi Per Cartone: &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Peso Netto:</label> <div class="row gx-2"> <div class="col-3"> <input placeholder="Pezzi" type="text" class="form-control" [(ngModel)]="articolo.pz" required min="1" name="pzcart" max="99" maxlength="3" #pzcart="ngModel"> <span style="color:red" *ngIf="pzcart.errors?.['required']"> Inserisci i pezzi per cartone </span> <span style="color:red" *ngIf="pzcart.errors?.['min']"> Il valore minimo è 1 </span> <span style="color:red" *ngIf="pzcart.errors?.['max']"> Il valore massimo è 99 </span> </div> <div class="col-3"> <input placeholder="Peso" name="peso" type="text" class="form-control" [(ngModel)]="articolo.peso" required maxlength="6" min="0.01" max="500" #peso="ngModel"> <span style="color:red" *ngIf="peso.invalid && (peso.dirty || peso.touched)"> Il peso dell'articolo deve essere compreso tra 0.01 e 500 </span> </div> <div class="col-4"> <input placeholder="Prezzo" type="text" class="form-control"> </div> <div class="col-2"> <select class="form-select"> <option> EUR </option> <option> USD </option> <option> GBP </option> </select> </div> </div> </div> <!-- Categoria, Stato Articolo --> <div class="row gx-2"> <div class="col-sm-6 mb-3"> <label class="form-label">Categoria:</label> <select class="form-select" name="cat" [(ngModel)]="articolo.famAssort.id"> <option [ngValue]="categoria.id" *ngFor="let categoria of Cat"> {{categoria.id}} - {{categoria.descrizione}} </option> </select> </div> <div class="col-sm-6 mb-3"> <label class="form-label">Stato:</label> <select class="form-select" name="status" [(ngModel)]="articolo.status"> <option value="1">Attivo</option> <option value="2">Sospeso</option> <option value="3">Eliminato</option> </select> </div> </div> <!-- row.// --> <!-- Immagine --> <div class="mb-4"> <label class="form-label">Immagine:</label> <input class="form-control" type="file" enctype="multipart/form-data" id="product_pics" name="product_pics" accept=".jpg, .jpeg, .png" (change)="selectImagesToUpload($event)" multiple /> <!application/x-www-form-urlencoded--> <button class="btn btn-primary" (click)="clearValues($event)">Clear all</button> </div> <div id="uploadImages" class="preview"> @if(articolo.imgsrc){ <p>{{articolo.imgsrc}};</p> }@else{ <p>No files currently selected for upload</p> } </div> <div class="alert alert-success" *ngIf="Conferma"> {{Conferma}} </div> <div class="alert alert-danger" *ngIf="errore"> {{errore}} </div> <br> <button type="submit" class="btn btn-primary" [disabled]="artForm.invalid">Salva Articolo</button> </form> </div> </div>

图片显示,忘记布局。查看物质xd
	
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.