Search code examples
c#angularhttppostedfilebasedataform

Send DataForm to server with an object the dataForm is null


I try to send dataForm to the server with an object. the object contains other things:

public class versionModel
{
    public string productName { get; set; }
    public string versionNumber { get; set; }
    public string[] features { get; set; }
    public HttpPostedFileBase file { get; set; }
}

I send it from angular 2 service, this is the component that creates the upload and saves it :

upload() 
{
    let inputEl: HTMLInputElement = this.inputEl.nativeElement;
    let fileCount: number = inputEl.files.length;
    let formData = new FormData();
    if (fileCount > 0) { 
        for (let i = 0; i < fileCount; i++) {
            formData.append('file[]', inputEl.files.item(i));
        }
        this.service.upload(formData).subscribe(x => this.me = x);
        this.formData2.emit(formData.getAll('file[]'));

    }
}

this is the model in client side:

export class AddVersion 
{
    constructor(public productName: string, public versionNumber: string, public features: string[], public file: FormData) {
        this.productName = productName;
        this.versionNumber = versionNumber;
        this.features = features;
       this.file = file;
    }
}

this is server side:

[HttpPost]
public ActionResult AddVersion(versionModel version)
{
    ServiceReference1.ProductsServiceClient psc = new ServiceReference1.ProductsServiceClient();

   var res= psc.AddVersion(new ServiceReference1.AddVersionModel()
    {
        productName = version.productName,
        versionNumber = version.versionNumber,
        features = version.features,
        file =version.file.InputStream
   });
    return Json(res, JsonRequestBehavior.AllowGet);
}

but in the server I get all the information except the file, I get null.


Solution

  • I haven't tried to exactly what you are doing, but I did encounter a similar result when trying to perform a File Upload via an MVC form. The file was always null.

    As it turns out, the issue was that the Form had to have the declaration to say that it was a Multi-Part upload

    Eg:

    <form id="Form1" method="post" encType="multipart/form-data" runat="server">
    

    The encType was required for me.

    I think in your angular class, you should add the encType header.

    headers.append('Content-Type', 'multipart/form-data');
    

    I found the following solution: at this page File Upload In Angular?

    <input type="file" (change)="fileChange($event)" placeholder="Upload file" accept=".pdf,.doc,.docx">
    
    fileChange(event) {
        let fileList: FileList = event.target.files;
        if(fileList.length > 0) {
            let file: File = fileList[0];
            let formData:FormData = new FormData();
            formData.append('uploadFile', file, file.name);
            let headers = new Headers();
            /** No need to include Content-Type in Angular 4 */
            headers.append('Content-Type', 'multipart/form-data');
            headers.append('Accept', 'application/json');
            let options = new RequestOptions({ headers: headers });
            this.http.post(`${this.apiEndPoint}`, formData, options)
                .map(res => res.json())
                .catch(error => Observable.throw(error))
                .subscribe(
                    data => console.log('success'),
                    error => console.log(error)
                )
        }
    }
    

    Alas I am not an angular developer, but I am reasonably sure it is the multi-part header you are missing that is causing the issue.