使用ajax post上传文件而无需刷新页面

5

我有一个页面文件 file-upload.jsp,其中包含以下代码片段:

 <form action="" id="frmupload" name="frmupload" method="post" enctype="multipart/form-data">
     <input type="file" id="upload_file" name="upload_file" multiple="" />
     <input type="submit" value="Update" />
 </form>

我有两个问题:
  1. The moment I select some files, i.e the onchange event of the input type file, the file(s) should get uploaded.

    I have a Java page that receives multipart request parameter and uploads the file to the said location. My problem is the form submission onchange, so that the Java file can proceed with further operations.

    I googled and went through lot of articles. Some say it's not possible to upload files directly via Ajax, some say submit the form to an iframe via Ajax/jQuery.

    I tried a lot of code from internet, such as this:

    $(document).ready(function(){
        $('upload_file').change(function(){
            var data = new FormData();
            data.append('file', $(this[0].files[0]));
            $.ajax({
                url: 'photo.jsp',
                type: 'post',
                contentType: attr('enctype', "multipart/form-data"),
                data: data,
                success: function(data){
                    alert(data);
                }
            })
        });
    });
    

    but could not get the expected results.

  2. I also need a progress bar for the upload operation.

3个回答

4

2

既然您已经在使用jQuery,我建议您使用jQuery表单插件,它可以让您通过AJAX上传表单,即使表单包含file输入。

该网站上有一个示例可用,展示了如何显示进度条。


你展示的例子使用了ajax,但我想要的是像Facebook或邮箱中看到的文件上传方式,即在选择文件后立即开始上传,并在页面上预览文件,无需按提交按钮。当一切准备就绪时,我希望按下提交按钮以实际进行上传。 - Cyber Dude
我提供的jQuery代码只是我尝试过的众多方法之一。欢迎使用其他方式来实现相同的功能。 - Cyber Dude


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接