简体   繁体   English

使用jQuery ajax从多个文件上传框上传图像

[英]Upload images from multiple file upload boxes using jQuery ajax

I have multiple file upload boxes in a single HTML form and in each file box there is an associated upload button and a div container. 我在一个HTML表单中有多个文件上传框,并且在每个文件框中都有一个关联的上传按钮和一个div容器。 Clicking the upload button should upload the respective file via AJAX (jQuery). 单击上传按钮应通过AJAX(jQuery)上传相应的文件。 I revered various questions and blogs where there is always a one file upload with one submit button. 我很喜欢各种问题和博客,那里总是只有一个提交文件和一个提交按钮。 But my question here is how to upload the selected file on a click event on a button without submitting the entire form. 但是我的问题是如何在不提交整个表单的情况下,在按钮的单击事件上上传所选文件。 Is that possible? 那可能吗?

I put a mock HTML code and the corresponding jsfiddle also 我放了一个模拟HTML代码和相应的jsfiddle

<form id='parent-form' action='complete.php'>
    <div>
        <input type='file' name='img1'/>
        <input type='button' value='upload' name='btnimg1' />
    </div>
    <div>
        <input type='file' name='img2'/>
        <input type='button' value='upload' name='btnimg2' />
    </div>
    <div>
        <input type='file' name='img3'/>
        <input type='button' value='upload' name='btnimg3' />
    </div>
    <br/>
    <input type='submit' value='Complete' />
</form>

http://jsfiddle.net/z1bj4v9t/ http://jsfiddle.net/z1bj4v9t/

Uploading files via AJAX is not support in all browsers, but in modern browsers it is possible. 并非在所有浏览器中都支持通过AJAX上传文件,但是在现代浏览器中是可以的。 You'll need to attach a listener to the buttons next to the file fields, or you can upload multiple images at once. 您需要在文件字段旁边的按钮上附加一个侦听器,或者您一次可以上传多张图片。

Take a look at this answer: https://stackoverflow.com/a/20462576/1997303 看一下这个答案: https : //stackoverflow.com/a/20462576/1997303

Well this is a thing: 好吧,这是一件事:

<form>
    <input type="file" multiple>
</form>

In HTML5 compatible browsers, add the "multiple" property to the <input type="file"> . 在与HTML5兼容的浏览器中,将“ multiple”属性添加到<input type="file"> A similar question was asked here . 这里也提出了类似的问题

I believe the fallback option is to actually use a Flash (of all things) plugin to force your input to be able to grab multiple files. 我相信,后备选项是实际上使用Flash(所有事物)插件来强制您的输入能够捕获多个文件。 At least this was how Facebook and others were doing it a couple years ago when I looked it up. 至少几年前,当我查找Facebook时,这就是Facebook和其他人的做法。

Edit to address your comment: 编辑以发表您的评论:

I might do something like: 我可能会做类似的事情:

$('[name^="btnimg"]').click(function(){
    /* AJAX sexiness here */
    return false; // IMPORTANT... keeps the main form from submitting
}

Then when submitting the main form, grab the data passed from AJAX uploads. 然后,在提交主表单时,获取从AJAX上传中传递的数据。

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

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