简体   繁体   中英

Upload and validation - Typescript and angular

This is just a feature of an app to check the file extension and size before uploading. No need for reading data. Examples will be appreciated. Thanks

this can be achieved by normal javascript too. typescript is a superset of javascript. you could write a function to check file size and extension. before that, you need to send an event to your function from view.

so in angular, you can try like

<input type="file" (change)="fileEvent($event)" >

and in typescript, you can write a function to check event like

 fileEvent(e) {

    /// get list of files
    let file_list = e.target.files;

    /// go through the list of files
    for (let i = 0, file; file = file_list[i]; i++) {

        let sFileName = file.name;
        let sFileExtension = sFileName.split('.')[sFileName.split('.').length - 1].toLowerCase();
        let iFileSize = file.size;
        let iConvert = (file.size / 1048576).toFixed(2);

        /// OR together the accepted extensions and NOT it. Then OR the size cond.
        /// It's easier to see this way, but just a suggestion - no requirement.
        if (!(sFileExtension === "pdf" ||
              sFileExtension === "doc" ||
              sFileExtension === "docx") || iFileSize > 10485760) { /// 10 mb
            txt = "File type : " + sFileExtension + "\n\n";
            txt += "Size: " + iConvert + " MB \n\n";
            txt += "Please make sure your file is in pdf or doc format and less than 10 MB.\n\n";
            alert(txt);
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM