使用JSP和Jquery上传文件

时间:2015-03-10 09:00:27

标签: java jquery ajax jsp

我有一个要求,我需要使用ajax提交一个包含异步文件输入的表单。以下是我写的代码。但它给了我错误。

的Input.jsp:

<script>
function fileUpload()
{
var formData = $('#myform').serialize();
     $.ajax({
            type: "POST",
            url: "second.jsp",
            async: true,
            data: formData,
            contentType: "multipart/form-data",
            processData: false,
            success: function(msg) {
             alert("File has been uploaded successfully");
            },
            error:function(msg) {
                alert("Failed to upload file");
            }
        });
}
</script>
<form name="myform" id="myform" action="#" method="post" enctype="multipart/form-data">
        <table>
            <tr>
                <td>Slide Name :</td>
                <td><input type="text" name="filename"></td>
            </tr>
            <tr>
                <td>Video File :</td>
                <td><input type="file" name="filecontent"></td>
            </tr>
            <tr>
                <td>Some input :</td>
                <td><input type="radio" name="myinput" value="y" >Yes&nbsp;<input type="radio" name="myinput" value="n">No</td>
            </tr>
            <tr>
                <td colspan="2" align="center"><input type="button" value="Submit" onclick="fileUpload()"></td>
            </tr>
        </table>
    </div>
    </form>

second.jsp

<body>
<%
String fileLocation="D://";
if(ServletFileUpload.isMultipartContent(request)){
                try {
                    List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
                        for (FileItem item : multiparts) {
                            if (item.isFormField()) {
                                String fieldName = item.getFieldName();
                                String fieldValue = item.getString();
                            } else {
                                String fieldName = item.getFieldName();
                                String fileName = FilenameUtils.getName(item.getName());
                                InputStream fileContent = item.getInputStream();
                                String name = new File(item.getName()).getName();
                                item.write(
                                          new File(fileLocation + File.separator + name));    
                            }
                        }
                       System.out.println("File Uploaded Successfully");
                    } catch (Exception ex) {
                       System.out.println("File Upload Failed due to " + ex);
                    }
}
%>
</body>

我得到的错误是:  我在控制台中出现以下错误

File Upload Failed due to org.apache.commons.fileupload.FileUploadException: the request was rejected because no multipart boundary was found

2 个答案:

答案 0 :(得分:1)

我得到了以下适用于我的代码:

function fileUpload()
{
$('#myform').attr('action', 'second.jsp');
    $('#myform').ajaxSubmit({cache:false,success: function a(){
    $('#myform').attr('action', '#');
    }
    });
}

感谢您回复Felix

答案 1 :(得分:0)

在你的代码中缺少这个以捕获文件:

 // Returns the uploaded File
Iterator iter = files.iterator();

FileItem element = (FileItem) iter.next();

完全代码应如下所示。我不会一步到位地做这么多事情。

boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (isMultipart) {
        //Create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);

        //Console Out Starting the Upload progress.
        System.out.println("\n - - - UPLOAD");

        // List of all uploaded Files
        List files = upload.parseRequest(request);

        // Returns the uploaded File
        Iterator iter = files.iterator();

        FileItem element = (FileItem) iter.next();

而不是.serialize();

尝试这样做:

var form = document.getElementById('form-id');
var formData = new FormData(form);