小编典典

如何在Axios中使用React设置多部分?

javascript

当我卷曲某些东西时,它可以正常工作:

curl -L -i -H 'x-device-id: abc' -F "url=http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"  http://example.com/upload

我如何使其与axios一起正常工作?如果这很重要,我正在使用react:

uploadURL (url) {
  return axios.post({
    url: 'http://example.com/upload',
    data: {
      url: url
    },
    headers: {
      'x-device-id': 'stuff',
      'Content-Type': 'multipart/form-data'
    }
  })
  .then((response) => response.data)
}

由于某些原因,这不起作用。


阅读 301

收藏
2020-05-01

共1个答案

小编典典

这是我如何使用axios在react中上传文件

import React from 'react'
import axios, { post } from 'axios';

class SimpleReactFileUpload extends React.Component {

  constructor(props) {
    super(props);
    this.state ={
      file:null
    }
    this.onFormSubmit = this.onFormSubmit.bind(this)
    this.onChange = this.onChange.bind(this)
    this.fileUpload = this.fileUpload.bind(this)
  }

  onFormSubmit(e){
    e.preventDefault() // Stop form submit
    this.fileUpload(this.state.file).then((response)=>{
      console.log(response.data);
    })
  }

  onChange(e) {
    this.setState({file:e.target.files[0]})
  }

  fileUpload(file){
    const url = 'http://example.com/file-upload';
    const formData = new FormData();
    formData.append('file',file)
    const config = {
        headers: {
            'content-type': 'multipart/form-data'
        }
    }
    return  post(url, formData,config)
  }

  render() {
    return (
      <form onSubmit={this.onFormSubmit}>
        <h1>File Upload</h1>
        <input type="file" onChange={this.onChange} />
        <button type="submit">Upload</button>
      </form>
   )
  }
}



export default SimpleReactFileUpload
2020-05-01