File Upload in Angular 4

二次信任 提交于 2019-12-03 01:11:37

Upload images in Angular 4 without a plugin This is the article that might be worth trying. Upload images in Angular 4 without a plugin

It emphasize on these points:

  1. Using the .request() method instead of .post
  2. Sending formData straight into the body.
  3. Customizing header items and constructing a new RequestOptions object.
  4. In order to send formData with image content you must remove the Content-Type header.

I don't think we need some extra libraries

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

And now we are ready to upload files with drag and drop as well as by clicking the link button and upload extra data with files.

See the complete article here Angular 4 upload files with data and web api by drag & drop

For common solution is to create new module like shared module. You just need create shared module like this and import shared module in app.module file

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 { }

just import share.module in your app.module like this.

import { NgModule } from '@angular/core';
import { SharedModule} from '../shared/shared.module';

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

take a look on lazy loading in angular 4

You don't need an external library to do this, check below sample code

@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

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

import fileupload from primeng or use simple file uploader

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

Send this data with request return this._httpClient.post('api/controller', data);

Server

  [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];
                    }
                }
            }
        }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!