【问题标题】:Typescript file upload validation打字稿文件上传验证
【发布时间】:2019-04-12 19:06:56
【问题描述】:

我正在尝试上传文件,但我收到以下代码的错误。错误是 HTML 元素类型上不存在属性。如何解决?

我已经注释了以下代码行的错误。

component.html

<input type="file" name="fileToUpload" id="fileToUpload" onchange="fileSelected();"/>

   <ul>
     <label>Select a Module Name</label>
     <select id = "ModuleDropDown">
       <option value="">Select</option>
       <option value="Recuirtmnet">Recuirtmnet</option>
       <option value="Talent" selected="selected">Talent</option>
       <option value="Attrition">Attrition</option>
       <option value="Performance">Performance</option>
       <option value="Survey">Survey</option>
      </select>
     </ul>

    <div id="fileName"></div>
    <div id="fileSize"></div>
    <div id="fileType"></div>

component.ts

fileSelected() {

    //Property 'files' does not exist on type 'HTMLElement'
    let file = document.getElementById('fileToUpload').files[0]; 

    if (file) {
        let fileSize = 0;
        if (file.size > 1024 * 1024)
            this.fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() + 'MB';
        else
            this.fileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + 'KB';

        document.getElementById('fileName').innerHTML = 'Name: ' + file.name;
        document.getElementById('fileSize').innerHTML = 'Size: ' + fileSize;
        document.getElementById('fileType').innerHTML = 'Type: ' + file.type;
        let dropDown = document.getElementById("ModuleDropDown");


        //Property 'options' does not exist on type 'HTMLElement'.
        //Property 'selectedIndex' does not exist on type 'HTMLElement'
        let dpVal = dropDown.options[dropDown.selectedIndex].value;

        let init_params = {};
        this.init_params.action = 'prepare';
        this.init_params.file_name = file.name;
        this.init_params.file_size = fileSize;
        this.init_params.moduleName = dpVal;

        ws.send(JSON.stringify(init_params))
        console.log("sending init params.....")

    }
}

【问题讨论】:

  • 你到底想在这里实现什么?
  • 我正在尝试上传文件,提交后尝试获取文件名、文件大小和文件类型,而在另一部分尝试获取下拉值。
  • 我认为你使用了一种不好的方法。在角面糊中使用更改事件并处理此事件。然后从事件中获取文件 那里你可以找到一个很好的例子stackoverflow.com/questions/47936183/angular-file-upload

标签: angular html typescript file-upload angular6


【解决方案1】:

您的代码存在很多问题。您正在使用 Vanilla JavaScript 而不是利用 Angular 语法。

  1. 可以使用(change) 跟踪文件输入的更改并将$event 对象传递给更改处理程序。

  2. 您可以使用[(ngModel)] 从下拉列表中获取所选选项的值。

  3. 不建议使用document 访问 DOM 并对其进行更改或向其显示数据。您应该改用字符串插值语法({{}})。

这里有一个Sample StackBlitz 供您参考。

选择一个选项,然后上传文件以在 UI 上查看选定文件详细信息,并在控制台上查看选定下拉选项。

【讨论】:

    猜你喜欢
    • 2022-11-19
    • 1970-01-01
    • 1970-01-01
    • 2015-02-25
    • 1970-01-01
    • 2022-12-01
    • 1970-01-01
    • 2017-12-22
    相关资源
    最近更新 更多