如何在角度2中发布带有图像的表单进行上传

时间:2017-07-11 08:50:26

标签: angular angular2-template angular2-forms

注意:  我已经在使用.net web api,它与邮递员一起工作正常。 像:

public HttpResponseMessage FormPost()
            {
    string member_f_name = HttpContext.Current.Request.Form["member_name"];
    if (HttpContext.Current.Request.Files.Count > 0)
                    {

                        myfiles = HttpContext.Current.Request.Files[0];
                        if (myfiles == null)
                            retmsg = "Comment Post Successfully.";
                        else
                        {
                            if (myfiles.ContentLength > 0)
                                retmsg = "Image Uploaded successfully.";
                            else
                                retmsg = "Comment Post Successfully.";
                        }
                    }
}

我只想用文本框文本发布文件(图像)。 使用相同的api代码。 我已经使用了两个单独的角度代码。 1.for file upload(但是文件更改时上传文件) 2.一个用于提交数据,点击提交按钮。

用于文件上传的代码Snippt。

fileChange(event) {
        debugger;

    let fileList: FileList = event.target.files;
    if(fileList.length > 0) {
        let file: File = fileList[0];
        let formData:FormData = new FormData();
        formData.append('file', file, file.name);
        let headers = new Headers({'Access-Control-Allow-Origin': '*'} );
        headers.append('enctype', 'multipart/form-data');  
        headers.append('Accept', 'application/json');  
        let method="post";
        let options = new RequestOptions({ headers: headers }); 
        let apiUrl1 = "http://local:port/api/Controller/Action";  
        this.http.post(apiUrl1, formData, options)  
       .map(res => res.json())  
        .catch(error => Observable.throw(error))  
        .subscribe(  
        data => console.log('success'),  
        error => console.log(error)  
        )  


    }
}

另一个用表单提交所有数据。

submitForm(myForm:NgForm) {
  debugger;

  var objFormData = new FormData();
                for (var key in myForm.value)
                    objFormData.append(key, myForm.value[key]);
                  let headers = new Headers({'Access-Control-Allow-Origin': '*'} );
        headers.append('enctype', 'multipart/form-data');  
        headers.append('Accept', 'application/json');  
          let options = new RequestOptions({ headers: headers }); 
// this.adminRegister.register(objFormData);
 let apiUrl1 = "http://localhost:port/api/Controller/Action";  
   this.http.post(apiUrl1, objFormData, options)  
       .map(res => res.json())  
    .catch(error => Observable.throw(error))  
    .subscribe(  
    data => console.log('success'),  
    error => console.log(error)  
    )  

 }

2 个答案:

答案 0 :(得分:0)

<div ng2FileDrop  [uploader]="uploader">
<input type="file" ng2FileSelect [uploader]="uploader" multiple />

在您的组件中

import { Component, OnInit } from '@angular/core';
import { FileUploader } from 'ng2-file-upload';
@Component({
  selector: 'app-files',
  templateUrl: 'files.component.html',
  styleUrls: ['files.component.css'],
})
export class FilesComponent implements OnInit {
  uploader = new FileUploader({url: `YOUR URL`});
}

答案 1 :(得分:0)

public postImage(url: string) {
  let formData: FormData = new FormData();
  formData.append('image', image);
  formData.append('text', 'hi this is my text');

  this.postWithXhr("url"
}   

 public postWithXhr(url, formdata: FormData, headers?: Header[]) {       
        if (!headers) {
            headers = [];
        }

        if (headers['Access-Control-Allow-Origin']) {
            headers.push({ header: 'Access-Control-Allow-Origin', value: '*' });
        }

        return Observable.create(observer => {
            const xhr: XMLHttpRequest = new XMLHttpRequest();
            xhr.onreadystatechange = () => {
                if (xhr.readyState === 4) {
                    if (xhr.status === 200) {
                        observer.next({ response: xhr.response, status: xhr.status });
                        observer.complete();
                    } else {
                        observer.error({ response: xhr.response, status: xhr.status });
                    }
                }
            };

            xhr.open('POST', url, true);

            if (headers) {
                for (const header of headers) {
                    xhr.setRequestHeader(header.header, header.value);
                }
            }
            xhr.send(formdata);
        });
    }

Hi think this will help you.