使用reactjs上传图像,不会在数据库中保存图像路径

时间:2018-01-31 11:41:30

标签: reactjs ruby-on-rails-4 file-upload axios

我在后端使用Rails API,在前端使用ReactJS。我也使用载波在后端处理我的图像。我试图上传我的图像并将其发送到后端。通过使用简单的HTML上传器在前端捕获图像文件。

这是我的uploader.jsx

import React from 'react'
import axios, { post } from 'axios';
import { PORT } from '../constant.js';


class PrescriptionNew 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', response.data)
    })
  }

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

  fileUpload(file){ 
    const url = `${PORT}/prescriptions`;
    var FormData = require('form-data');
    const formData = new FormData();
    formData.append('file',file)
    const config = {
      headers: {
        'content-type': 'multipart/form-data'
      }
    }
    return post(url,formData, config)
  }
  
  render() {
    if (this.state.file !== null) {
      console.log('this.file', this.state.file.name)
    }
    return (
      <form onSubmit={this.onFormSubmit}>
        <h1>File Upload</h1>
        <input type="file" onChange={this.onChange} />
        <button type="submit">Upload</button>
      </form>
   )
  }
}

export default PrescriptionNew;

上面的代码是this solution的精确副本。我使用了formData和axios来将数据推送到后端。但是数据在数据库中存储为“nil”值。 console.log(formData)给出一个空哈希。

后端的我的控制器代码是

def create
  @prescription = Prescription.new(prescription_params)
  @prescription.user = current_user
  unless @prescription.save
    render json: { status: 200, errors: @prescription.errors } and return
  else
    render :show
  end
end

我还提到了这个门户网站给出的许多解决方案。但是,仍然无法研究我的代码中出了什么问题。

1 个答案:

答案 0 :(得分:0)

简单的解决方案是填充FormData。返回一个空的FormData将存储&#39; nil&#39;数据库中的值。

完美的选择是

class PrescriptionNew extends Component {

  upload_image(){
    var element = document.getElementById("image-form")
    var formData =  new FormData(element);
    const url = `${PORT}/prescriptions`
    fetch(url,{
      method: "POST",
      body: formData
    })
    .then(response => response.json)
  }

  after_submit(event){
    event.preventDefault();
  }

  render(){
    return(
      <div>
        <h3 className="index-title">Upload Your Prescription</h3>
        <form onSubmit={event => this.after_submit(event)} id="image-form" encType='multipart/form-data'>
          <input type="file" name="image_path"/>
          <button onClick={() => this.upload_image()}>Upload</button>
        </form>  
      </div>
    )
  }
}

export default PrescriptionNew;