为什么我不能打开文件对话框与 typescript 伪造< a>链接< input type=file>

n3ipq98p  于 2023-06-24  发布在  TypeScript
关注(0)|答案(2)|浏览(180)

这里是我的情况,代码和来自Stackoverflow的参考。
我想触发打开对话框,我发现引用,但他们似乎不工作;

首先我的代码片段:

  1. <i class="fas fa-upload uploadicon"></i><br>
  2. Drop document here or
  3. <a href="javascript:;" class="dropimgmessage" id="uploadLink" name="uploadLink" ngbTooltip="Click to upload a document or drag here!" placement="top">browse</a>
  4. <input type="file" class="form-control fileuploader" #fileInput id="api-file-container" formControlName="docUpload" name="api-file-container" (change)="handleFileInput($event.target.files)">
  5. <span class="dropimagetypemsg">Supports PDF, JPG, PNG, GIF</span>

现在我的 typescript :

  1. declaration of variables:
  2. public uploadlink: HTMLElement;
  3. public fileinput: HTMLElement;
  4. ------
  5. ngAfterViewInit() {
  6. this.uploadlink = document.querySelector('#uploadLink') as HTMLElement;
  7. this.fileinput = document.querySelector('#api-file-container') as HTMLElement;
  8. this.uploadlink.addEventListener('click', (e: Event) => {
  9. e.preventDefault();
  10. this.fileinput.click();
  11. });
  12. }

发生的事情是,代码会触发,但不会进入片段:

  1. this.uploadlink.addEventListener('click', (e: Event) => {

它在. addEventListener处停止。
所以我试着从HTML调用一个函数onClick,就像这样。

  1. public fakeFileInput(e: Event): void {
  2. console.log('Fake Input to File Upload: ', e);
  3. if(this.uploadlink.getAttribute('text') === 'browse') {
  4. console.log('EVENT browse upload was click: ');
  5. this.uploadlink.setAttribute('defaultPrevented', 'false');
  6. this.fileinput.click();
  7. }
  8. }

通过将该调用添加到函数中,如下所示:

  1. <a href="javascript:;" (click)="fakeFileInput($event)" class="dropimgmessage" id="uploadLink" name="uploadLink" ngbTooltip="Click to upload a document or drag here!" placement="top">browse</a>

现在这是可行的,但是,我在这里得到了一个错误:文件选择器对话框只能在用户激活时显示。
我的参考资料:
Calling a typescript method from your html button onclick event
How to open a file / browse dialog using javascript?
How to make a link act as a file input
在JSFiddle -http://jsfiddle.net/7aGEv/3/
我哪里做错了?
谢谢你。

yzckvree

yzckvree1#

你不需要任何JS来触发没有按钮的文件上传,你可以简单地使用标签:

  1. <label for="uploadInput">browse</label>
  2. <input id="uploadInput" type="file" style="display:none" />
wwtsj6pe

wwtsj6pe2#

如果堆栈中没有用户交互(由浏览器控制),则无法以编程方式触发文件上传打开。这是浏览器的一项安全功能,用于防止恶意网站诱骗用户上传文件。

相关问题