Açısal Dosya Yükleme


193

Angular ile yeni başlayan biriyim, Angular 5 Dosya yükleme parçasının nasıl oluşturulacağını bilmek istiyorum , herhangi bir öğretici veya doktor bulmaya çalışıyorum, ancak hiçbir yerde hiçbir şey göremiyorum. Bunun hakkında bir fikrin var mı? Ve ng4 dosyalarını denedim ama Angular 5 için çalışmıyor


2
öyleyse u sürükle bırak ya da basit Choose Filebtn yükleme mi istiyorsunuz ? Bdw her iki durumda da u sadece FormData
Dhyey

4
Primeng'e bir bakın, bir süredir kullanıyorum ve açısal v5 ile çalışıyor. primefaces.org/primeng/#/fileupload
Bünyamin Coşkuner

JSON'u istemciye yüklemesi gereken kişiler için şu soruya göz
AnthonyW

Yanıtlar:


429

İşte api'ye dosya yüklemek için çalışan bir örnek:

1. Adım: HTML Şablonu (file-upload.component.html)

Türün basit giriş etiketini tanımlayın file. (change)Seçim dosyalarını işlemek için -event işlevine bir işlev ekleyin .

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

Adım 2: TypeScript'te Yükleme İşleme (file-upload.component.ts)

Seçilen dosya için varsayılan bir değişken tanımlayın.

fileToUpload: File = null;

(change)Dosya giriş etiketinizden kaçınılmaz olarak kullandığınız işlev oluşturun :

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

Çok dosyalı seçimi işlemek istiyorsanız, bu dosyalar dizisini yineleyebilirsiniz.

Şimdi size file-upload.service öğesini çağırarak dosya yükleme işlevi oluşturun.

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

Adım 3: Dosya Yükleme Hizmeti (file-upload.service.ts)

POST yöntemi ile bir dosya yükleyerek kullanmalısınız FormData, çünkü http isteğine dosya ekleyebilirsiniz.

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

Yani, işimde her gün kullandığım çok basit bir çalışma örneği.


6
@Katie çoklu doldurmayı etkinleştirdiniz mi?
Gregor Doroschenko

2
@GregorDoroschenko Dosya hakkında ek bilgi içeren bir model kullanmaya çalışıyordum ve işe almak için bunu yapmak zorunda kaldım: const invFormData: FormData = new FormData(); invFormData.append('invoiceAttachment', invoiceAttachment, invoiceAttachment.name); invFormData.append('invoiceInfo', JSON.stringify(invoiceInfo)); Denetleyicinin iki karşılık gelen parametresi var, ancak denetleyicideki JSON'u ayrıştırmak zorunda kaldım. Core 2 denetleyicim modeli parametrede otomatik olarak almayacaktı. Özgün tasarımım bir dosya özelliğine sahip bir modeldi, ama işe yaramadım
Papa Stahl

1
@GregorDoroschenko Bu kodu denedimcreateContrat(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 Ve benim için çalışmıyor. Ben ws sonrası:Content-Disposition: form-data; name="fileKey"; filename="file.docx" Content-Type: application/octet-stream <file>
OnnaB

1
@OnnaB Dosya ve diğer özellikler için FormData kullanıyorsanız, dosya ve diğer özellikleri FormData olarak ayrıştırmalısınız. FormData ve gövdeyi aynı anda kullanamazsınız.
Gregor Doroschenko

25

Bu şekilde projedeki web API'sına yükleme dosyası uyguluyorum.

Kimin için endişe duyuyorum.

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

Adım adım

ASP.NET Web API'sı

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

HTML formu

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

API kullanmak için TS dosyası

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

Hizmet 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
Üstbilgileri gönderme şekliniz nedir?
Şalom Dahan

14

Çok kolay ve en hızlı yöntem ng2-dosya-upload kullanmaktır .

Ng2-file-upload dosyasını npm ile yükleyin. npm i ng2-file-upload --save

İlk önce modülünüzü içe aktarın.

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

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

İşaretleme:

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

Bileşeninizde ts:

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

Bunun en basit kullanımı. Tüm gücünü bilmek için demoya bakınız


4
resim yüklendiğinde nasıl yanıt alınır? yanıt ne olacak, belgelerde bu kısım eksik.
Muhammed Şahzad

7

Açısal 5.2.11 kullanıyorum, Gregor Doroschenko tarafından sağlanan çözümü seviyorum, ancak yüklenen dosyanın sıfır bayt olduğunu fark ettim, benim için işe almak için küçük bir değişiklik yapmak zorunda kaldım.

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

Aşağıdaki satırlar (formData) benim için çalışmadı.

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

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


6

Tamam, bu iş parçacığı google'ın ilk sonuçları arasında göründüğü ve aynı soruya sahip diğer kullanıcılar için, trueboroda'nın işaret ettiği gibi tekerleği yeniden yerleştirmek zorunda değilsiniz, bu yükleme işlemini basitleştiren ng2 dosya yükleme kütüphanesi açısal 6 ve 7 ile dosya yapmanız gereken tek şey:

En son Açısal CLI'yı yükleyin

yarn add global @angular/cli

Ardından uyumluluk sorunu için rx-compat'u yükleyin

npm install rxjs-compat --save

Ng2-file-upload yükleyin

npm install ng2-file-upload --save

Modülünüzdeki FileSelectDirective Yönergesini içe aktarın.

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

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

Bileşeninizde

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

export class AppComponent implements OnInit {

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

şablon

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

Daha iyi anlamak için bu bağlantıyı kontrol edebilirsiniz: Açısal 6/7 ile Dosya Yükleme


1
Bağlantı için teşekkürler. Yükleme masaüstünde iyi çalışıyor ancak hayatım boyunca iOS gibi mobil cihazlarda çalışmak için yükleme yapamıyorum. Film rulosundan bir dosya seçebilirim, ancak yüklediğimde her zaman başarısız olur. Herhangi bir fikir? FYI, bunu yüklü bir uygulamada değil, mobil safaride çalıştırıyor.
ScottN

1
Merhaba @ScottN ve hoş geldiniz, belki sorun kullandığınız tarayıcıdan geliyor? başka biriyle test ettin mi?
Mohamed Makkaoui

1
Merhaba @Mohamed Makkaoui cevap için teşekkürler. İOS'ta Chrome'da denedim ve yine aynı sonuç. Sunucuya gönderirken bunun bir başlık sorunu olup olmadığını merak ediyorum? NET ve NOT AWS FYI yazılmış özel bir WebAPI kullanıyorum.
ScottN

1
Merhaba @ScottN Bu bağlantı developers.google.com/web/tools/chrome-devtools/… kullanarak kodunuzda hata ayıklama yapana ve hangi hata mesajını aldığınızı görene kadar bir başlık sorunu olup olmadığını bilemeyiz .
Mohamed Makkaoui

6

Şahsen ben bu kullanarak yapıyorum NGX-malzeme-file-girişini ön ucu için ve Firebase arka uç için. Cloud Firestore ile birleştirilmiş arka uç için Firebase için daha hassas C yüksek sesle Depolama . Dosyayı 20 MB'den büyük olmayacak şekilde sınırlayan ve yalnızca belirli dosya uzantılarını kabul eden bir örneğin altında. Yüklenen dosyalara bağlantıları saklamak için Cloud Firestore'u da kullanıyorum , ancak bunu atlayabilirsiniz.

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 (boyut doğrulayıcı bölüm)

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 (dosya yükleyici bölümü)

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

storage.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
Harika görünüyorsunuz, ancak toString()contactForm bildiriminde neden ihtiyacınız var ?
trungk18

1
@ trungk18 bir kez daha kontrol edin ve haklısınız, toString()cevabımı düzenledi. Bu yorumu okuyanlar için fileUploader, contact.component.ts sonunda vardı ])].toString()}). Şimdi basitçe var: ])]}).
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. ts Dosyası
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. Arka Uç Baharı (java dosyası)

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

C sürücüsünde bir "temp" klasörü oluşturmak zorundayız, o zaman bu kod Json'u konsolda yazdırır ve yüklenen dosyayı oluşturulan klasöre kaydeder


Bu dosyayı nasıl alırız? Bununla ilgili bir rehberlik var mı?
Siddharth Choudhary

Ayrıca benim bahar sunucu 8080 üzerinde çalışıyor ve açısal en 3000 üzerinde çalışıyor. Şimdi ben server_url localhost olarak işaretlemek: 8080 / api / uploadForm cors izin verilmiyor diyor!
Siddharth Choudhary

byte [] bytes = file.getBytes (); bayt akışını verecektir .. bunu dosyaya dönüştürebilirsiniz, cors sorunu için google'da çözüm bulabilirsiniz
Shafeeq Mohammed

5

İlk olarak, Açısal projenizde HttpClient'i kurmanız gerekir.

Src / app / app.module.ts dosyasını açın, HttpClientModule dosyasını içe aktarın ve aşağıdaki gibi modülün import dizisine ekleyin:

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

Ardından, bir bileşen oluşturun:

$ ng generate component home

Ardından, bir yükleme hizmeti oluşturun:

$ ng generate service upload

Ardından, src / app / upload.service.ts dosyasını aşağıdaki gibi açın:

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

Ardından, src / app / home / home.component.ts dosyasını açın ve aşağıdaki içe aktarmaları ekleyerek başlayın:

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

Ardından, fileUpload ve dosya değişkenlerini tanımlayın ve UploadService'i aşağıdaki gibi enjekte edin:

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

Ardından, uploadFile () yöntemini tanımlayın:

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

Ardından, birden fazla resim dosyasını yüklemek için kullanılabilecek uploadFiles () yöntemini tanımlayın:

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

Ardından, onClick () yöntemini tanımlayın:

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

Ardından, resim yükleme arayüzümüzün HTML şablonunu oluşturmamız gerekiyor. Src / app / home / home.component.html dosyasını açın ve aşağıdaki içeriği ekleyin:

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

Şuna bak öğretici ve bu yazı


4

Angular ve nodejs (express) kullanarak tam Dosya yükleme örneği

HTML Kodu

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

TS Bileşen Kodu

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

Düğüm Js kodu

fileUpload API denetleyicisi

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

Multer kullanarak servis yükle

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 nereden geliyor?
James

@James httpService sunucuya http çağrısı yapmak için açısal http modülüdür. İstediğiniz herhangi bir http hizmetini '@ angular / common / http' adresinden {HttpClientModule} kullanabilirsiniz;
Rohit Parte

2

Bunu dene

Yüklemek

npm install primeng --save

İthalat

import {FileUploadModule} from 'primeng/primeng';

Html

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

1
Yukarıdaki örnek kullanarak yorgun. Ama ben ./upload.php bulunamadı.
Sandeep Kamath

2
URL'nizi upload.php @sandeep kamath yerine yüklenmesi gereken yere sağlamalısınız
Vignesh

1
@Vignesh Cevabınız için teşekkürler. Ama ben dosyayı yüklemek hiç url özniteliği vermiyorum bulundu, varsayılan bir olmalıdır.
Sandeep Kamath

1
Eğer u biz bu yöntemde yapıyoruz php dosyayı nasıl alabilirim açıklayabilir misiniz.
Shaikh Arbaaz

2

In açısal 7/8/9

Kaynak Bağlantı

resim açıklamasını buraya girin

Bootstrap Formunu Kullanma

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

In Bileşen Sınıf

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;
}
Sitemizi kullandığınızda şunları okuyup anladığınızı kabul etmiş olursunuz: Çerez Politikası ve Gizlilik Politikası.
Licensed under cc by-sa 3.0 with attribution required.