File Upload In Angular?

前端 未结 14 2304
执念已碎
执念已碎 2020-11-22 08:10

I know this is very a general question but I am failing to upload a file in Angular 2. I have tried

1) http://valor-software.com/ng2-file-upload/ and

2) h

相关标签:
14条回答
  • 2020-11-22 08:58

    jspdf and Angular 8

    I generate a pdf and want to upload the pdf with POST request, this is how I do (For clarity, I delete some of the code and service layer)

    import * as jsPDF from 'jspdf';
    import { HttpClient } from '@angular/common/http';
    
    constructor(private http: HttpClient)
    
    upload() {
        const pdf = new jsPDF()
        const blob = pdf.output('blob')
        const formData = new FormData()
        formData.append('file', blob)
        this.http.post('http://your-hostname/api/upload', formData).subscribe()
    }
    
    0 讨论(0)
  • 2020-11-22 08:59

    Angular 2 provides good support for uploading files. No third party library is required.

    <input type="file" (change)="fileChange($event)" placeholder="Upload file" accept=".pdf,.doc,.docx">
    
    fileChange(event) {
        let fileList: FileList = event.target.files;
        if(fileList.length > 0) {
            let file: File = fileList[0];
            let formData:FormData = new FormData();
            formData.append('uploadFile', file, file.name);
            let headers = new Headers();
            /** In Angular 5, including the header Content-Type can invalidate your request */
            headers.append('Content-Type', 'multipart/form-data');
            headers.append('Accept', 'application/json');
            let options = new RequestOptions({ headers: headers });
            this.http.post(`${this.apiEndPoint}`, formData, options)
                .map(res => res.json())
                .catch(error => Observable.throw(error))
                .subscribe(
                    data => console.log('success'),
                    error => console.log(error)
                )
        }
    }
    

    using @angular/core": "~2.0.0" and @angular/http: "~2.0.0"

    0 讨论(0)
  • 2020-11-22 08:59

    In Angular 2+, it is very important to leave the Content-Type empty. If you set the 'Content-Type' to 'multipart/form-data' the upload will not work !

    upload.component.html

    <input type="file" (change)="fileChange($event)" name="file" />
    

    upload.component.ts

    export class UploadComponent implements OnInit {
        constructor(public http: Http) {}
    
        fileChange(event): void {
            const fileList: FileList = event.target.files;
            if (fileList.length > 0) {
                const file = fileList[0];
    
                const formData = new FormData();
                formData.append('file', file, file.name);
    
                const headers = new Headers();
                // It is very important to leave the Content-Type empty
                // do not use headers.append('Content-Type', 'multipart/form-data');
                headers.append('Authorization', 'Bearer ' + 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9....');
                const options = new RequestOptions({headers: headers});
    
                this.http.post('https://api.mysite.com/uploadfile', formData, options)
                     .map(res => res.json())
                     .catch(error => Observable.throw(error))
                     .subscribe(
                         data => console.log('success'),
                         error => console.log(error)
                     );
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-22 09:01

    I've upload file using reference. No package is required to upload file this way.

    // code to be written in .ts file

    @ViewChild("fileInput") fileInput;
    
    addFile(): void {
    let fi = this.fileInput.nativeElement;
    if (fi.files && fi.files[0]) {
      let fileToUpload = fi.files[0];
        this.admin.addQuestionApi(fileToUpload)
          .subscribe(
            success => {
              this.loading = false;
              this.flashMessagesService.show('Uploaded successfully', {
                classes: ['alert', 'alert-success'],
                timeout: 1000,
              });
            },
            error => {
              this.loading = false;
              if(error.statusCode==401) this.router.navigate(['']);
              else
                this.flashMessagesService.show(error.message, {
                  classes: ['alert', 'alert-danger'],
                  timeout: 1000,
                });
            });
      }
    

    }

    // code to be written in service.ts file

    addQuestionApi(fileToUpload: any){
    var headers = this.getHeadersForMultipart();
    let input = new FormData();
    input.append("file", fileToUpload);
    
    return this.http.post(this.baseUrl+'addQuestions', input, {headers:headers})
          .map(response => response.json())
          .catch(this.errorHandler);
    

    }

    // code to be written in html

    <input type="file" #fileInput>
    
    0 讨论(0)
  • 2020-11-22 09:04

    To upload image with form fields

    SaveFileWithData(article: ArticleModel,picture:File): Observable<ArticleModel> 
    {
    
        let headers = new Headers();
        // headers.append('Content-Type', 'multipart/form-data');
        // headers.append('Accept', 'application/json');
    
    let requestoptions = new RequestOptions({
      method: RequestMethod.Post,
      headers:headers
        });
    
    
    
    let formData: FormData = new FormData();
    if (picture != null || picture != undefined) {
      formData.append('files', picture, picture.name);
    }
     formData.append("article",JSON.stringify(article));
    
    return this.http.post("url",formData,requestoptions)
      .map((response: Response) => response.json() as ArticleModel);
    } 
    

    In my case I needed .NET Web Api in C#

    // POST: api/Articles
    [ResponseType(typeof(Article))]
    public async Task<IHttpActionResult> PostArticle()
    {
        Article article = null;
        try
        {
    
            HttpPostedFile postedFile = null;
            var httpRequest = HttpContext.Current.Request;
    
            if (httpRequest.Files.Count == 1)
            {
                postedFile = httpRequest.Files[0];
                var filePath = HttpContext.Current.Server.MapPath("~/" + postedFile.FileName);
                postedFile.SaveAs(filePath);
            }
            var json = httpRequest.Form["article"];
             article = JsonConvert.DeserializeObject <Article>(json);
    
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }
    
            article.CreatedDate = DateTime.Now;
            article.CreatedBy = "Abbas";
    
            db.articles.Add(article);
            await db.SaveChangesAsync();
        }
        catch (Exception ex)
        {
            int a = 0;
        }
        return CreatedAtRoute("DefaultApi", new { id = article.Id }, article);
    }
    
    0 讨论(0)
  • 2020-11-22 09:09

    From the answers above I build this with Angular 5.x

    Just call uploadFile(url, file).subscribe() to trigger an upload

    import { Injectable } from '@angular/core';
    import {HttpClient, HttpParams, HttpRequest, HttpEvent} from '@angular/common/http';
    import {Observable} from "rxjs";
    
    @Injectable()
    export class UploadService {
    
      constructor(private http: HttpClient) { }
    
      // file from event.target.files[0]
      uploadFile(url: string, file: File): Observable<HttpEvent<any>> {
    
        let formData = new FormData();
        formData.append('upload', file);
    
        let params = new HttpParams();
    
        const options = {
          params: params,
          reportProgress: true,
        };
    
        const req = new HttpRequest('POST', url, formData, options);
        return this.http.request(req);
      }
    }
    

    Use it like this in your component

      // At the drag drop area
      // (drop)="onDropFile($event)"
      onDropFile(event: DragEvent) {
        event.preventDefault();
        this.uploadFile(event.dataTransfer.files);
      }
    
      // At the drag drop area
      // (dragover)="onDragOverFile($event)"
      onDragOverFile(event) {
        event.stopPropagation();
        event.preventDefault();
      }
    
      // At the file input element
      // (change)="selectFile($event)"
      selectFile(event) {
        this.uploadFile(event.target.files);
      }
    
      uploadFile(files: FileList) {
        if (files.length == 0) {
          console.log("No file selected!");
          return
    
        }
        let file: File = files[0];
    
        this.upload.uploadFile(this.appCfg.baseUrl + "/api/flash/upload", file)
          .subscribe(
            event => {
              if (event.type == HttpEventType.UploadProgress) {
                const percentDone = Math.round(100 * event.loaded / event.total);
                console.log(`File is ${percentDone}% loaded.`);
              } else if (event instanceof HttpResponse) {
                console.log('File is completely loaded!');
              }
            },
            (err) => {
              console.log("Upload Error:", err);
            }, () => {
              console.log("Upload done");
            }
          )
      }
    
    0 讨论(0)
提交回复
热议问题