仅将更改时的文件输入提交到服务器并忽略其他输入,直到按下提交表单

发布于 2025-01-09 08:08:25 字数 484 浏览 1 评论 0原文

我有一个这样的表单

<form method="post" action="">
    <input type="text" onchange="uploadFile()" name="username">
    <textarea name="description"></textarea>
    <input type="file" name="upload">
    <button>Submit</button>
</form>

,我希望当用户选择文件时自动上传文件,而不是当用户单击提交按钮时

尝试在更改事件上上传此文件确实会显示发布请求,但文件不在请求中。

问题: 是否可以通过 ajax 将单个输入提交到服务器而不包含其他字段?

I have a form like this

<form method="post" action="">
    <input type="text" onchange="uploadFile()" name="username">
    <textarea name="description"></textarea>
    <input type="file" name="upload">
    <button>Submit</button>
</form>

I want when a user selects a file to automatically upload the file instead of the when the user clicks the submit button

trying to upload this on change event does show a post request, but the files are not in the request.

Question:
Can an individual input be submitted to the server without the other field inclusion via ajax?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

写下不归期 2025-01-16 08:08:25

是的,这应该是可能的。

下面是一个示例:

uploadFile() {
    let formData = new FormData(); // Create FromData object
    let form = document.querySelector('form'); // Get the form element
    formData.append( 'upload', form.upload.files[0] ) // Add your file with the name upload to the formData.
    await fetch('yourPostTarget.php', {
            method: 'POST',
            body: formData
    }); // Send the file to your server using ajax
}

其他修复:

  • 您可能应该向表单添加一个操作。
  • 上传文件的 onchange 函数可能应该位于文件输入中,而不是文本输入中。

Yes, It should be possible.

Heres an example:

uploadFile() {
    let formData = new FormData(); // Create FromData object
    let form = document.querySelector('form'); // Get the form element
    formData.append( 'upload', form.upload.files[0] ) // Add your file with the name upload to the formData.
    await fetch('yourPostTarget.php', {
            method: 'POST',
            body: formData
    }); // Send the file to your server using ajax
}

Other fixes:

  • You should probably add an action to your form.
  • The onchange function to upload the file should probably be in the file input not the text input.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文