【发布时间】: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