简体   繁体   中英

How to post a file to a web api from reactjs With react-adal, not Axios

I need to use this package to consume rest api:

https://github.com/salvoravida/react-adal

The code I have so far is the following, basically I have found examples all around and put all together, however the const data has the values tenantid, tenanturl and tenantpassword.

The questions is how do I send the file into the request?

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';

const data = {
  TenantId: this.this.state.tenantid,
  TenanrUrl: this.state.tenanturl,
  TenantPassword: this.state.tenantpassword 
};

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

export default class extends Component {
  constructor(props) {
    super(props);
    this.state = {value: ''};
    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){
    alert('A name was submitted: ' + this.state.value);
    event.preventDefault();
    postData();
  }

  postData = () => {
    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('files', 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>
    );
  }
}

The problem is that you're creating the options variable before any of the references in it are defined. You'll need to do something like this:

 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 = {value: ''}; 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){ alert('A name was submitted: ' + this.state.value); event.preventDefault(); postData(); } postData = () => { this.data.append("TenantId", this.state.tenantid); this.data.append("TenanrUrl", this.state.tenanturl); this.data.append("TenantPassword", this.state.tenantpassword); const options = { method: 'post', data: this.data, config: { headers: { 'Content-Type': 'multipart/form-data' } } }; adalApiFetch(options) .then(response => response.json()) .then(responseJson => { if (!this.isCancelled) { this.setState({ data: responseJson }); } }) .catch(error => { console.error(error); }); }; upload(e){ this.data = new FormData(); let files = e.target.files; for (let i = 0; i < files.length; i++) { data.append('files', 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> ); } } 

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