javascript - How to send form data with react - Stack Overflow

I have a webapi with this method:public async Task<IHttpActionResult>PutTenant(string id, Tenan

I have a webapi with this method:

 public async Task<IHttpActionResult>  PutTenant(string id, Tenant tenant, HttpPostedFile certificateFile)
        {
            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 = certificateFile.ContentType;
            blockBlob.UploadFromStream(certificateFile.InputStream);

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

            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }
            if (id != tenant.TenantId)
            {
                return BadRequest();
            }

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

Now I have a form in react:

import React, { Component } from 'react';

import { Row, Col } from 'antd';
import PageHeader from '../../ponents/utility/pageHeader';
import Box from '../../ponents/utility/box';
import LayoutWrapper from '../../ponents/utility/layoutWrapper.js';
import ContentHolder from '../../ponents/utility/contentHolder';
import basicStyle from '../../settings/basicStyle';
import IntlMessages from '../../ponents/utility/intlMessages';
import { adalApiFetch } from '../../adalConfig';
import axios from 'axios';
const API_SERVER = "example.azure/upload";

export default class extends Component {
  constructor(props) {
    super(props);

  }

  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('files', files[i], files[i].name);
    }

    let d = {
      method: 'post',
      url: API_SERVER,
      data: data,
      config: {
        headers: {
          'Content-Type': 'multipart/form-data'
        },
      },
      onUploadProgress: (eve) => {
        let progress = utility.UploadProgress(eve);
        if (progress == 100) {
          console.log("Done");
        } else {
          console.log("Uploading...",progress);
        }
      },
    };
    let req = axios(d);

     return new Promise((resolve)=>{
        req.then((res)=>{
            return resolve(res.data);
        });
    });

  }


  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>
              {//Put Form here with file upload.
              }
              <form>
              Name:     <input type="text" name="tenanturl" />
              Password: <input type="text" name="password" />

              <input onChange = { e => this.upload(e) } type = "file" id = "files" ref = { file => this.fileUpload } />
              <input type="submit" value="Submit" />
              </form>
              </ContentHolder>
            </Box>
          </Col>
        </Row>
      </LayoutWrapper>
      </div>
    );
  }
}

The tenant object has 2 string properties which are the same in the form. How do I send those 2 string properties as a Tenant object? How do I trigger the submit form?

new to forms in react btw

I have a webapi with this method:

 public async Task<IHttpActionResult>  PutTenant(string id, Tenant tenant, HttpPostedFile certificateFile)
        {
            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 = certificateFile.ContentType;
            blockBlob.UploadFromStream(certificateFile.InputStream);

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

            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }
            if (id != tenant.TenantId)
            {
                return BadRequest();
            }

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

Now I have a form in react:

import React, { Component } from 'react';

import { Row, Col } from 'antd';
import PageHeader from '../../ponents/utility/pageHeader';
import Box from '../../ponents/utility/box';
import LayoutWrapper from '../../ponents/utility/layoutWrapper.js';
import ContentHolder from '../../ponents/utility/contentHolder';
import basicStyle from '../../settings/basicStyle';
import IntlMessages from '../../ponents/utility/intlMessages';
import { adalApiFetch } from '../../adalConfig';
import axios from 'axios';
const API_SERVER = "example.azure./upload";

export default class extends Component {
  constructor(props) {
    super(props);

  }

  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('files', files[i], files[i].name);
    }

    let d = {
      method: 'post',
      url: API_SERVER,
      data: data,
      config: {
        headers: {
          'Content-Type': 'multipart/form-data'
        },
      },
      onUploadProgress: (eve) => {
        let progress = utility.UploadProgress(eve);
        if (progress == 100) {
          console.log("Done");
        } else {
          console.log("Uploading...",progress);
        }
      },
    };
    let req = axios(d);

     return new Promise((resolve)=>{
        req.then((res)=>{
            return resolve(res.data);
        });
    });

  }


  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>
              {//Put Form here with file upload.
              }
              <form>
              Name:     <input type="text" name="tenanturl" />
              Password: <input type="text" name="password" />

              <input onChange = { e => this.upload(e) } type = "file" id = "files" ref = { file => this.fileUpload } />
              <input type="submit" value="Submit" />
              </form>
              </ContentHolder>
            </Box>
          </Col>
        </Row>
      </LayoutWrapper>
      </div>
    );
  }
}

The tenant object has 2 string properties which are the same in the form. How do I send those 2 string properties as a Tenant object? How do I trigger the submit form?

new to forms in react btw

Share Improve this question asked Jul 15, 2018 at 8:23 Luis ValenciaLuis Valencia 34.1k99 gold badges311 silver badges532 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 3

Here is my sample. Basically I will define properties I want to send to API. In this case I use axios

const data = {
    Username: this.state.username,
    Email: this.state.email,
}

axios
      .post(url, data)
      .then(data => {
        //something
      })
      .catch(error => {
        //something
      });

And in my API controller I will receive data being pass to server by using [FormBody] tag

public async Task<IActionResult> AddNewUser([FromBody] UserInputViewModel userInputVm)

Please adjust accordingly with your code. Let me know if you have any issue.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745236694a4617935.html

相关推荐

  • javascript - How to send form data with react - Stack Overflow

    I have a webapi with this method:public async Task<IHttpActionResult>PutTenant(string id, Tenan

    7小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信