繁体   English   中英

使用 axios 从 react-native 上传文件到 rails 6 api 后端

[英]Upload file to rails 6 api backend from react-native using axios

我想使用 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):

很感谢任何形式的帮助。 提前致谢

我在 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM