How to upload local image file on React Native app to Rails api?

前端 未结 1 1052
独厮守ぢ
独厮守ぢ 2020-12-21 22:52

I\'m having trouble understanding how a local file path from a smartphone could possibly get uploaded on the server side with a Rails api for instance.

The file path

相关标签:
1条回答
  • 2020-12-21 23:23

    I have recently spent 1+ hour debugging something similar.

    I found out that if you make a POST to your Rails backend from your React Native app using this json:

    let formData = new FormData();
      formData.append('photo', {
        uri,
        name: `photo.${fileName}`,
        type: `image/${fileType}`,
      });
    

    Rails will automatically give you a ActionDispatch::Http::UploadedFile in your params[:photo], which you can attach directly to your model like Photo.create(photo: params[:photo]) and it simply works.

    However, if you don't pass a filename, everything breaks and you'll get a huge string instead and it will raise a ArgumentError (invalid byte sequence in UTF-8).

    So, based on your code, I can spot the bug right on: you are passing name as photo.${fileType}, which is wrong, and should be photo.${fileName} (update accordingly to get your image filename ... console.log(photo) in your React Native code will show you the correct one.

    0 讨论(0)
提交回复
热议问题