POST:422不可处理的实体尝试从 JavaScript前端rails api后端上传图像

问题描述

我试图从接受“文件”输入类型的表单上传图像,但是当我选择图像并提交时,我收到 422 错误。我不确定我的后端设置是否正确,或者我的前端是否错误?这不是全部代码,只是我认为可能与解决问题相关的代码

class Photo {

  constructor({
    id,date,image,photographer,gallery_id
  }) {
    this.id = id;
    this.date = date;
    this.image = image;
    this.photographer = photographer;
    this.gallery_id = gallery_id

    this.element = document.createElement('li')
    this.element.dataset.id = this.id
    this.element.id = `photo-${this.id}`
    Photo.all.push(this)

  static renderForm() {
    Photo.photoForm.innerHTML += `
        <form id="new_photo">
            Date: <input type="text" id="date">
            Photographer: <input type="text" id="photographer">
            image: <input type="file" id="file" accept="image/*">
            <input type="submit" id="Publish">
        </form>
        `
  }
}
////////////////////////////////////////////////////

class PhotoService {

  constructor(endpoint) {
    this.endpoint = endpoint
  }
  getPhotos() {
    fetch(`${this.endpoint}/photos`)
      .then(resp => resp.json())
      .then(photos => {
        for (const photo of photos) {
          const p = new Photo(photo)
          p.slapOnDom()

        }

      })
  }
  //  sending a new image to the backend //
  createPhoto() {

    const photo = {
      date: document.getElementById('date').value,photographer: document.getElementById('photographer').value,image: document.getElementById('file').value,gallery_id: 1
    }


    const configObj = {
      method: 'POST',headers: {
        'Content-Type': 'application/json'

      },body: JSON.stringify(photo)
    }

    fetch(`${this.endpoint}/photos`,configObj)
      .then(resp => resp.json())
      .then(photo => {
        const p = new Photo(photo)
        p.slapOnDom()
      })

  }

}
////////////////////////////////////////////////////
const base_url = "http://127.0.0.1:3000"
const photoService = new PhotoService(base_url)

// document.addEventListener('DOMContentLoaded',getPhotos)
Photo.photoForm.addEventListener('submit',handleSubmit)
photoService.getPhotos()
Photo.renderForm()

function handleSubmit(event) {
  event.preventDefault()
  const reader = new FileReader();
  reader.onload = logFile();
  reader.readAsDataURL(file.files[0]);
  photoService.createPhoto()
}

]1

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...