实施ng2-file-upload

时间:2016-06-04 00:46:08

标签: javascript angular

我正在尝试探索尝试使用ng2-file-upload但是在理解如何实现它时遇到一些麻烦,因为自述文件非常稀疏。是否有更多细节可以帮助我开始这个。我正在尝试创建一个演示应用程序来上传图像并将其作为开始保存在服务器中。

我在这里查看了演示页http://valor-software.com/ng2-file-upload/

如果有人可以提供帮助,可以提出一些问题。

  1. 对于打字稿页面,const URL指的是API,在示例中,它是“https://evening-anchorage-3159.herokuapp.com/api/”。

  2. demo / component / file-upload目录中有一个file-catcher.js文件。任何人都可以解释这是什么以及是否需要它?看起来像一个快递应用程序。

  3. 或者欢迎任何其他实现图像上传功能的方式。感谢。

2 个答案:

答案 0 :(得分:3)

您是否尝试过没有第三方上传?

服务:

export class WebService {

constructor(private http:Http) {

}

 public makeFileRequest(files:File[]):Observable<any> {
   return Observable.create(observer => {
       let formData:FormData = new FormData(),
           xhr:XMLHttpRequest = new XMLHttpRequest();

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

       xhr.onreadystatechange = () => {
           if (xhr.readyState === 4) {
               if (xhr.status === 200) {
                   observer.next(JSON.parse(xhr.response));
                   observer.complete();
               } else {
                   observer.error(xhr.response);
               }
           }
       };

       xhr.open('POST', CONSTS.baseURL + "/api/uploadFile", true);
       xhr.send(formData);
   });
}

在组件中:

import {Component, NgZone} from "@angular/core";
import {WebService} from "../services/services";
@Component({
 templateUrl:"./your.template.html"
})

 export class YourComponent{
 public fileEvent=null;
 private fileName;
 public validTypes = ["application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/msword","application/pdf"];
 private errorFileType:boolean = false;
 private fileUploadedSuccessFully:boolean = false;
 private uploading:boolean = false;
 public uploadingMessage = "Gönder";

 constructor(public webService:WebService,public zone:NgZone){

 }
 uploadFile(event){
   if(this.validTypes.indexOf(event.target.files[0].type)!=-1){
       this.fileEvent = event;
       this.fileName = event.target.files[0].name;
       this.errorFileType = false;
   }
   else {
       this.errorFileType = true;
   }
 }
   upload(){
   this.uploading = true;
   this.uploadingMessage = "Yükleniyor";

   this.webService.makeFileRequest(this.fileEvent.target.files).subscribe((data)=>this.zone.run(()=>{
       this.fileUploadedSuccessFully = true;
       this.uploadingMessage = "Yüklendi!";
   }));
}

在html模板中:

 <input type="file" (change)="uploadFile($event)">
 <span (click)="uploading==false?upload():null" [ngClass]="{'upload-disable': uploading==true}">{{uploadingMessage}}</span>

答案 1 :(得分:1)

按顺序回答您的问题

1)Const URL,https://evening-anchorage-3159.herokuapp.com指应用程序运行的BASE_URL,/ api指的是需要为文件uplaoding调用的路径。因此,在您的应用中,您必须包含BASE_URL,然后使用/ api上传文件。

2)File-catcher.js文件是使用multer包实际在Express服务器上执行上传的最重要文件。如果您不使用快速服务器,则必须在服务器中包含multer软件包以上载文件。 我建议您阅读this tutorialmulter以便更好地理解和使用。

相关问题