【问题标题】:Attach JSON to an existing form将 JSON 附加到现有表单
【发布时间】:2020-07-28 21:32:20
【问题描述】:

我正在为我的个人网站从博客文章表单中的选定图像中提取 exif 数据。 我想将找到的 exif 数据作为我的表单字段发送,格式为 JSON。我不确定正确的方法。我的第一个想法是只输入一个 text_area 并将 JSON 的值设置到该字段中。虽然我觉得必须有更好的方法。

想法?

【问题讨论】:

  • 您好,请问您是如何从图片中提取exif数据的?
  • 这个可爱的库github.com/mattiasw/ExifReader。此外,我只是将有问题的图像客户端上传到 S3,因此图像永远不会发送到我的服务器,否则我只会在服务器端完成所有这些操作。
  • 可以加一个document.addEventListener('submit', ...防止页面重载,也就是提交e.preventDefault()的默认行为,用字段信息和图片的数据信息构建一个数据对象,构建一个 HTTP 请求,并使用 POST 获取以 JSON 格式发送您创建的数据结构。
  • 这是一个有趣的想法。感谢分享。
  • 嘿!嘿,你最后做到了吗?

标签: javascript json forms exif


【解决方案1】:

您可以这样做,将图像元数据作为字段添加到数据对象上并发送:

// The elements are being instanced outside the event listener. In the event listener we can get the current value of the element
const nameInput = document.getElementById('name') 
const lastNameInput = document.getElementById('last-name')
const idInput = document.getElementById('id')

// A regular button, not a submit one
const sendBtn = document.getElementById("send-btn")

// The event that will listen the button, take the data of your fields and send it in JSON format
sendBtn.addEventListener('click', async () => {
    // The URL of your server
    const url = 'http://localhost:3000/users'

    const data = { 
        name: nameInput.value,
        lastName: lastNameInput.value,
        id: idInput.value
    }

    const request = new Request(
        url,
        {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' }, // If the headers are not defined, your backend application doesn't recognize the data sent with JSON
            body: JSON.stringify(data)
        }
    )

    try {
        const response = await fetch( request )
        const jsonResponse = await response.json()
        // With the response of the server you have infinite posibilities.
        console.log(jsonResponse)
    } catch (e){
        alert('Error connecting with the server')
    }    
})

【讨论】:

    猜你喜欢
    • 2017-08-03
    • 2018-07-13
    • 1970-01-01
    • 2016-08-21
    • 1970-01-01
    • 2016-07-31
    • 2015-12-29
    • 2020-05-21
    相关资源
    最近更新 更多