【问题标题】:Browse file in AngularJS + TypeScript on button click单击按钮在 AngularJS + TypeScript 中浏览文件
【发布时间】:2018-04-28 23:34:34
【问题描述】:

我有 user.component.htmluser.component.ts 我发现的所有示例都以这种方式在 html 中<input type="file" /> 我不想使用这种风格。我的 html 文件中有:

<button type="button" class="btn" (click)="openPicture()" Browse </button>

下面是ts文件上的函数:

  public openPicture() {
    //for testing
    console.log('button clicked to open picture');

    var picture = browse.the.picture.and.assing.to.this.variable;

    //another test, see on console if picture is read
    console.log('%c       ', 'font-size: 100px; background: {{picture}} no-repeat;');
    // Later display picture variable on html and save to database or do anything desired.
}

我在stackoverflow 上找到了exampleangular/material,但我没有这个模块。有没有其他替代方法,无需安装任何额外的包来解决这个问题?

【问题讨论】:

    标签: javascript html angularjs spring typescript


    【解决方案1】:

    您可以尝试在标签中使用旧的隐藏输入:

    <label class="btn">
        Browse <input type="file" style="display: none;" (change)="handleChange($event)">
    </label>
    

    handleChange 实现必须消耗事件:

    handleChange(event) {
        // consume event.target.files[0] which has File type
    }
    

    关于File的其他信息可以在MDN上找到

    【讨论】:

    • 我有点接近解决方案,我将 handleChange 更改为 public handleChange(event: MouseEvent) { } 但我的浏览按钮变大了,在浏览按钮内现在有第二个按钮“选择文件”和标签“否选择的文件”。当我单击浏览时没有任何反应,但是当我单击“选择文件”时,我可以选择一些东西。当然我只想要浏览按钮来选择文件。
    • 你把display: none的样式应用到input了吗?
    【解决方案2】:

    由于浏览器的安全功能,您实际上需要使用input 标签来访问文件系统。不过,您可以做的是隐藏 input 元素并从其余代码和标记中访问它。

    查看this related answer,了解您可以做什么。否则,这里有一个简单的例子来说明它是如何工作的:

    <input type="file" style="display: none" #file/>
    <button type="button" class="btn" (click)="file.click()" Browse </button
    

    【讨论】:

    • file.click() 让我选择一个文件,但是这个文件去哪里了?如何处理所选文件或将其传递给我自己的函数 openPicture() ?我想处理选定的文件,在 html 上显示,然后保存到 db。
    【解决方案3】:

    你可以这样实现

    <input type="file" style="display: none" #file (change)="fileChange($event)"/>
    <button type="button" class="btn" (click)="file.click()"> Browse </button>
    

    .ts

    export class AppComponent {
      file: File;
    
      constructor() {
    
      }
    
      fileChange(file) {
        this.file = file.target.files[0];
        console.log(this.file.name);
      }
    }
    

    【讨论】:

    • 谢谢它的工作,我选择了一个文件,然后它在控制台上给了我文件名,我想再次浏览但然后单击取消然后我得到这个错误:“错误类型错误:无法读取属性'名称'未定义的“有没有办法防止这种情况?我也可以指定浏览位置吗?
    • 1.无法读取未定义的属性'名称' => 你需要检查this.file!= undefined 2. 我可以指定浏览位置吗? => 不,你不能这样做
    • 当我加载相同的图像时,没有任何反应,有什么提示吗?这是我的新问题stackoverflow.com/questions/47473692/…
    猜你喜欢
    • 1970-01-01
    • 2012-08-24
    • 2012-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多