modelbinder IsMultiPartContent始终返回false。如何使用react上传文件

时间:2018-07-19 16:04:15

标签: javascript .net reactjs asp.net-web-api asp.net-web-api2

我有以下反应成分

import React, { Component } from 'react';
import { Row, Col } from 'antd';
import PageHeader from '../../components/utility/pageHeader';
import Box from '../../components/utility/box';
import LayoutWrapper from '../../components/utility/layoutWrapper.js';
import ContentHolder from '../../components/utility/contentHolder';
import basicStyle from '../../settings/basicStyle';
import IntlMessages from '../../components/utility/intlMessages';
import { adalApiFetch } from '../../adalConfig';

export default class extends Component {
  constructor(props) {
    super(props);
    this.state = {TenantId: '', TenantUrl: '', TenantPassword: '' };
    this.handleChangeTenantUrl = this.handleChangeTenantUrl.bind(this);
    this.handleChangeTenantPassword = this.handleChangeTenantPassword.bind(this);
    this.handleChangeTenantId= this.handleChangeTenantId.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  };


  handleChangeTenantUrl(event){
    this.setState({TenantUrl: event.target.value});
  }

  handleChangeTenantPassword(event){
    this.setState({TenantPassword: event.target.value});
  }

  handleChangeTenantId(event){
    this.setState({TenantId: event.target.value});
  }

  handleSubmit(event){
    event.preventDefault();
    const formData = new FormData()

    let files = event.target.files;
      for (let i = 0; i < files.length; i++) {
        formData.append('content', files[i], files[i].name);
    } 

    const options = {
      method: 'put',
      data: {"TenantId": this.state.TenantId, "TenantUrl": this.state.TenantUrl, "TenantPassword": this.state.TenantPassword },
      config: {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }
    };

    adalApiFetch(fetch, "/Tenant", options)
      .then(response => response.json())
      .then(responseJson => {
        if (!this.isCancelled) {
          this.setState({ data: responseJson });
        }
      })
      .catch(error => {
        console.error(error);
      });
  }


  upload(e){
      let data = new FormData();
      //Append files to form data
      let files = e.target.files;
      for (let i = 0; i < files.length; i++) {
        data.append('content', files[i], files[i].name);
      }      
  }

  render(){
    const { data } = this.state;
    const { rowStyle, colStyle, gutter } = basicStyle;

    return (
      <div>
        <LayoutWrapper>
        <PageHeader>{<IntlMessages id="pageTitles.TenantAdministration" />}</PageHeader>
        <Row style={rowStyle} gutter={gutter} justify="start">
          <Col md={12} sm={12} xs={24} style={colStyle}>
            <Box
              title={<IntlMessages id="pageTitles.TenantAdministration" />}
              subtitle={<IntlMessages id="pageTitles.TenantAdministration" />}
            >
              <ContentHolder>
              <form onSubmit={this.handleSubmit}>
                <label>
                  TenantId:
                  <input type="text" value={this.state.TenantId} onChange={this.handleChangeTenantId} />
                </label>
                <label>
                  TenantUrl:
                  <input type="text" value={this.state.TenantUrl} onChange={this.handleChangeTenantUrl} />
                </label>
                <label>
                  TenantPassword:
                  <input type="text" value={this.state.TenantPassword} onChange={this.handleChangeTenantPassword} />
                </label>
                <label>
                  Certificate:
                  <input onChange = { e => this.upload(e) } type = "file" id = "files" ref = { file => this.fileUpload } />
                </label>             
              <input type="submit" value="Submit" />
              </form>
              </ContentHolder>
            </Box>
          </Col>
        </Row>
      </LayoutWrapper>
      </div>
    );
  }
}

并且我有以下webapi控制器

public class TenantModelBinder : IModelBinder
    {
        public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
        {
            if (bindingContext.ModelType != typeof(Tenant))
            {
                return false;
            }

            var task = Task.Run(async () =>
            {
                var model = new Tenant();

                if (!actionContext.Request.Content.IsMimeMultipartContent())
                {
                    bindingContext.ModelState.AddModelError(bindingContext.ModelName, "WebRequeest content 'multipart/form-data' is valid");
                }
                else
                {
                    var provider = await actionContext.Request.Content.ReadAsMultipartAsync();

                    var fileContent = provider.Contents.FirstOrDefault(n => n.Headers.ContentDisposition.Name.Equals("file"));
                    if (fileContent == null)
                    {
                        bindingContext.ModelState.AddModelError(bindingContext.ModelName, "Section 'file' is missed");
                    }

                    var modelContent = provider.Contents.FirstOrDefault(n => n.Headers.ContentDisposition.Name.Equals("model"));
                    if (modelContent == null)
                    {
                        bindingContext.ModelState.AddModelError(bindingContext.ModelName, "Section 'model' is missed");
                    }

                    if (fileContent != null && modelContent != null)
                    {
                        model = JsonConvert.DeserializeObject<Tenant>(await modelContent.ReadAsStringAsync());
                        //model.Text = "<NativeTranslation>";
                        model.ContentType = provider.Contents[0].Headers.ContentType.MediaType;
                        model.CertificateFile = await fileContent.ReadAsByteArrayAsync();
                        //model.TenantId = fileContent.Headers.ContentDisposition.FileName;
                    }
                }

                return model;
            });

            task.Wait();

            bindingContext.Model = task.Result;
            return true;
        }
    }


  public class Tenant
    {
        public string TenantId { get; set; }
        public string TenantUrl { get; set; }
        public Uri CertificatePath { get; set; }
        public string CertificatePassword { get; set; }

        public byte[] CertificateFile { get; set; }
        public string ContentType { get; set; }

        public override string ToString()
        {
            return JsonConvert.SerializeObject(this);
        }
    }


 [HttpPut]
        public async Task<IHttpActionResult> PutTenant([ModelBinder(typeof(TenantModelBinder))] Tenant tenant)
        {
            //var provider = new MultipartMemoryStreamProvider();
            //var contentType = "";
            //var content = new byte[0];
            //await base.Request.Content.ReadAsMultipartAsync(provider);
            //if (provider.Contents.Count > 0)
            //{
            //    contentType = provider.Contents[0].Headers.ContentType.MediaType;
            //    content = await provider.Contents[0].ReadAsByteArrayAsync();
            //}


            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConfigurationManager.AppSettings["AzureStorageKey"].ToString());
            // Create the blob client.
            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

            // Retrieve reference to a previously created container.
            CloudBlobContainer container = blobClient.GetContainerReference(ConfigurationManager.AppSettings["certificatesContainer"].ToString());

            // Retrieve reference to a blob named "myblob".
            CloudBlockBlob blockBlob = container.GetBlockBlobReference("myblob");

            // Create or overwrite the "myblob" blob with contents from a local file.
            blockBlob.Properties.ContentType = tenant.ContentType;
            MemoryStream stream = new MemoryStream(tenant.CertificateFile);
            blockBlob.UploadFromStream(stream);

            var tenantStore = CosmosStoreFactory.CreateForEntity<Tenant>();
            tenant.CertificatePath = blockBlob.Uri;

            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var added = await tenantStore.AddAsync(tenant);
            return StatusCode(HttpStatusCode.NoContent); 
        }

该行:

actionContext.Request.Content.IsMimeMultipartContent()

总是假的,那就是问题。

1 个答案:

答案 0 :(得分:1)

我不知道React,但似乎您的请求不是multipart/form-data请求。

您正确使用了ContentType,但据我了解,您的数据是JSON ...

您需要发送FormData对象。

类似这样的东西:

const formData = new FormData()
formData.append("model", {"TenantId": this.state.TenantId, "TenantUrl": this.state.TenantUrl, "TenantPassword": this.state.TenantPassword });
let files = event.target.files;
for (let i = 0; i < files.length; i++) {
    formData.append('content', files[i], files[i].name);
}

const options = {
    method: 'put',
    data: formData,
    config: {
        headers: {
            'Content-Type': 'multipart/form-data'
        }
    }
};

无论如何,您都可以在文档链接here中找到所有必要的信息。

请查看example的有关在jQuery上发送multipart/form-data的信息。

还有example在React上。