【问题标题】:File Upload in Angular 4Angular 4 中的文件上传
【发布时间】:2023-04-07 18:20:01
【问题描述】:

当我尝试安装时 “npm install ng2-file-upload --save” 在我的 Angular 4 应用程序中它抛出

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

上传不工作 我的应用程序抛出

"无法绑定到 'uploader',因为它不是 '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(祖父模块)中导入/更改任何内容。

有人可以帮我解决这个问题吗...

【问题讨论】:

    标签: angular file-upload dependencies peer


    【解决方案1】:

    从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];
                        }
                    }
                }
            }
    

    【讨论】:

      【解决方案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

      【讨论】:

        【解决方案3】:

        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);
             }
           }
        }
        

        【讨论】:

          【解决方案4】:

          我认为我们不需要一些额外的库

          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);
          }
          

          现在我们已经准备好通过拖放以及单击链接按钮上传文件并上传带有文件的额外数据。

          在此处查看完整文章Angular 4 upload files with data and web api by drag & drop

          【讨论】:

            【解决方案5】:

            在没有插件的情况下在 Angular 4 中上传图片 这是可能值得一试的文章。 Upload images in Angular 4 without a plugin

            强调以下几点:

            1. 使用 .request() 方法代替 .post
            2. 将 formData 直接发送到正文中。
            3. 自定义标头项并构造新的 RequestOptions 对象。
            4. 要发送带有图像内容的 formData,您必须删除 Content-Type 标头。

            【讨论】:

            • 好文章!它有帮助。
            【解决方案6】:

            常见的解决方案是创建像shared module 这样的新模块。您只需要创建共享模块,例如 这个并在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 中的延迟加载

            【讨论】:

            • 尝试执行此操作但出现此错误,类型 FileSelectDirective 是 2 个模块声明的一部分:FileUploadModule 和 PackagesModule!请考虑将 FileSelectDirective 移至导入 FileUploadModule 和 PackagesModule 的更高模块。您还可以创建一个新的 NgModule,它导出并包含 FileSelectDirective,然后在 FileUploadModule 和 PackagesModule 中导入该 NgModule。
            • 我认为您在 2 个模块中使用了文件选择指令,以及您使用的 ng2-file-upload 版本。
            猜你喜欢
            • 2017-11-09
            • 1970-01-01
            • 1970-01-01
            • 2018-10-29
            • 2023-03-18
            • 2018-06-21
            • 2018-05-06
            • 1970-01-01
            • 2017-12-22
            相关资源
            最近更新 更多