如何在 axios 中使用 react 设置 multipart? [英] How do I set multipart in axios with react?

查看:69
本文介绍了如何在 axios 中使用 react 设置 multipart?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

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.

推荐答案

这是我在 react 中使用 axios 上传文件的方法

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

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

来源

这篇关于如何在 axios 中使用 react 设置 multipart?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆