使用(AngularJS 2)和ASP.net MVC Web API进行文件上载

前端之家收集整理的这篇文章主要介绍了使用(AngularJS 2)和ASP.net MVC Web API进行文件上载前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试使用AngularJS 2 rc5和asp.net mvc上传文件.
我无法找到一种方法上传angularjs 2和asp.net mvc中的文件.
最后

这项工作对我而言

upload.service.ts文件

import {Injectable}from '@angular/core';
import {Observable} from 'rxjs/Rx';
@Injectable()
export class UploadService {
progress$: any;
progress: any;
progressObserver: any;
constructor() {
    this.progress$= Observable.create(observer => {
        this.progressObserver = observer
    }).share();
}

 makeFileRequest(url: string,params: string[],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.upload.onprogress = (event) => {
            this.progress = Math.round(event.loaded / event.total * 100);

            this.progressObserver.next(this.progress);
        };

        xhr.open('POST',url,true);
        var serverFileName = xhr.send(formData);
        return serverFileName;
    });
}
}

和appcomponnet.ts文件

import {Component } from 'angular2/core';
import {UploadService} from './app.service';

@Component({
selector: 'my-app',template: `
  <div>
    <input type="file" (change)="onChange($event)"/>
  </div>
`,providers: [ UploadService ]
 })
  export class AppComponent {
   picName: string;
   constructor(private service:UploadService) {
   this.service.progress$.subscribe(
     data => {
      console.log('progress = '+data);
      });
    }

     onChange(event) {
       console.log('onChange');
         var files = event.srcElement.files;
        console.log(files);
           this.service.makeFileRequest('http://localhost:8182/upload',[],files).subscribe(() => {
        console.log('sent');
        this.picName = fileName;
     });
     }
      }

和行动方法

public HttpResponseMessage UploadFile()
    {
        var file = HttpContext.Current.Request.Files[0];


        if (file.ContentLength > 0)
        {
            var fileName = Path.GetFileName(file.FileName);
            var path = Path.Combine(Server.MapPath("~/App_Data/uploads"),fileName);
            file.SaveAs(path);
             var content = JsonConvert.SerializeObject(serverFileName,new JsonSerializerSettings
        {
            ContractResolver = new CamelCasePropertyNamesContractResolver()
        });

        var response = Request.CreateResponse(HttpStatusCode.OK);
        response.Content = new StringContent(content,Encoding.UTF8,"application/json");
        return response;
     }
原文链接:https://www.f2er.com/angularjs/143358.html

猜你在找的Angularjs相关文章