如何使用JSP / Servlet和Ajax将文件上传到服务器?

时间:2011-08-02 15:01:13

标签: jquery ajax jsp servlets file-upload

我正在创建一个JSP / Servlet Web应用程序,我想通过Ajax将文件上传到Servlet。我该怎么做呢?我正在使用jQuery。

到目前为止我已经完成了:

<form class="upload-box">
    <input type="file" id="file" name="file1" />
    <span id="upload-error" class="error" />
    <input type="submit" id="upload-button" value="upload" />
</form>

使用这个jQuery:

$(document).on("#upload-button", "click", function() {
    $.ajax({
        type: "POST",
        url: "/Upload",
        async: true,
        data: $(".upload-box").serialize(),
        contentType: "multipart/form-data",
        processData: false,
        success: function(msg) {
            alert("File has been uploaded successfully");
        },
        error:function(msg) {
            $("#upload-error").html("Couldn't upload file");
        }
    });
});

但是,它似乎不会发送文件内容。

4 个答案:

答案 0 :(得分:21)

到目前为止,从jQuery使用的当前XMLHttpRequest版本1开始,使用JavaScript通过XMLHttpRequest上传文件是。常见的解决方法是让JavaScript创建一个隐藏的<iframe>并将表单提交给它,以便创建它以异步方式发生的印象。这也正是大多数jQuery文件上传插件正在执行的操作,例如jQuery Form pluginexample here)。

假设您的带有HTML表单的JSP以这样的方式被重写,以便在客户端禁用JS时(现在已经......) ,如下所示:

<form id="upload-form" class="upload-box" action="/Upload" method="post" enctype="multipart/form-data">
    <input type="file" id="file" name="file1" />
    <span id="upload-error" class="error">${uploadError}</span>
    <input type="submit" id="upload-button" value="upload" />
</form>

然后在jQuery Form插件的帮助下只需

<script src="jquery.js"></script>
<script src="jquery.form.js"></script>
<script>
    $(function() {
        $('#upload-form').ajaxForm({
            success: function(msg) {
                alert("File has been uploaded successfully");
            },
            error: function(msg) {
                $("#upload-error").text("Couldn't upload file");
            }
        });
    });
</script>

对于servlet方面,这里不需要做任何特殊的事情。只需像不使用Ajax时那样实现它:How to upload files to server using JSP/Servlet?

如果X-Requested-With标头等于XMLHttpRequest,您只需要在servlet中进行额外检查,这样您就可以知道客户端具有何种响应方式。 JS禁用(截至目前,它主要是旧的移动浏览器,它们已禁用JS)。

if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
    // Return ajax response (e.g. write JSON or XML).
} else {
    // Return regular response (e.g. forward to JSP).
}

请注意,相对较新的XMLHttpRequest版本2能够使用新的FileFormData API发送所选文件。另请参阅HTML5 File Upload to Java Servletsending a file as multipart through xmlHttpRequest

答案 1 :(得分:2)

此代码适用于我:

&#13;
&#13;
$('#fileUploader').on('change', uploadFile);


function uploadFile(event)
	{
	    event.stopPropagation(); 
	    event.preventDefault(); 
	    var files = event.target.files; 
	    var data = new FormData();
	    $.each(files, function(key, value)
	    {
	        data.append(key, value);
	    });
	    postFilesData(data); 
	 }
	
function postFilesData(data)
	{
	 $.ajax({
        url: 'yourUrl',
        type: 'POST',
        data: data,
        cache: false,
        dataType: 'json',
        processData: false, 
        contentType: false, 
        success: function(data, textStatus, jqXHR)
        {
        	//success
        },
        error: function(jqXHR, textStatus, errorThrown)
        {
            console.log('ERRORS: ' + textStatus);
        }
	    });
	}
&#13;
<form method="POST" enctype="multipart/form-data">
	<input type="file" name="file" id="fileUploader"/>
</form>
&#13;
&#13;
&#13;

答案 2 :(得分:1)

如果表单只有文件类型输入,如果除了文件类型之外还有其他一些输入,那么@ Monsif的代码效果很好,那么它们就会丢失。因此,不是复制每个表单数据并将它们附加到FormData对象,而是可以将原始表单本身赋予构造函数。

关于@Monsif的代码和https://www.new-bamboo.co.uk/blog/2012/01/10/ridiculously-simple-ajax-uploads-with-formdata/帖子,我推出了以下适用于我的代码。我希望它可以帮助别人。

<script type="text/javascript">
        var files = null; // when files input changes this will be initiliazed.
        $(function() {
            $('#form2Submit').on('submit', uploadFile);
    });

        function uploadFile(event) {
            event.stopPropagation();
            event.preventDefault();
            //var files = files;
            var form = document.getElementById('form2Submit');
            var data = new FormData(form);
            postFilesData(data);
}

        function postFilesData(data) {
            $.ajax({
                url :  'yourUrl',
                type : 'POST',
                data : data,
                cache : false,
                dataType : 'json',
                processData : false,
                contentType : false,
                success : function(data, textStatus, jqXHR) {
                    alert(data);
                },
                error : function(jqXHR, textStatus, errorThrown) {
                    alert('ERRORS: ' + textStatus);
                }
            });
        }
</script>

html代码可以是以下内容:

<form id ="form2Submit" action="yourUrl">
  First name:<br>
  <input type="text" name="firstname" value="Mickey">
  <br>
  Last name:<br>
  <input type="text" name="lastname" value="Mouse">
  <br>
<input id="fileSelect" name="fileSelect[]" type="file" multiple accept=".xml,txt">
<br>
  <input type="submit" value="Submit">
</form>

答案 3 :(得分:-1)

此代码适用于我。

used commons io.jar&amp; commons文件upload.jar和jQuery表单插件

&#13;
&#13;
<script>
    $(function() {
        $('#upload-form').ajaxForm({
            success: function(msg) {
                alert("File has been uploaded successfully");
            },
            error: function(msg) {
                $("#upload-error").text("Couldn't upload file");
            }
        });
    });
</script>
&#13;
<form id="upload-form" class="upload-box" action="upload" method="POST" enctype="multipart/form-data">
    <input type="file" id="file" name="file1" />
    <span id="upload-error" class="error">${uploadError}</span>
    <input type="submit" id="upload-button" value="upload" />
</form>
&#13;
&#13;
&#13;

 boolean isMultipart = ServletFileUpload.isMultipartContent(request);

        if (isMultipart) {
            // Create a factory for disk-based file items
            FileItemFactory factory = new DiskFileItemFactory();

            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);

            try {
                // Parse the request
                List items = upload.parseRequest(request);
                Iterator iterator = items.iterator();
                while (iterator.hasNext()) {
                    FileItem item = (FileItem) iterator.next();
                    if (!item.isFormField()) {
                        String fileName = item.getName();    
                        String root = getServletContext().getRealPath("/");
                        File path = new File(root + "../../web/Images/uploads");
                        if (!path.exists()) {
                            boolean status = path.mkdirs();
                        }

                        File uploadedFile = new File(path + "/" + fileName);
                        System.out.println(uploadedFile.getAbsolutePath());
                        item.write(uploadedFile);
                    }
                }
            } catch (FileUploadException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }



enter code here
相关问题