【问题标题】:Upload file to rails 6 api backend from react-native using axios使用 axios 从 react-native 将文件上传到 rails 6 api 后端
【发布时间】:2020-08-31 20:44:56
【问题描述】:

我想使用 axios 将带有数据的图像上传到我的 rails 6 api。我尝试使用 formdata,但收到 ActiveSupport::MessageVerifier::InvalidSignature 错误。这是我的代码:

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)); 

}

这是我收到的错误:

Completed 500 Internal Server Error in 171ms (ActiveRecord: 46.0ms | Allocations: 32866)



ActiveSupport::MessageVerifier::InvalidSignature (ActiveSupport::MessageVerifier::InvalidSignature):

非常感谢任何帮助。提前致谢

【问题讨论】:

标签: javascript ruby-on-rails react-native


【解决方案1】:

我在 reactjs 中遇到了同样的问题。我认为您的照片文件应该是“blob”文件。 我就这样解决了

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,
        );
    }   
  }

然后像这样使用fetch() 将参数发送到Rails API

 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
  })

但当然不在同一个事件处理程序中,因为状态还不会更新,而且它有效。由于某种原因,我既不能使用 axios 也不能这样做。

别忘了在 Rails 控制器中允许参数

  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

【讨论】:

    猜你喜欢
    • 2020-10-28
    • 1970-01-01
    • 2022-01-05
    • 2019-10-06
    • 1970-01-01
    • 2021-05-20
    • 2021-07-30
    • 2018-03-28
    • 1970-01-01
    相关资源
    最近更新 更多