【问题标题】:Angular 2 form Data and JSON data post in same requestAngular 2 表单数据和 JSON 数据在同一请求中发布
【发布时间】:2017-07-04 13:24:53
【问题描述】:

我正在使用 Angular 2 和 HTML 文件上传控件进行文件上传操作。 我上传文件的代码如下-

saveDocument(value: any) {
        let apiEndPoint: any = 'http://localhost:58736/LandingPage/addUpdateDocument';
        let fi = this.FileInput.nativeElement;
        if (fi.files && fi.files[0]) {
            let fileToUpload = fi.files[0];
            let formData: FormData = new FormData();
            formData.append('newDocument', fileToUpload, value);
            let headers = new Headers();
            headers.append('Accept', 'application/json');
            let options = new RequestOptions({ headers: headers });
            this._http.post(`${apiEndPoint}`, formData , options).map(res => res.json()).catch(error => Observable.throw(error)).subscribe(
                data => console.log('success'),
                error => console.log(error))
        }
    }

我有一个 ASP.Net MVC 服务器端方法如下--

[System.Web.Http.HttpPost]
        public string addUpdateDocument(HttpPostedFileBase newDocument)
        {
            string responseMessage = string.Empty;
            try
            {
                if (newDocument.ContentLength > 0)
                {
                    string _FileName = Path.GetFileName(newDocument.FileName);
                    string _path = Path.Combine(Server.MapPath("~/upload"), _FileName);
                    newDocument.SaveAs(_path);
                }
                responseMessage = "Upload Successfull !!";
            }
            catch(Exception ex)
            {
                responseMessage = "Upload Successfull !!";
            }

            return responseMessage;
        }

    }

只要我只上传文件,它就可以正常工作。但我想发送除文件之外的更多信息。我尝试实现该功能如下--

this._http.post(`${apiEndPoint}`,{'newDocument':formData,'documentMetaData':value} , options).map(res => res.json()).catch(error => Observable.throw(error)).subscribe(
                data => console.log('success'),
                error => console.log(error))

然后我修改了服务端方法如下-

[System.Web.Http.HttpPost]
public string addUpdateDocument(HttpPostedFileBase newDocument, BlankFormsModels documentMetaData)

BlankFormsModels 只是一个类。当我这样做时,在服务器端接收到元数据,但没有接收到文件。它是空的。请建议如何在同一个请求中发布表单数据和 JSON 数据。

【问题讨论】:

标签: angular


【解决方案1】:

你可以这样发送数据:

var obj = {
   formData : formData,
   otherInfo : otherInfo
}

在服务器端,上传文件时,使用obj 的密钥formData 而不是整个对象。之后发布另一个数据。 使用 Promise 进行正确的同步。

【讨论】:

  • 这对我不起作用,当我附加两个文件时,formData 将变为空。
猜你喜欢
  • 2017-02-11
  • 2017-02-03
  • 1970-01-01
  • 2021-05-14
  • 2011-11-27
  • 1970-01-01
  • 2017-04-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多