简体   繁体   中英

Upload file with Angular2

I was following a tutorial here , on how to upload files with Angular2. However, i when i try implementing the code into my project, the result in my console is just the page html contents instead of the JSON response im suppose to be sending via my POST request on my back end ( asp.net core ). Under the networking tab it seems to making the POST to the correct address, so i don't know why I'm getting an html document instead of my response data. Anyone know why?

upload.html

<h2>Upload</h2>
<input type="file" (change)="fileChangeEvent($event)" placeholder="Upload file..." />
<button type="button" (click)="upload()">Upload</button>

upload.ts

import * as ng from '@angular/core';

@ng.Component({
  selector: 'upload',
  template: require('./upload.html')
})
export class Upload {
    filesToUpload: Array<File>;

    constructor() {
        this.filesToUpload = [];
    }

    upload() {
        this.makeFileRequest("http://localhost:5000/api/SampleData/uploadFile", [], this.filesToUpload).then((result) => {
            console.log(result);
        }, (error) => {
            console.error(error);
        });
    }

    fileChangeEvent(fileInput: any){
        this.filesToUpload = <Array<File>> fileInput.target.files;
    }

    makeFileRequest(url: string, params: Array<string>, files: Array<File>) {
        return new Promise((resolve, reject) => {
            var formData: any = new FormData();
            var xhr = new XMLHttpRequest();
            for(var i = 0; i < files.length; i++) {
                formData.append("uploads[]", files[i], files[i].name);
            }
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4) {
                    if (xhr.status == 200) {
                        resolve(JSON.parse(xhr.response));
                    } else {
                        reject(xhr.response);
                    }
                }
            }

SampleData.cs

    [HttpPost]
    public IActionResult uploadFile()
    {
        var files = Request.Form.Files;
        return Json("Working ? ");
    }

First it looks like your are doing it right from the Angular part, by creating form data. I had some similar issues getting files correctly on a POST request in asp.net. So the way I solved it, is to parse the content from the Request.

First create an empty method, it's important or else will you end up with a 404. Next read the file from the Request object:

[HttpPost]
public IActionResult uploadFile()
{
    var files = Request.Files;
    if (Request.Form[0] == null || files[0] == null || files[0].ContentLength < 1)
    {
            // TODO log
            Response.StatusCode = 400;
            return Json("Please provide a file");
    }
    // TODO parse the file(s) as you like :)
    foreach (HttpPostedFile file in files)
    {
        file.SaveAs(file.FileName);
    }
}

[Updated for asp.net core]

The changed the Request object in asp.net core, now the form data is in:

Request.Form.Files;

Here is an option

service.ts

uploadDealDocumentFile(document: DealDocument, files: File[]): Observable<any> {
var url = BASE_URL + 'fileupload/';
return Observable.create(observer => {
  let formData: FormData = new FormData(),
    xhr: XMLHttpRequest = new XMLHttpRequest();

  for (let i = 0; i < files.length; i++) {
    //formData.append("selectedDealId", document.dealId);          
    formData.append("uploads[]", files[i], document.dealCode + '-' + 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);
  xhr.send(formData);
});
}

FileUploadController.cs

public class FileUploadController : ApiController
{
    [HttpPost()]
    public string UploadFiles()
    {
        string sPath = HostingEnvironment.MapPath("~/UploadDocs/");
        int iUploadedCnt = 0;

        HttpFileCollection filesCollection = HttpContext.Current.Request.Files;
        string id = HttpContext.Current.Request.Form["Id"];

        for (int i = 0; i <= filesCollection.Count - 1; i++)
        {
            HttpPostedFile file = filesCollection[i];

            if (file.ContentLength > 0)
            {
                if (!File.Exists(sPath + Path.GetFileName(file.FileName)))
                {                        
                    file.SaveAs(sPath + Path.GetFileName(file.FileName));
                    iUploadedCnt = iUploadedCnt + 1;
                }
            }
        }

        if (iUploadedCnt > 0)
        {
            return iUploadedCnt + " Files Uploaded Successfully";
        }
        else
        {
            return "Upload Failed";
        }
    }
}

Good luck!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM