离子/打字稿功能,用于将图像保存到文件夹

时间:2018-06-21 07:06:14

标签: javascript image typescript ionic-framework input

通过输入类型文件,我想将所选图像保存在文件夹中。我该怎么办?

html代码:

<ion-item >
      <ion-label>Immagine</ion-label>
      <ion-input type="file">Chose image</ion-input>
      <button ion-button color:"secondary" (click)="getImage()">Get Image</button>
</ion-item>

1 个答案:

答案 0 :(得分:0)

您可以执行File插件来写入文件。这是完整的示例。

安装文件插件:

ionic cordova plugin add cordova-plugin-file
npm install --save @ionic-native/file

app.module.ts文件

import { File } from '@ionic-native/file';
@NgModule({
     providers: [   
        File
     ]
})
export class AppModule { }

HTML文件

<ion-list>
        <ion-item (click)="onImageClick()">
           <div>
               <ion-icon ios="ios-add-circle" md="md-add-circle"></ion-icon>
                  Add Files
           </div>
       </ion-item>
       <ion-item>
           <button ion-button (click)="addImage()">Upload</button>
       </ion-item>
   </ion-list>

打字稿文件

import { File } from '@ionic-native/file';

private Attachments: any[] = [];

constructor(private camera: Camera, private file:File) { }

public onImageClick() {

    let input = document.createElement('input');
    input.setAttribute('type', 'file');
    input.setAttribute('accept', 'image/*'); //you can change also file type as **'file/*'**
    input.setAttribute("multiple", ""); // If you dont want multiple select file pls remove this line

    input.addEventListener('change', (event: any) => {      
      let fileList: File[] = event.target.files;
      console.log("File List Object Value",fileList);

        for (let fileIdx = 0; fileIdx < fileList.length; fileIdx++) {
                    let file = fileList[fileIdx];
                    this.attachmentBase64(file, fileIdx);
        }
         console.log("Attachments",this.Attachments);
    });

    input.click();
  }

private attachmentBase64(file: File, fileIndex: number) {
       let self=this;
        var reader = new FileReader();

        reader.readAsDataURL(file);
        reader.onerror = function (error) {
        }
        reader.onloadend = function () {
            //Read complete
            if (reader.readyState == 2) {
                self.Attachments[fileIndex].Base64 = reader.result;                
            }
        };
    }

   private addImage(){
      for(let file of this.Attachments){
         this.writeFile(file.Base64,"My Picture","FileName.png");
      }
  }


//here is the method is used to write a file in storage
public writeFile(base64Data: any, folderName: string, fileName: any) {
        let contentType = this.getContentType (base64Data);
        let DataBlob = this. base64toBlob(content, contentType);


// here iam mentioned this line this.file.externalRootDirectory is a native pre-defined file path storage. You can change a file path whatever pre-defined method.
        let filePath= this.file.externalRootDirectory + folderName;

         this.file.writeFile(filePath, fileName, DataBlob, contentType)
            .then((success) => {
                console.log("File Writed Successfully", success);
            }).catch((err) => {
                console.log("Error Occured While Writing File", err);
            })
    }

//here is the method is used to get content type of an bas64 data
public getContentType(base64Data: any) {
        let block = base64Data.split(";");
        let contentType = block[0].split(":")[1];       
       return contentType;      
    }

//here is the method is used to convert base64 data to blob data
public base64toBlob(b64Data, contentType) {
        contentType = contentType || '';
        sliceSize = 512;
        let  byteCharacters = atob(b64Data);
        let byteArrays = [];
        for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
            let slice = byteCharacters.slice(offset, offset + sliceSize);
            let byteNumbers = new Array(slice.length);
            for (let i = 0; i < slice.length; i++) {
                byteNumbers[i] = slice.charCodeAt(i);
            }
            var byteArray = new Uint8Array(byteNumbers);
            byteArrays.push(byteArray);
        }
        let blob = new Blob(byteArrays, { type: contentType });
        return blob;
    }

工作示例。如有任何错误,请通知我。

参考文献: