Tải lên tập tin góc


189

Tôi là người mới bắt đầu với Angular, tôi muốn biết cách tạo phần tải lên tập tin Angular 5 , tôi đang cố gắng tìm bất kỳ hướng dẫn hoặc tài liệu nào, nhưng tôi không thấy bất cứ điều gì ở bất cứ đâu. Bất cứ ý tưởng cho điều này? Và tôi đang thử tập tin ng4 nhưng nó không hoạt động cho Angular 5


2
Vì vậy, bạn muốn kéo và thả hoặc Choose Filetải lên btn đơn giản ? Bdw trong cả hai trường hợp bạn chỉ cần tải lên bằng FormData
Dhyey

4
Hãy nhìn vào Primeng, tôi đã sử dụng nó một thời gian và nó hoạt động với v5 góc. primefaces.org/primeng/#/fileupload
Bunyamin Coskuner

Đối với những người chỉ cần tải JSON lên máy khách, hãy xem câu hỏi này: stackoverflow.com/questions/54971238/
Kẻ

Câu trả lời:


419

Dưới đây là một ví dụ hoạt động để tải tệp lên api:

Bước 1: Mẫu HTML (tệp-upload.component.html)

Xác định thẻ đầu vào đơn giản của loại file. Thêm một chức năng để có thể (change)xử lý việc chọn tập tin.

<div class="form-group">
    <label for="file">Choose File</label>
    <input type="file"
           id="file"
           (change)="handleFileInput($event.target.files)">
</div>

Bước 2: Xử lý tải lên trong TypeScript (file-upload.component.ts)

Xác định một biến mặc định cho tập tin được chọn.

fileToUpload: File = null;

Tạo chức năng mà bạn sử dụng không (change)liên quan đến thẻ nhập tệp của bạn:

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

Nếu bạn muốn xử lý lựa chọn đa biến, hơn bạn có thể lặp qua mảng tệp này.

Bây giờ tạo chức năng tải lên tệp bằng cách gọi cho bạn tệp-upload.service:

uploadFileToActivity() {
    this.fileUploadService.postFile(this.fileToUpload).subscribe(data => {
      // do something, if upload success
      }, error => {
        console.log(error);
      });
  }

Bước 3: Dịch vụ tải tệp lên (tệp-upload.service.ts)

Bằng cách tải lên một tệp qua phương thức POST, bạn nên sử dụng FormData, vì vậy bạn có thể thêm tệp vào yêu cầu http.

postFile(fileToUpload: File): Observable<boolean> {
    const endpoint = 'your-destination-url';
    const formData: FormData = new FormData();
    formData.append('fileKey', fileToUpload, fileToUpload.name);
    return this.httpClient
      .post(endpoint, formData, { headers: yourHeadersConfig })
      .map(() => { return true; })
      .catch((e) => this.handleError(e));
}

Vì vậy, đây là ví dụ làm việc rất đơn giản, mà tôi sử dụng hàng ngày trong công việc của mình.


6
@Katie bạn có kích hoạt polyfill không?
Gregor Dorosunn

2
@GregorDoroschenko Tôi đã cố gắng sử dụng một mô hình có thông tin bổ sung về tệp và tôi phải làm điều này để làm cho nó hoạt động: const invFormData: FormData = new FormData(); invFormData.append('invoiceAttachment', invoiceAttachment, invoiceAttachment.name); invFormData.append('invoiceInfo', JSON.stringify(invoiceInfo)); Bộ điều khiển có hai tham số tương ứng, nhưng tôi phải phân tích JSON trong bộ điều khiển. Bộ điều khiển Core 2 của tôi sẽ không tự động chọn mô hình trong tham số. Thiết kế ban đầu của tôi là một mô hình với thuộc tính tệp, nhưng tôi không thể làm cho nó hoạt động
Papa Stahl

1
@GregorDoroschenko Tôi đã thử mã nàycreateContrat(fileToUpload: File, newContrat: Contrat): Observable<boolean> { let headers = new Headers(); const endpoint = Api.getUrl(Api.URLS.createContrat)); const formData: FormData =new FormData(); formData.append('fileKey', fileToUpload, FileToUpload.name); let body newContrat.gup(this.auth.getCurrentUser().token); return this.http .post(endpoint, formData, body) .map(() => { return true; }) }
OnnaB

1
@GregorDoroschenko Và đối với tôi không hoạt động. Tôi đăng trong ws:Content-Disposition: form-data; name="fileKey"; filename="file.docx" Content-Type: application/octet-stream <file>
OnnaB

1
@OnnaB Nếu bạn đang sử dụng FormData cho tệp và cho các thuộc tính khác, thì bạn nên phân tích tệp của mình và các thuộc tính khác dưới dạng FormData. Bạn không thể sử dụng FormData và cơ thể cùng một lúc.
Gregor Dorosunn

22

Bằng cách này, tôi triển khai tệp tải lên lên API web trong dự án.

Tôi chia sẻ cho ai quan tâm.

const formData: FormData = new FormData();
formData.append('Image', image, image.name);
formData.append('ComponentId', componentId);
return this.http.post('/api/dashboard/UploadImage', formData);

Từng bước một

API web ASP.NET

[HttpPost]
[Route("api/dashboard/UploadImage")]
public HttpResponseMessage UploadImage() 
{
    string imageName = null;
    var httpRequest = HttpContext.Current.Request;
    //Upload Image
    var postedFile = httpRequest.Files["Image"];
    //Create custom filename
    if (postedFile != null)
    {
        imageName = new String(Path.GetFileNameWithoutExtension(postedFile.FileName).Take(10).ToArray()).Replace(" ", "-");
        imageName = imageName + DateTime.Now.ToString("yymmssfff") + Path.GetExtension(postedFile.FileName);
        var filePath = HttpContext.Current.Server.MapPath("~/Images/" + imageName);
        postedFile.SaveAs(filePath);
    }
}

Biểu mẫu HTML

<form #imageForm=ngForm (ngSubmit)="OnSubmit(Image)">

    <img [src]="imageUrl" class="imgArea">
    <div class="image-upload">
        <label for="file-input">
            <img src="upload.jpg" />
        </label>

        <input id="file-input" #Image type="file" (change)="handleFileInput($event.target.files)" />
        <button type="submit" class="btn-large btn-submit" [disabled]="Image.value=='' || !imageForm.valid"><i
                class="material-icons">save</i></button>
    </div>
</form>

Tệp TS để sử dụng API

OnSubmit(Image) {
    this.dashboardService.uploadImage(this.componentId, this.fileToUpload).subscribe(
      data => {
        console.log('done');
        Image.value = null;
        this.imageUrl = "/assets/img/logo.png";
      }
    );
  }

Dịch vụ TS

uploadImage(componentId, image) {
        const formData: FormData = new FormData();
        formData.append('Image', image, image.name);
        formData.append('ComponentId', componentId);
        return this.http.post('/api/dashboard/UploadImage', formData);
    }

1
Cách của bạn không gửi tiêu đề là gì?
Shalom Dahan

14

Phương pháp rất dễ dàng và nhanh nhất là sử dụng ng2-file-upload .

Cài đặt ng2-file-upload qua npm. npm i ng2-file-upload --save

Tại mô-đun nhập đầu tiên trong mô-đun của bạn.

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

Add it to [imports] under @NgModule:
imports: [ ... FileUploadModule, ... ]

Đánh dấu:

<input ng2FileSelect type="file" accept=".xml" [uploader]="uploader"/>

Trong ts commponent của bạn:

import { FileUploader } from 'ng2-file-upload';
...
uploader: FileUploader = new FileUploader({ url: "api/your_upload", removeAfterUpload: false, autoUpload: true });

Đó là cách sử dụng đơn giản nhất của việc này. Để biết tất cả sức mạnh của điều này xem bản demo


4
Làm thế nào để có được phản hồi khi hình ảnh được tải lên? Điều gì sẽ là phản ứng, tài liệu bị thiếu phần này.
Muhammad Shahzad

7

Tôi đang sử dụng Angular 5.2.11, tôi thích giải pháp được cung cấp bởi Gregor Doroschenko, tuy nhiên tôi nhận thấy rằng tệp được tải lên là byte không, tôi phải thực hiện một thay đổi nhỏ để làm cho nó hoạt động.

postFile(fileToUpload: File): Observable<boolean> {
  const endpoint = 'your-destination-url';
  return this.httpClient
    .post(endpoint, fileToUpload, { headers: yourHeadersConfig })
    .map(() => { return true; })
    .catch((e) => this.handleError(e));
}

Các dòng sau (formData) không hoạt động với tôi.

const formData: FormData = new FormData();
formData.append('fileKey', fileToUpload, fileToUpload.name);

https://github.com/amitrke/ngrke/blob/master/src/app/service/fileupload.service.ts


6

Ok, vì chủ đề này xuất hiện trong số các kết quả đầu tiên của google và đối với những người dùng khác có cùng câu hỏi, bạn không cần phải quay lại bánh xe như được chỉ ra bởi trueboroda, có thư viện tải lên tệp ng2 giúp đơn giản hóa quá trình tải lên này tập tin với góc 6 và 7 tất cả những gì bạn cần làm là:

Cài đặt CLI góc mới nhất

yarn add global @angular/cli

Sau đó cài đặt rx-compat cho mối quan tâm tương thích

npm install rxjs-compat --save

Cài đặt ng2-file-upload

npm install ng2-file-upload --save

Nhập Chỉ thị FileSelectDirective trong mô-đun của bạn.

import { FileSelectDirective } from 'ng2-file-upload';

Add it to [declarations] under @NgModule:
declarations: [ ... FileSelectDirective , ... ]

Trong thành phần của bạn

import { FileUploader } from 'ng2-file-upload/ng2-file-upload';
...

export class AppComponent implements OnInit {

   public uploader: FileUploader = new FileUploader({url: URL, itemAlias: 'photo'});
}

Bản mẫu

<input type="file" name="photo" ng2FileSelect [uploader]="uploader" />

Để hiểu rõ hơn, bạn có thể kiểm tra liên kết này: Cách tải lên tệp bằng góc 6/7


1
Cảm ơn các liên kết. Tải lên hoạt động tốt trên máy tính để bàn nhưng tôi không thể tải lên để hoạt động trên các thiết bị di động như iOS. Tôi có thể chọn một tệp từ cuộn camera nhưng khi tôi tải lên thì nó luôn bị lỗi. Có ý kiến ​​gì không? FYI, chạy cái này trong safari di động, không phải trong một ứng dụng được cài đặt.
ScottN

1
Xin chào @ScottN và bạn được chào đón, có thể vấn đề đến từ trình duyệt bạn đang sử dụng? bạn đã thử nó với một cái khác chưa?
Mohamed Makkaoui

1
Xin chào @Mohamed Makkaoui cảm ơn bạn đã trả lời. Tôi đã thử nó trong Chrome trên iOS và vẫn cho kết quả tương tự. Tôi tò mò nếu đây là một vấn đề tiêu đề khi đăng lên máy chủ? Tôi đang sử dụng một WebAPI tùy chỉnh được viết bằng .Net và KHÔNG AWS FYI.
ScottN

1
Xin chào @ScottN, chúng tôi sẽ không thể biết liệu đó có phải là sự cố tiêu đề hay không cho đến khi bạn gỡ lỗi mã của mình bằng liên kết này developers.google.com/web/tools/chrome-devtools/ , và xem bạn nhận được thông báo lỗi nào.
Mohamed Makkaoui

6

Cá nhân tôi đang làm điều này bằng cách sử dụng ngx-liệu-file-input cho front-end và Firebase cho back-end. Chính xác hơn là C Storage Storage cho Firebase cho back-end kết hợp với Cloud Firestore. Bên dưới một ví dụ, giới hạn tệp không lớn hơn 20 MB và chỉ chấp nhận các phần mở rộng tệp nhất định. Tôi cũng đang sử dụng Cloud Firestore để lưu trữ các liên kết đến các tệp đã tải lên, nhưng bạn có thể bỏ qua phần này.

contact.component.html

<mat-form-field>
  <!--
    Accept only files in the following format: .doc, .docx, .jpg, .jpeg, .pdf, .png, .xls, .xlsx. However, this is easy to bypass, Cloud Storage rules has been set up on the back-end side.
  -->
  <ngx-mat-file-input
    [accept]="[
      '.doc',
      '.docx',
      '.jpg',
      '.jpeg',
      '.pdf',
      '.png',
      '.xls',
      '.xlsx'
    ]"
    (change)="uploadFile($event)"
    formControlName="fileUploader"
    multiple
    aria-label="Here you can add additional files about your project, which can be helpeful for us."
    placeholder="Additional files"
    title="Additional files"
    type="file"
  >
  </ngx-mat-file-input>
  <mat-icon matSuffix>folder</mat-icon>
  <mat-hint
    >Accepted formats: DOC, DOCX, JPG, JPEG, PDF, PNG, XLS and XLSX,
    maximum files upload size: 20 MB.
  </mat-hint>
  <!--
    Non-null assertion operators are required to let know the compiler that this value is not empty and exists.
  -->
  <mat-error
    *ngIf="contactForm.get('fileUploader')!.hasError('maxContentSize')"
  >
    This size is too large,
    <strong
      >maximum acceptable upload size is
      {{
        contactForm.get('fileUploader')?.getError('maxContentSize')
          .maxSize | byteFormat
      }}</strong
    >
    (uploaded size:
    {{
      contactForm.get('fileUploader')?.getError('maxContentSize')
        .actualSize | byteFormat
    }}).
  </mat-error>
</mat-form-field>

contact.component.ts (phần xác nhận kích thước)

import { FileValidator } from 'ngx-material-file-input';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

/**
 * @constructor
 * @description Creates a new instance of this component.
 * @param  {formBuilder} - an abstraction class object to create a form group control for the contact form.
 */
constructor(
  private angularFirestore: AngularFirestore,
  private angularFireStorage: AngularFireStorage,
  private formBuilder: FormBuilder
) {}

public maxFileSize = 20971520;
public contactForm: FormGroup = this.formBuilder.group({
    fileUploader: [
      '',
      Validators.compose([
        FileValidator.maxContentSize(this.maxFileSize),
        Validators.maxLength(512),
        Validators.minLength(2)
      ])
    ]
})

contact.component.ts (phần tải lên tập tin)

import { AngularFirestore } from '@angular/fire/firestore';
import {
  AngularFireStorage,
  AngularFireStorageReference,
  AngularFireUploadTask
} from '@angular/fire/storage';
import { catchError, finalize } from 'rxjs/operators';
import { throwError } from 'rxjs';

public downloadURL: string[] = [];
/**
* @description Upload additional files to Cloud Firestore and get URL to the files.
   * @param {event} - object of sent files.
   * @returns {void}
   */
  public uploadFile(event: any): void {
    // Iterate through all uploaded files.
    for (let i = 0; i < event.target.files.length; i++) {
      const randomId = Math.random()
        .toString(36)
        .substring(2); // Create random ID, so the same file names can be uploaded to Cloud Firestore.

      const file = event.target.files[i]; // Get each uploaded file.

      // Get file reference.
      const fileRef: AngularFireStorageReference = this.angularFireStorage.ref(
        randomId
      );

      // Create upload task.
      const task: AngularFireUploadTask = this.angularFireStorage.upload(
        randomId,
        file
      );

      // Upload file to Cloud Firestore.
      task
        .snapshotChanges()
        .pipe(
          finalize(() => {
            fileRef.getDownloadURL().subscribe((downloadURL: string) => {
              this.angularFirestore
                .collection(process.env.FIRESTORE_COLLECTION_FILES!) // Non-null assertion operator is required to let know the compiler that this value is not empty and exists.
                .add({ downloadURL: downloadURL });
              this.downloadURL.push(downloadURL);
            });
          }),
          catchError((error: any) => {
            return throwError(error);
          })
        )
        .subscribe();
    }
  }

lưu trữ.rules

rules_version = '2';
service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
        allow read; // Required in order to send this as attachment.
      // Allow write files Firebase Storage, only if:
      // 1) File is no more than 20MB
      // 2) Content type is in one of the following formats: .doc, .docx, .jpg, .jpeg, .pdf, .png, .xls, .xlsx.
      allow write: if request.resource.size <= 20 * 1024 * 1024
        && (request.resource.contentType.matches('application/msword')
        || request.resource.contentType.matches('application/vnd.openxmlformats-officedocument.wordprocessingml.document')
        || request.resource.contentType.matches('image/jpg')
        || request.resource.contentType.matches('image/jpeg')
        || request.resource.contentType.matches('application/pdf')
                || request.resource.contentType.matches('image/png')
        || request.resource.contentType.matches('application/vnd.ms-excel')
        || request.resource.contentType.matches('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'))
    }
  }
}

2
Nhìn tuyệt vời, nhưng tại sao bạn cần toString()tại khai báo contactForm?
trungk18

1
@ trungk18 kiểm tra lại một lần nữa và bạn đúng toString()là vô dụng, đã chỉnh sửa câu trả lời của tôi. Đối với những người sẽ đọc bình luận này, vào cuối fileUploadertrong contact.component.ts tôi đã có ])].toString()}). Bây giờ nó chỉ đơn giản là : ])]}).
Daniel Danielecki

5
  1. HTML

    <div class="form-group">
      <label for="file">Choose File</label><br /> <input type="file" id="file" (change)="uploadFiles($event.target.files)">
    </div>

    <button type="button" (click)="RequestUpload()">Ok</button>
  1. Tập tin ts
public formData = new FormData();
ReqJson: any = {};

uploadFiles( file ) {
        console.log( 'file', file )
        for ( let i = 0; i < file.length; i++ ) {
            this.formData.append( "file", file[i], file[i]['name'] );
        }
    }

RequestUpload() {
        this.ReqJson["patientId"] = "12"
        this.ReqJson["requesterName"] = "test1"
        this.ReqJson["requestDate"] = "1/1/2019"
        this.ReqJson["location"] = "INDIA"
        this.formData.append( 'Info', JSON.stringify( this.ReqJson ) )
            this.http.post( '/Request', this.formData )
                .subscribe(( ) => {                 
                });     
    }
  1. Mùa xuân cuối cùng (tập tin java)

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class Request {
    private static String UPLOADED_FOLDER = "c://temp//";

    @PostMapping("/Request")
    @ResponseBody
    public String uploadFile(@RequestParam("file") MultipartFile file, @RequestParam("Info") String Info) {
        System.out.println("Json is" + Info);
        if (file.isEmpty()) {
            return "No file attached";
        }
        try {
            // Get the file and save it somewhere
            byte[] bytes = file.getBytes();
            Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename());
            Files.write(path, bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "Succuss";
    }
}

Chúng ta phải tạo một thư mục "temp" trong ổ C, sau đó mã này sẽ in Json trong bảng điều khiển và lưu tệp đã tải lên trong thư mục đã tạo


Làm thế nào để chúng tôi lấy lại tập tin đó? Bạn có một số hướng dẫn về điều đó?
Siddharth Choudhary

Ngoài ra, máy chủ mùa xuân của tôi đang chạy trên 8080 và angular's đang chạy trên 3000. Bây giờ khi tôi đánh dấu server_url là localhost: 8080 / api / uploadForm, nó nói rằng cors không được phép!
Siddharth Choudhary

byte [] byte = file.getBytes (); nó sẽ cung cấp luồng byte..bạn có thể chuyển đổi nó thành tệp, đối với vấn đề cors bạn có thể tìm giải pháp trong google
Shafeeq Mohammed

5

Trước tiên, bạn cần thiết lập HttpClient trong dự án Angular của bạn.

Mở tệp src / app / app.module.ts, nhập httpClientModule và thêm nó vào mảng nhập của mô-đun như sau:

import { BrowserModule } from '@angular/platform-browser';  
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';  
import { AppComponent } from './app.component';  
import { HttpClientModule } from '@angular/common/http';

@NgModule({  
  declarations: [  
    AppComponent,  
  ],  
  imports: [  
    BrowserModule,  
    AppRoutingModule,  
    HttpClientModule  
  ],  
  providers: [],  
  bootstrap: [AppComponent]  
})  
export class AppModule { }

Tiếp theo, tạo một thành phần:

$ ng generate component home

Tiếp theo, tạo một dịch vụ tải lên:

$ ng generate service upload

Tiếp theo, mở tệp src / app / upload.service.ts như sau:

import { HttpClient, HttpEvent, HttpErrorResponse, HttpEventType } from  '@angular/common/http';  
import { map } from  'rxjs/operators';

@Injectable({  
  providedIn: 'root'  
})  
export class UploadService { 
    SERVER_URL: string = "https://file.io/";  
    constructor(private httpClient: HttpClient) { }
    public upload(formData) {

      return this.httpClient.post<any>(this.SERVER_URL, formData, {  
         reportProgress: true,  
         observe: 'events'  
      });  
   }
}

Tiếp theo, mở tệp src / app / home / home.component.ts và bắt đầu bằng cách thêm các mục nhập sau:

import { Component, OnInit, ViewChild, ElementRef  } from '@angular/core';
import { HttpEventType, HttpErrorResponse } from '@angular/common/http';
import { of } from 'rxjs';  
import { catchError, map } from 'rxjs/operators';  
import { UploadService } from  '../upload.service';

Tiếp theo, xác định các biến fileUpload và tệp và tiêm UploadService như sau:

@Component({  
  selector: 'app-home',  
  templateUrl: './home.component.html',  
  styleUrls: ['./home.component.css']  
})  
export class HomeComponent implements OnInit {
    @ViewChild("fileUpload", {static: false}) fileUpload: ElementRef;files  = [];  
    constructor(private uploadService: UploadService) { }

Tiếp theo, xác định phương thức uploadFile ():

uploadFile(file) {  
    const formData = new FormData();  
    formData.append('file', file.data);  
    file.inProgress = true;  
    this.uploadService.upload(formData).pipe(  
      map(event => {  
        switch (event.type) {  
          case HttpEventType.UploadProgress:  
            file.progress = Math.round(event.loaded * 100 / event.total);  
            break;  
          case HttpEventType.Response:  
            return event;  
        }  
      }),  
      catchError((error: HttpErrorResponse) => {  
        file.inProgress = false;  
        return of(`${file.data.name} upload failed.`);  
      })).subscribe((event: any) => {  
        if (typeof (event) === 'object') {  
          console.log(event.body);  
        }  
      });  
  }

Tiếp theo, xác định phương thức uploadFiles () có thể được sử dụng để tải lên nhiều tệp hình ảnh:

private uploadFiles() {  
    this.fileUpload.nativeElement.value = '';  
    this.files.forEach(file => {  
      this.uploadFile(file);  
    });  
}

Tiếp theo, xác định phương thức onClick ():

onClick() {  
    const fileUpload = this.fileUpload.nativeElement;fileUpload.onchange = () => {  
    for (let index = 0; index < fileUpload.files.length; index++)  
    {  
     const file = fileUpload.files[index];  
     this.files.push({ data: file, inProgress: false, progress: 0});  
    }  
      this.uploadFiles();  
    };  
    fileUpload.click();  
}

Tiếp theo, chúng ta cần tạo mẫu HTML của giao diện người dùng tải lên hình ảnh của chúng tôi. Mở tệp src / app / home / home.component.html và thêm nội dung sau:

       <div style="text-align:center; margin-top: 100px; ">

        <button mat-button color="warn" (click)="onClick()">  
            Upload  
        </button>  
    <input type="file" #fileUpload id="fileUpload" name="fileUpload" multiple="multiple" accept="image/*" style="display:none;" /></div>

Kiểm tra hướng dẫn này và bài viết này


4

Hoàn thành ví dụ về tải lên tệp bằng Angular và nodejs (express)

Mã HTML

            <div class="form-group">
                <label for="file">Choose File</label><br/>
                <input type="file" id="file" (change)="uploadFile($event.target.files)" multiple>
            </div>

Mã thành phần TS

uploadFile(files) {
    console.log('files', files)
        var formData = new FormData();

    for(let i =0; i < files.length; i++){
      formData.append("files", files[i], files[i]['name']);
        }

    this.httpService.httpPost('/fileUpload', formData)
      .subscribe((response) => {
        console.log('response', response)
      },
        (error) => {
      console.log('error in fileupload', error)
       })
  }

Mã nút Js

fileUpload API điều khiển

function start(req, res) {
fileUploadService.fileUpload(req, res)
    .then(fileUploadServiceResponse => {
        res.status(200).send(fileUploadServiceResponse)
    })
    .catch(error => {
        res.status(400).send(error)
    })
}

module.exports.start = start

Dịch vụ tải lên bằng multer

const multer = require('multer') // import library
const moment = require('moment')
const q = require('q')
const _ = require('underscore')
const fs = require('fs')
const dir = './public'

/** Store file on local folder */
let storage = multer.diskStorage({
destination: function (req, file, cb) {
    cb(null, 'public')
},
filename: function (req, file, cb) {
    let date = moment(moment.now()).format('YYYYMMDDHHMMSS')
    cb(null, date + '_' + file.originalname.replace(/-/g, '_').replace(/ /g,     '_'))
}
})

/** Upload files  */
let upload = multer({ storage: storage }).array('files')

/** Exports fileUpload function */
module.exports = {
fileUpload: function (req, res) {
    let deferred = q.defer()

    /** Create dir if not exist */
    if (!fs.existsSync(dir)) {
        fs.mkdirSync(dir)
        console.log(`\n\n ${dir} dose not exist, hence created \n\n`)
    }

    upload(req, res, function (err) {
        if (req && (_.isEmpty(req.files))) {
            deferred.resolve({ status: 200, message: 'File not attached', data: [] })
        } else {
            if (err) {
                deferred.reject({ status: 400, message: 'error', data: err })
            } else {
                deferred.resolve({
                    status: 200,
                    message: 'File attached',
                    filename: _.pluck(req.files,
                        'filename'),
                    data: req.files
                })
            }
        }
    })
    return deferred.promise
}
}

1
httpService đến từ đâu?
James

@James httpService là mô-đun http góc cạnh để thực hiện cuộc gọi http đến máy chủ. Bạn có thể sử dụng bất kỳ dịch vụ http nào bạn muốn.import {HttpClientModule} từ '@ angular / common / http';
Rohit Parte

2

Thử cái này

Tải về

npm install primeng --save

Nhập khẩu

import {FileUploadModule} from 'primeng/primeng';

Html

<p-fileUpload name="myfile[]" url="./upload.php" multiple="multiple"
    accept="image/*" auto="auto"></p-fileUpload>

1
tôi mệt mỏi khi sử dụng ví dụ trên. Nhưng tôi đang nhận được ./upload.php không tìm thấy.
Sandeep Kamath

2
Bạn nên cung cấp URL của mình tại nơi cần tải thay vì upload.php @sandeep kamath
Vignesh

1
@Vignesh cảm ơn bạn đã trả lời. Nhưng tôi thấy rằng tôi không cung cấp thuộc tính url cho tất cả, nó tải tệp, nên là thuộc tính mặc định.
Sandeep Kamath

1
Bạn có thể giải thích làm thế nào chúng ta có thể nhận tệp bằng php nếu chúng ta đang làm theo phương pháp này.
Shaikh Arbaaz

2

Trong góc 7/8/9

Liên kết nguồn

nhập mô tả hình ảnh ở đây

Sử dụng mẫu Bootstrap

<form>
    <div class="form-group">
        <fieldset class="form-group">

            <label>Upload Logo</label>
            {{imageError}}
            <div class="custom-file fileInputProfileWrap">
                <input type="file" (change)="fileChangeEvent($event)" class="fileInputProfile">
                <div class="img-space">

                    <ng-container *ngIf="isImageSaved; else elseTemplate">
                        <img [src]="cardImageBase64" />
                    </ng-container>
                    <ng-template #elseTemplate>

                        <img src="./../../assets/placeholder.png" class="img-responsive">
                    </ng-template>

                </div>

            </div>
        </fieldset>
    </div>
    <a class="btn btn-danger" (click)="removeImage()" *ngIf="isImageSaved">Remove</a>
</form>

Trong lớp thành phần

fileChangeEvent(fileInput: any) {
    this.imageError = null;
    if (fileInput.target.files && fileInput.target.files[0]) {
        // Size Filter Bytes
        const max_size = 20971520;
        const allowed_types = ['image/png', 'image/jpeg'];
        const max_height = 15200;
        const max_width = 25600;

        if (fileInput.target.files[0].size > max_size) {
            this.imageError =
                'Maximum size allowed is ' + max_size / 1000 + 'Mb';

            return false;
        }

        if (!_.includes(allowed_types, fileInput.target.files[0].type)) {
            this.imageError = 'Only Images are allowed ( JPG | PNG )';
            return false;
        }
        const reader = new FileReader();
        reader.onload = (e: any) => {
            const image = new Image();
            image.src = e.target.result;
            image.onload = rs => {
                const img_height = rs.currentTarget['height'];
                const img_width = rs.currentTarget['width'];

                console.log(img_height, img_width);


                if (img_height > max_height && img_width > max_width) {
                    this.imageError =
                        'Maximum dimentions allowed ' +
                        max_height +
                        '*' +
                        max_width +
                        'px';
                    return false;
                } else {
                    const imgBase64Path = e.target.result;
                    this.cardImageBase64 = imgBase64Path;
                    this.isImageSaved = true;
                    // this.previewImagePath = imgBase64Path;
                }
            };
        };

        reader.readAsDataURL(fileInput.target.files[0]);
    }
}

removeImage() {
    this.cardImageBase64 = null;
    this.isImageSaved = false;
}
Khi sử dụng trang web của chúng tôi, bạn xác nhận rằng bạn đã đọc và hiểu Chính sách cookieChính sách bảo mật của chúng tôi.
Licensed under cc by-sa 3.0 with attribution required.