2017-04-26 147 views
1

我是堆棧溢出以及angular2中的新手。我目前正在學習如何使用angular2在應用程序內的本地文件夾中上傳圖像。我無法理解如何將圖像保存在本地文件夾中。我已經閱讀了堆棧溢出的許多答案,但他們(幾乎)使用angularjs而不是angular2。任何人都可以幫助我如何使用angular2和nodejs上傳和保存本地文件夾中的圖像。我只是HTML代碼。如何在本地文件夾中使用angular2保存圖像

<div class="form-group"> 
<label for="single">single</label> 
<input type="file" class="form-control" name="single" 
/></div> 

我已經度過了整個夜晚,但都是徒勞的。可有人請給我簡單的教程僅通過顯示如何在本地文件夾中使用保存角2

+1

你見過這個:http://stackoverflow.com/questions/41547945/write-to-a-local-file-using-angular2-typescript-locally – DeborahK

+0

我完成了它。使用django作爲後端。 – maadi

回答

0

我想你的意思是如何在服務器文件夾時,您選擇要上傳的文件已經被從本地選擇保存圖像,因爲夾。對?你提到了NodeJS,所以你想把它發送到NodeJS服務器,然後保存它。

import { Component, OnInit, OnDestroy, ChangeDetectorRef } from '@angular/core'; 

... 

fileToUpload: File; 

constructor(private imageService: ImageService, 
      private changeDetectorRef: ChangeDetectorRef) { } 

fileChange(input) { 
    this.readFiles(input.files); 
} 

readFile(file, reader, callback){ 
    reader.onload =() => { 
    callback(reader.result); 
    this.fileToUpload = reader.result; 
    this.onImageUpload(); 
    } 
    reader.readAsDataURL(file); 
} 

readFiles(files, index=0){ 
    let reader = new FileReader(); 
    if (index in files) { 
    this.readFile(files[index], reader, (result) => { 
     var img = document.createElement("img"); 
     img.src = result; 

     this.readFiles(files, index+1); 
    }); 
    } else { 
    this.changeDetectorRef.detectChanges(); 
    } 
} 

onImageUpload() { 
    this.imageService.updateImage(this.fileToUpload).subscribe(
    (photo: Photo) => { 
     if (photo) { ... } 
    } 
); 
} 

然後在服務你運行像這樣(我在考慮JPG):

updateImage(fileToUpload) { 
    const body = JSON.stringify(fileToUpload); 
    const headers = new Headers({ 'Content-Type': 'image/jpeg' }); 

    return this.http.patch(this.config.host + '/photo/', body, { headers: headers }) 
    .map((response: Response) => { 

     console.log(response.json().data); 
    }) 
    .catch((error: Response) => { 
     console.log("Error: ", error); 
     return Observable.throw(error.json()); 
    }); 
} 

我希望這有助於你的東西開始。

相關問題