【问题标题】:Image uploading using reactjs, does not save image path in the database使用reactjs上传图片,不在数据库中保存图片路径
【发布时间】:2018-02-01 14:58:54
【问题描述】:

我在后端使用 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

我还参考了此门户中提供的许多解决方案。但是,仍然无法研究我的代码中出了什么问题。

【问题讨论】:

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


    【解决方案1】:

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

    完美的解决方案是

    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; 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-04-07
      • 2021-12-02
      • 1970-01-01
      • 2013-11-01
      • 2015-04-20
      • 2023-04-09
      • 1970-01-01
      相关资源
      最近更新 更多