简体   繁体   English

使用React和Rails上传图像-Paperclip和AWS S3存储桶

[英]Using React and Rails to upload image - Paperclip and AWS S3 bucket

I have a react frontend and a Rails backend. 我有一个React前端和一个Rails后端。 I am using the paperclip gem and aws-sdk gem in order to upload images to my app. 我正在使用回形针gem和aws-sdk gem以便将图像上传到我的应用程序。 The whole idea is that a user can upload a comment and in that comment there can be an attachment. 整个想法是用户可以上传评论,并且该评论中可以包含附件。 I think maybe I am sending my backend the wrong data though because it is not working.... On the frontend i'm using file reader to make a file object and sending my rails app the file object -- but it doesn't seem to be recognizing it. 我认为也许我正在向后端发送错误的数据,因为它无法正常工作。...在前端,我正在使用文件读取器制作文件对象,并将Rails应用程序发送给文件对象-但它没有似乎正在意识到这一点。 If i want my rails backend to recognize this image attachment, how should the image be formatted in my frontend before i send it to my rails app? 如果我想让Rails后端识别该图像附件,在将图像发送到Rails应用程序之前应如何在前端对图像进行格式化?

This is how my file object is stored in the state -- on handleChange of course: 这是我的文件对象在状态下的存储方式-当然在handleChange上:

 handleFileChange = (e) => {
  debugger

 e.preventDefault();

  let reader = new FileReader();
  let file = e.target.files[0];

  reader.onloadend = () => {
    this.setState({
      file: file,
      imagePreviewUrl: reader.result
    });
  }
  reader.readAsDataURL(file)
}

then when i submit the form i use a callback that eventually sends that file object to my adapter which makes the call to the rails backend as sseen below: 然后,当我提交表单时,我使用了一个回调函数,该回调函数最终将该文件对象发送到我的适配器,该适配器对rails后端的调用如下所示:

  static addComment(comment, project_id, datetime, clientView, file) {
   debugger
   return fetch(path,{
     method: 'POST',
     headers: headers(),
     body: JSON.stringify({
       client_view: clientView,
       comment_text: comment,
       project_id: project_id,
       currenttime: datetime,
       commentasset: file
     })
   })
   .then( resp => resp.json())
 }

so im sending my rails the file object in the param that is commentasset... but when i hit my byebug on my rails end and check 所以我将我的rails文件对象发送到了commentasset的参数中...但是当我在我的rails端击中我的byebug并检查时

params[:commentasset] 

it appears to be blank. 它似乎是空白。 Why isnt it sending back my file object? 为什么不发回我的文件对象?

You're sending a request with JSON including the file as body. 您正在使用JSON发送请求,其中包括文件作为正文。 Try to send request using FormData instead: 尝试使用FormData发送请求:

static addComment(comment, project_id, datetime, clientView, file) {
   debugger
   const body = FormData.new();
   body.append('client_view', clientView);
   body.append('comment_text', comment);
   body.append('project_id', project_id);
   body.append('currenttime', datetime);
   body.append('commentasset', file);

   return fetch(path,{
     method: 'POST',
     headers: headers(),
     body: body
   })
   .then( resp => resp.json())
 }

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

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