Angular 4 文件上传

9

当我尝试在我的Angular 4应用程序中安装“npm install ng2-file-upload --save”时,会出现以下错误:

UNMET PEER DEPENDENCY @4.1.0
UNMET PEER DEPENDENCY @4.1.0
`-- ng2-file-upload@1.2.1

上传功能无法正常运作,我的应用程序会抛出以下错误信息:
"Can't bind to 'uploader' since it isn't a known property of 'input'"
这是我的HTML代码
<input type="file" ng2FileSelect [uploader]="upload" multiple formControlName="file" id="file"/>

以及它的组件

import { FileUploadModule } from 'ng2-file-upload/ng2-file-upload';   
import { FileSelectDirective, FileUploader } from 'ng2-file-upload/ng2-file-
upload';

export class PersonalInfoComponent implements OnInit
{
    public upload:FileUploader= new FileUploader({url:""});
}

父模块

import { FileUploadModule } from 'ng2-file-upload/ng2-file-upload';

@NgModule({

imports: [
..
....
..
FileUploadModule
],

export class RegistrationModule { }

我没有在AppModule(祖先模块)中导入/更改任何内容。

有人可以帮我吗...

6个回答

4

不使用插件在Angular 4中上传图片

这是一篇值得尝试的文章。

不使用插件在Angular 4中上传图片

它强调以下几点:

  1. 使用.request()方法而非.post方法
  2. 直接将formData发送到请求体中
  3. 自定义标题项和构建新的RequestOptions对象
  4. 为了发送包含图像内容的formData,必须删除Content-Type头部

不错的文章!它很有帮助。 - Adrita Sharma

3
我认为我们不需要额外的库。
onFileChange(event){
   let files = event.target.files; 
   this.saveFiles(files);
    }
@HostListener('dragover', ['$event']) onDragOver(event) {
    this.dragAreaClass = "droparea";
    event.preventDefault();
}
@HostListener('dragenter', ['$event']) onDragEnter(event) {
    this.dragAreaClass = "droparea";
    event.preventDefault();
}
@HostListener('dragend', ['$event']) onDragEnd(event) {
    this.dragAreaClass = "dragarea";
    event.preventDefault();
}
@HostListener('dragleave', ['$event']) onDragLeave(event) {
    this.dragAreaClass = "dragarea";
    event.preventDefault();
}
@HostListener('drop', ['$event']) onDrop(event) {   
    this.dragAreaClass = "dragarea";           
    event.preventDefault();
    event.stopPropagation();
    var files = event.dataTransfer.files;
    this.saveFiles(files);
}

现在我们可以通过拖放或点击链接按钮上传文件,并且还可以上传与文件相关的额外数据。

查看完整文章,请点击这里


2
您不需要外部库来实现此操作,请查看以下示例代码。
@Component({
    selector: 'app-root',
    template: '<div>'
        + '<input type="file" (change)="upload($event)">'
        + '</div>',
})

export class AppComponent {

    constructor(private _service: commonService) { }

    upload(event: any) {
        let files = event.target.files;
        let fData: FormData = new FormData;

        for (var i = 0; i < files.length; i++) {
            fData.append("file[]", files[i]);
        }
        var _data = {
            filename: 'Sample File',
            id: '0001'
        }

        fData.append("data", JSON.stringify(_data));

        this._service.uploadFile(fData).subscribe(
            response => this.handleResponse(response),
            error => this.handleError(error)
        )
    }
    handleResponse(response: any) {
        console.log(response);
    }
    handleError(error: string) {
        console.log(error);
    }
}

More info


2

常见的解决方案是创建新的模块,例如共享模块。你只需要像这样创建共享模块,并在app.module文件中导入共享模块。

import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';

import { FileSelectDirective, FileDropDirective } from 'ng2-file-upload';
import { FileUploadModule } from 'ng2-file-upload/ng2-file-upload';

@NgModule({
     imports: [ FileUploadModule],  
     declarations: [ ],
     exports :[ FileSelectDirective, FileDropDirective, FormsModule,
               FileUploadModule],
})
export class SharedModule { }

只需像这样在您的app.module中导入share.module。
import { NgModule } from '@angular/core';
import { SharedModule} from '../shared/shared.module';

@NgModule({
    imports: [SharedModule],
    declarations: [],
    exports :[],
   })
export class AppModule { }

看一下Angular 4中的懒加载


尝试执行此操作但出现错误:Type FileSelectDirective 是 2 个模块的声明的一部分:FileUploadModule 和 PackagesModule!请考虑将 FileSelectDirective 移动到导入 FileUploadModule 和 PackagesModule 的更高级别的模块中。您还可以创建一个新的 NgModule,该 NgModule 导出并包括 FileSelectDirective,然后在 FileUploadModule 和 PackagesModule 中导入该 NgModule。 - Damith Ganegoda
我认为你在两个模块中使用了文件选择指令,你使用的ng2-file-upload版本是哪个? - Sathish Kotha

0

HTML:

<input type="file" (change)="onFileChange($event)" id="file">

TS:

@Component({
  ......
})

export class myComponent{

    form: FormGroup;

    contructor(fb: FormGroup){
       form: fb.group({file: null});
    }

 //fVals comes from HTML Form -> (ngSubmit)="postImage(form.value)" 
    postImage(fVals){
      let body = new FormData();
      body.append('file', formValues.file);

      let httpRequest = httpclient.post(url, body);
      httpRequest.subscribe((response) =>{
         //..... handle response here
      },(error) => {
         //.....handle errors here
      });
   }

   onFileChange(event) {
     if(event.target.files.length > 0) {
       let file = event.target.files[0];
       this.form.get('file').setValue(file);
     }
   }
}

0

从primeng导入文件上传或使用简单的文件上传器

HTML

  <p-fileUpload name="myfile[]"  customUpload="true" 
     (uploadHandler)="uploadSuiteForRelease($event)" auto="auto"></p-fileUpload> 

TS

 var data = new FormData();
        let index: number = 0;
        if (this.files != undefined)
        {
            for (let file of this.files.files)
            {
                data.append("myFile" + index, file);
                ++index;
            }
        }
     data.append('viewModel', JSON.stringify(<<data model that needs to be 
     sent with request>>));

发送请求时,请使用以下数据:return this._httpClient.post('api/controller', data);

服务器

  [HttpPost]
        public async Task<IHttpActionResult> Post()
        {
            HttpPostedFile httpPostedFile = null;
            var viewModel = JsonConvert.DeserializeObject<ReleasesViewModel>(HttpContext.Current.Request["viewModel"]);
            if (viewModel != null)
            {
                if (HttpContext.Current.Request.Files.AllKeys.Any())
                {
                    var cnt = HttpContext.Current.Request.Files.Count;
                    for (int i = 0; i < cnt; i++)
                    {
                        httpPostedFile = HttpContext.Current.Request.Files["myFile" + i];
                    }
                }
            }
        }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接