2017-04-27 73 views
1

例如,我在src文件夾下創建了一個名爲'upload'的文件夾。Angular 2 - 如何上傳文件並存儲在本地文件夾中

HTML文件:

<div> 
    <input type="file" id="photo" (change)="onChange($event)" /> 
</div> 
<div class="col-md-6 mb-4 mt-3"> 
    <button (click)="upload()" class="btn btn-primary w-100">Upload Picture</button> 
</div> 

上載文件modal.component.ts

import { Http, Response } from '@angular/http'; 
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; 
import "rxjs/add/operator/do"; 
import "rxjs/add/operator/map"; 
const uploadURL = '/upload'; 

@Component({ 

selector: 'upload-modal', 
templateUrl: './upload-modal.component.html', 
styleUrls: ['./upload-modal.component.css'] 
}) 
export class UploadModalComponent { 
displayMessage: string = ''; 
constructor(public activeModal: NgbActiveModal, private http: Http, private el: ElementRef) { } 
setDisplayMessage(msg: string) { 
    this.displayMessage = msg; 
} 

upload() { 
    this.activeModal.dismiss('Cross click'); 
} 

onChange(event) { 
let inputEl: HTMLInputElement = this.el.nativeElement.querySelector('#photo'); 

let fileCount: number = inputEl.files.length; 

let formData = new FormData(); 

if (fileCount > 0) { // a file was selected 

    formData.append('photo', inputEl.files.item(0)); 

    this.http 
    .post(uploadURL, formData).map((res: Response) => res.json()).subscribe(
    // map the success function and alert the response 
    (success) => { 
     alert("success"); 
    }, 
    (error) => alert("error")); 
    } 

    } 
} 

當我點擊上傳按鈕,我發現在控制檯日誌此錯誤= http://localhost:3000/upload 404(未找到)
我想這必須與路由。任何人都有經驗?

回答

0

希望這有助於:完整的代碼。

你需要運行這個CMD:npm i ng2-file-upload --save

代碼:https://github.com/valor-software/ng2-file-upload

演示:http://valor-software.com/ng2-file-upload/

+0

感謝您的回答,我不喜歡使用第三方。 :) – weikian

+0

[https://ciphertrick.com/2016/10/24/file-upload-with-angular2-nodejs/](https://ciphertrick.com/2016/10/24/file-upload-with- angular2-nodejs /)檢查這不是第三方 – Cruzer

+0

@weikian,下載怎麼辦?有沒有辦法打開目錄彈出4角度顯示保存對話框? – Sagar

相關問題