【问题标题】:How get image from FormData to Rails API and saves in ActiveStorage如何从 FormData 获取图像到 Rails API 并保存在 ActiveStorage
【发布时间】:2019-10-11 01:40:22
【问题描述】:

我正在尝试将 FormData 对象从我的 React Native 应用程序发送到我的 Rails API。 我正在使用 react-native-image-crop-picker 从图库中选择图像并将图像对象存储在我的状态中:

 ImagePicker.openPicker({
      multiple: true,
      cropping: true,
      includeBase64: true,
      compressImageMaxHeight: 1080,
      compressImageMaxWidth: 1080,
    })
      .then(selectedImages => {
        selectedImages.map(image => {

          let prefix;
          let ext;

          [prefix, ext] = image.filename.split(".");
          ext = ext.toLowerCase() === "heic" ? "jpg" : ext;

          const upload = {
            uri: image.path,
            type: image.mime,
            name: `${prefix}.${ext}`,
          };

          this.setState(prevState => ({
            event: {
              ...prevState.event,
              images: [...prevState.event.images, upload],
            },
          }));        

        });
      })
      .catch(error => {

      });

然后我创建一个 FormData 对象来发送我的 Rails API:

 const data = new FormData();

 data.append("name", event.name);
 data.append("description", event.description);
 data.append("date", event.date);
 data.append("time", event.time);
 data.append("images", event.images[0]);

我的api成功接收到que请求: Parameters: {"event"=>{"_parts"=>[["event[name]", ""], ["event[description]", ""], ["event[date]", ""], ["event[time]", ""], ["event[images]", {"uri"=>"/private/var/mobile/Containers/Data/Application/6226B812-CDEC-4994-A864-0A91EE8C44B3/tmp/react-native-image-crop-picker/BFC043EC-D33F-4E07-BBEA-634CE5DE8A3F.jpg", "type"=>"image/jpeg", "name"=>"IMG_7142.jpg"}]]}}

现在,我怎样才能恢复这个图像并直接保存在我的 Rails ActiveStorage 中? 我正在尝试将图像对象:{"uri"=>"/private/var/mobile/Containers/Data/Application/6226B812-CDEC-4994-A864-0A91EE8C44B3/tmp/react-native-image-crop-picker/BFC043EC-D33F-4E07-BBEA-634CE5DE8A3F.jpg", "type"=>"image/jpeg", "name"=>"IMG_7142.jpg"} 直接附加到我的模型,但我得到了当前的异常:ActiveRecord::RecordNotSaved (Failed to save the new associated avatar_attachment.):

【问题讨论】:

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


    【解决方案1】:

    我看到您要附加多张图片。 如果您已经通过documentation,我相信您现在必须已经设置了活动存储。

    你的模型中有has_many_attached :images吗?请注意,图像可能是其他东西或几乎任何名称。

    我能够通过执行以下操作来检索图像名称(但我怀疑它是否适合您的目的):

    hash = {"uri"=>"/private/var/mobile/Containers/Data/Application/6226B812-CDEC-4994-A864-0A91EE8C44B3/tmp/react-native-image-crop-picker/BFC043EC-D33F-4E07-BBEA-634CE5DE8A3F.jpg", "type"=>"image/jpeg", "name"=>"IMG_7142.jpg"}
    
    hash['uri'].split('/')[-1]
    
    => "BFC043EC-D33F-4E07-BBEA-634CE5DE8A3F.jpg"
    

    如果上述路线是您想要的方式,并且您确定它会以这种方式运行,那么您需要执行以下操作:

    @your_model.images.attach(io: File.open("#{hash['uri']}"), filename: "#{hash['uri'].split('/')[-1]}")

    您可以在此处找到有关其实际工作原理的完整教程 - https://medium.com/@ashley_foster/react-native-image-uploads-with-activestorage-ec4898317a82

    试一试,如果您在此过程中遇到困难,您可以发表评论或编辑/更新您的问题。

    【讨论】:

    • 我已经在管理has_many_attached :images。本教程的问题在于教如何做,但使用 base64 图像,这会增加 33% 的请求大小。我只想通过 FormData 发送文件。我可以让它在 Postman 上工作,但是从应用程序发送图像看起来我不是在发送图像,而只是他的路径本身
    • 这有可能会起作用,你试过了吗? @your_model.images.attach(io: File.open("#{hash['uri']}"), filename: "#{hash['uri'].split('/')[-1]}") 但是,如果它不起作用,我建议您先完成上述教程,然后再考虑优化图像的大小,当您到达那里时,这一步通常是最简单的。
    • 是的,我试过了,但没有按预期工作。现在我正在使用教程方式,它也可以正常工作。谢谢!
    猜你喜欢
    • 2018-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多