angular2^ typescript merging files and JSON data to the server (1. Client processing)

Source: Internet
Author: User
Tags export class

First, the following framework basic process (Web > WebService "front-end Architecture") > (nodejs "Data Broker") > (API "Background interface")

--web (HTML angular framework)

--webservice (the service file written in angular, where it was possible to use the "ng2-file-upload" plug-in file + parameters to merge the submission, but request a unified commit in my project, so using a third-party plug-in here is less appropriate

So I wrote XMLHttpRequest for form data Merge commit, angular HTTP post is not possible, so use XMLHttpRequest)

--nodejs (Nodejs do webserver, upload files from the browser to the backend server, Nodejs layer just do a data transfer + parameter encryption = =, Nodejs required)

--api (This is a brief introduction, PHP java. net Nodejs = = All can be only unified good request parameters and Access parameters OK)

"" "This reference article has the following (May angular2 at present domestic use is not particularly skilled, in the domestic search answer can not find, had to bite the bullet Fq read English" English is not good only with translation software: (")

GitHub Stack Overflow

Https://github.com/asafdav/ng-csv

Https://stackoverflow.com/questions/37174759/how-do-you-post-a-formdata-object-in-angular-2

Https://stackoverflow.com/questions/36352405/file-upload-with-angular2-to-rest-api

Https://stackoverflow.com/questions/32423348/angular-post-uploaded-file

This article mainly introduces the front end (Web > WebService "front-end architecture") Data merge submission, the next article mainly introduces the back-end data Merge submission

1. Component

-----1. HTML authoring

<type= "File"  (change)= "Filechange ($event)"/>

-----2. Ts

Import {Component, OnInit} from ' @angular/core '; import {Router} from"@angular/router";//introducing a public service submissionImport {apiservice, editalbumparam} from "App/service/api.service"; @Component ({selector:' App-albumedit ', Templateurl:'./albumedit.component.html ', Styleurls: ['./albumedit.component.css ']}) Export class Albumeditcomponent implements OnInit {private albumtypedata;  Private file:file[]; Private Editalbumparam:editalbumparam=NewEditalbumparam (); Constructor (private api:apiservice, Private Router:router) {} ngoninit () {}//main implementation methods accept the file when it is modifiedFilechange (event) { This. File =Event.srcElement.files; }  //Submit an eventSubmit () {//to submit parameters and files uniformly     This. Api.editalbum ( This. Editalbumparam, This. file). Subscribe (res = {      if(Res. state = = 0) {alert ("Added successfully! ");  }    }); }}

2. Api.service.ts (all component the required path for API requests)

Import {injectable} from ' @angular/core '; import {Http, Headers, requestoptions} from"@angular/http"; import {Observable} from"Rxjs/rx"; Import"Rxjs/rx"; import {Uploadservice} from"App/service/upload.service"; @Injectable () Export class Apiservice {constructor (private http:http, Private Upload:uploadservice) {} Priva Te Post (data:paramdata): Observable<ResponseInfo>{Let host= "/serverh5"; Let Bodyobj={cmd:data.cmd, param:JSON.stringify (Data.param)}; Let body= ' cmd=${data.cmd}&param=${json.stringify (Data.param)} '; Console.log ("Send infomation:" +body); When a file stream is found, a form data merge commit is invoked to invoke the public upload serviceif(data.file) {return  This. Upload.makefilerequest (Host, Bodyobj, Data.file). Map (res =res as Responseinfo). Filter ((res:responseinfo)={console.log (res); if(Res. state = = 1) {alert (res.                    MSG); }                    returnRes. state = = 0;        }); } Else{Let myheaders=NewHeaders (); Myheaders.append (' Content-type ', ' application/x-www-form-urlencoded '); return  This. Http.post (host, body, {headers:myheaders}) . Map (Res=Res.json () as Responseinfo). Filter ((res:responseinfo)={console.log (res); if(Res. state = = 1) {alert (res.                    MSG); }                    returnRes. state = = 0;        }); }    }    //LoginLogin (param:loginparam) {return  This. Post (NewParamdata ("Loginbysms", param)); }    //Send Verification CodeSendcode (param:loginparam) {return  This. Post (NewParamdata ("Smsulogin", param)); }    //Get album TypeGetalbumtype () {return  This. Post (NewParamdata ("Albumtype", {})); }    //Get album listgetalbumlist (param:albumlistparam) {return  This. Post (NewParamdata ("Myalbumlist", param)); }    //Add Edit albumEditalbum (param:editalbumparam, file?): file[]) {        return  This. Post (NewParamdata ("Useraddalbum", param, file)); }}export class Paramdata {/**     *     */Constructor (public cmd:string, public param:object, public file?: file[]) {}}export class Responseinfo {/**    *    */Constructor ( public state?: number, public Msg?: String, public Value?: Any) {}}export class Loginparam {public Phone?: number; Public Code?: number;}    Export class Albumlistparam {public pageindex:number;    Public pagesize:number;    Public guid:string; Public CType?: string;}    Export class Editalbumparam {public name:string;    Public guid:string;    Public introduce:string;    Public id:number;    Public price:string;    Public ctypeid:string;    Public rid:number; public rtype:number;}

3. Written by upload Service.ts

Import {injectable} from ' @angular/core '; import {Observable} from' Rxjs/rx '; Import' Rxjs/add/operator/share '; @Injectable () export class Uploadservice {[x:string]: any; Constructor () { This. progress$ = OBSERVABLE.CREATE (Observer = {             This. Progressobserver =Observer}).    Share (); } public Makefilerequest (url:string, Postdata:any, files:file[]): Observable<Response> {        returnOBSERVABLE.CREATE (Observer ={Let Formdata:formdata=NewFormData (), Xhr:xmlhttprequest=NewXMLHttpRequest (); //formData file stream append             for(Let i = 0; i < files.length; i++) {formdata.append ("Uploads[]", Files[i], files[i].name); }            //formData parameter Append            if(PostData!== "" && postdata!== undefined && postdata!==NULL) {                 for(varPropertyinchpostdata) {                    if(Postdata.hasownproperty) {Formdata.append (property, Postdata[property]); } }} xhr.onreadystatechange= () + = {                if(Xhr.readystate = = 4) {                    if(Xhr.status = = 200) {observer.next (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);        Xhr.send (FormData);    }); }}

The next article mainly introduces the back-end data Merge submission

If there is a wrong place to write, please point out and suggest, thank you:)

angular2^ typescript merging files and JSON data to the server (1. Client processing)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.