Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

angular - File Upload using (AngularJS 2) and ASP.net MVC Web API

I'm trying to upload a file with AngularJS 2 rc5 and asp.net mvc. I cant find a way to upload file in angularjs 2 and asp.net mvc.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

finally


solution

this work for me

upload.service.ts file

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

and appcomponnet.ts file

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

and action method

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...