I am using Rails API in the backend and ReactJS in frontend. I am also using carrier-wave for processing my image in the backend. I tried to upload my image and send it to the backend. The image files are being captured in the frontend by using simple HTML uploader.
This is my 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;
The above code is an exact replica of this solution.I have used formData and axios in order to PUSH the data to the backend. But the datas are stored as a "nil" values in the database. console.log(formData) gives an empty hash.
My Controller code in backend side is
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
I have also refered many solution given in this portal. But still , cannot able to study whats going wrong in my code.