简体   繁体   English

上传和验证-打字稿和角度

[英]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. 这也可以通过普通的javascript实现。 typescript is a superset of javascript. 打字稿是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);
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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