【问题标题】:Ionic 2 Upload file from browserIonic 2 从浏览器上传文件
【发布时间】:2018-06-04 03:44:10
【问题描述】:

我有一个 Ionic 2 PWA,所以它应该在浏览器中运行。我希望用户可以将文件上传到服务器。因为 ionic native 的文件选择器仅适用于 android,所以我不能在浏览器中使用它。所以我的想法是使用 type="file" 的输入字段。但我的问题是,我只得到文件名而不是路径。要上传文件,我需要路径。起初我用 ngModel 尝试过,然后用 ionic 的表单生成器尝试过。这是我的表单生成器代码:

TS:

import {Component} from '@angular/core';
import {Validators, FormBuilder, FormGroup } from '@angular/forms';

@Component({
    selector: 'page-test',
    templateUrl: 'test.html',
})
export class TestPage {

    private file : FormGroup;

    constructor( private formBuilder: FormBuilder ) {
        this.file = this.formBuilder.group({
            image: ['']
        });
    }

    logForm(){
        console.log(this.file.value)
    }

}

HTML:

...
<ion-content padding>
    <form [formGroup]="file" (ngSubmit)="logForm()">
        <input type="file" size="50" formControlName="image">
        <button ion-button type="submit">Submit</button>
    </form>
</ion-content>

但就像我说的,控制台只记录文件名:

对象{图像:“2970.jpg”}

如果我记录“this.file”(没有 .value),我发现那里既没有文件对象也没有类似的东西。有没有办法在离子浏览器应用程序中获取文件路径以将其上传到服务器?

【问题讨论】:

  • 你试过我的解决方案了吗?如果有效,请接受我的回答...
  • 你找到解决办法了吗?

标签: file ionic-framework file-upload browser ionic2


【解决方案1】:

我不知道你是否已经找到了解决方案,但无论如何我都会发布它......

对于这个解决方案,您不需要任何外部 npm 模块。这是一步一步的

通过运行创建新组件

$ ionic generate component file-uploader

然后复制粘贴下面的代码

src/components/file-uploader/file-uploader.ts

import { Component, ViewChild, ElementRef, Input } from '@angular/core';

import 'rxjs/add/operator/map';
import { Observable } from 'rxjs/Observable';
import { HttpClient } from '@angular/common/http';

/**
 * Usage
 *
 *  <file-uploader [apiUrl]="apiUrl" [params]="uploadParams"></file-uploader>
 *
 *  <file-uploader [apiUrl]="apiUrl" [params]="[{'key':'language_code', 'value': 'en'}]"></file-uploader>
 *
 */

@Component({
selector: 'file-uploader',
templateUrl: 'file-uploader.html'
})
export class FileUploaderComponent
{
    @ViewChild('file') fileInput: ElementRef;

    @Input('apiUrl') apiUrl: string = null;

    @Input('params') params: Array<{key: string, value: string}> = [];

    @Input('buttonText') buttonText: string = 'Upload';

    @Input('buttonType') buttonType: 'button' | 'icon' = 'icon';

    @Input('icon') icon: string = 'cloud-upload';

    @Input('onUploadSuccess') onUploadSuccess: (file: File, response: any) => void
        = function (file: File, response: any) { console.log(file); console.log(response); };

    @Input('onUploadError') onUploadError: (file: File) => void = function (error: any) { console.log(error) };

    fileToUpload: File = null;

    constructor(private httpClient: HttpClient)
    {
    }

    triggerFileInputClick()
    {
        this.fileInput.nativeElement.click();
    }

    onFileInputChange(files: FileList)
    {
        this.fileToUpload = files.item(0);

        if (this.fileInput.nativeElement.value != '')
        {
            this.upload();
        }
    }

    upload()
    {
        const formData: FormData = new FormData();

        formData.append('file', this.fileToUpload, this.fileToUpload.name);

        this.params.map(param => {
            formData.append(param.key, param.value);
        });

        let headers = {};

        this.httpClient
            .post(this.apiUrl, formData, { headers: headers })
            // .map(() => { return true; })
            .subscribe(response => {
                this.onUploadSuccess(this.fileToUpload, response);

                this.fileInput.nativeElement.value = '';
            }, error => {
                this.onUploadError(error);
            });
    }
}

src/components/file-uploader/file-uploader.html

<div>

    <input type="file" #file (change)="onFileInputChange($event.target.files)">

    <button *ngIf="buttonType == 'button'" ion-button (click)="triggerFileInputClick()">{{buttonText}}</button>

    <ion-icon *ngIf="buttonType == 'icon'" name="cloud-upload" (click)="triggerFileInputClick()"></ion-icon>

</div>

src/components/file-uploader/file-uploader.scss

file-uploader {
    [type=file] {
        display: none;
    }
}

src/pages/home/home.html

<file-uploader [apiUrl]="apiUrl" [params]="[{'key':'language_code', 'value': languageCode}]"></file-uploader>

您现在需要做的就是在 NgModule 中加载组件并使用它。

我要提到的最后一件事是,如果您遇到未定义属性的问题,例如apiUrl,你应该在 ngOnInit() 方法中初始化它们。

希望有帮助

更新 不要忘记将文件上传器导入到使用上传器的组件中,否则你会得到 Can't bind to 'apiUrl' because it is not a known property of 'file-uploader'错误。 我所做的是在 components 文件夹中创建了新的模块 components.module.ts 文件。然后我将文件上传器组件导入其中。为了使用它,我将 components 模块导入到使用文件上传器组件的组件中。

src/components/components.module.ts

import { IonicModule } from 'ionic-angular';
import { NgModule } from '@angular/core';
import { FileUploaderComponent } from './file-uploader/file-uploader';

@NgModule({
    declarations: [
        FileUploaderComponent
    ],
    imports: [
        IonicModule,
    ],
    exports: [
        FileUploaderComponent
    ]
})
export class ComponentsModule {}

src/pages/home/home.module.ts

import { ComponentsModule } from '../../components/components.module';

【讨论】:

  • 出现错误......无法绑定到“apiUrl”,因为它不是“文件上传器”的已知属性。 1. 如果'file-uploader'是一个Angular组件并且它有'apiUrl'输入,那么验证它是这个模块的一部分。 2. 如果 'file-uploader' 是一个 Web 组件,则将 'CUSTOM_ELEMENTS_SCHEMA' 添加到该组件的 '@NgModule.schemas' 以禁止显示此消息。 3. 允许任何属性将“NO_ERRORS_SCHEMA”添加到该组件的“@NgModule.schemas”。 (" ][apiUrl]="apiUrl" [params]="[{'key':'language_code', 'value': languageCode}]">
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-03-27
  • 1970-01-01
  • 2018-09-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多