Javascript 如何在 axios 中使用 react 设置 multipart?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41878838/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:43:41  来源:igfitidea点击:

How do I set multipart in axios with react?

javascriptreactjsmultipartform-dataaxios

提问by Shamoon

When I curl something, it works fine:

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

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

How do I get this to work right with axios? I'm using react if that matters:

我如何让它与 axios 一起工作?如果这很重要,我正在使用反应:

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)
}

This doesn't work for some reason.

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

回答by Ashik Nesin

Here's how I do file upload in react using axios

这是我如何使用 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

Source

来源

回答by Shota

If you are sending alphanumeric data try changing

如果您要发送字母数字数据,请尝试更改

'Content-Type': 'multipart/form-data'

to

'Content-Type': 'application/x-www-form-urlencoded'

If you are sending non-alphanumeric data try to remove 'Content-Type' at all.

如果您要发送非字母数字数据,请尝试完全删除“Content-Type”。

If it still does not work, consider trying request-promise(at least to test whether it is really axios problem or not)

如果还是不行,可以考虑试试request-promise(至少要测试一下是否真的是axios的问题)

回答by SHREYA PRASAD

ok. I tried the above two ways but it didnt work for me. After trial and error i came to know that actually the file was not getting saved in 'this.state.file' variable.

好的。我尝试了上述两种方法,但对我不起作用。经过反复试验,我才知道实际上该文件并未保存在“this.state.file”变量中。

fileUpload = (e) => {
    let data = e.target.files
    if(e.target.files[0]!=null){
        this.props.UserAction.fileUpload(data[0], this.fallBackMethod)
    }
}

here fileUpload is a different js file which accepts two params like this

这里 fileUpload 是一个不同的 js 文件,它接受两个这样的参数

export default (file , callback) => {
const formData = new FormData();
formData.append('fileUpload', file);

return dispatch => {
    axios.put(BaseUrl.RestUrl + "ur/url", formData)
        .then(response => {
            callback(response.data);
        }).catch(error => {
         console.log("*****  "+error)
    });
}

}

}

don't forget to bind method in the constructor. Let me know if you need more help in this.

不要忘记在构造函数中绑定方法。如果您在这方面需要更多帮助,请告诉我。