i want to upload image with data to my rails 6 api using axios. I try with formdata but I am getting an ActiveSupport::MessageVerifier::InvalidSignature
error. Here is my code:
uploadToServer= () => {
const file =this.state.photo
let formdata = new FormData()
formdata.append('name', this.state.name)
formdata.append('photo', file)
axios.post(
'api',
formdata,
{
headers: {
'Content-type' : 'multipart/form-data',
'Authorization':'xx'
}
}
).then(resp => console.log(resp)).catch(error => console.error(error));
}
This is the error I receive:
Completed 500 Internal Server Error in 171ms (ActiveRecord: 46.0ms | Allocations: 32866)
ActiveSupport::MessageVerifier::InvalidSignature (ActiveSupport::MessageVerifier::InvalidSignature):
Any help is very much appreciated. Thanks in advance
I had the same problem in reactjs. I think your photo file should be a " blob " file. I solved it like that
import Resizer from 'react-image-file-resizer';
imageInputHandler = (event) =>{
var fileInput = false
if(event.target.files[0]) {
fileInput = true
}
if(fileInput) {
Resizer.imageFileResizer(
event.target.files[0],
800,
800,
'JPEG',
100,
0,
uri => {
console.log("ok....resized")
this.setState({
file: uri
})
},
'blob',
200,
200,
);
}
}
And then sent the parameter to the Rails API with fetch()
like that
const formData = new FormData();
formData.append('text', self.state.text);
formData.append('user_id', self.props.user_id);
formData.append('image', self.state.image);
fetch('http://localhost:3000/posts/create', {
method: 'POST',
body: formData
})
But of course not in the same event handler because the state won't be updated yet, and it worked. For some reason, I couldn't do it neither using axios.
And don't forget to permit the params in your Rails controller
def create
@post=Post.create(post_params)
image_url=rails_blob_path(@post.image , only_path: true) if @post.image.attached?
render json: {text: @post.text, image: image_url, user_id: @post.user_id, id:@post.id }
end
private
def post_params
params.permit( :text, :user_id, :image )
end
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.