codewriter
codewriter

Reputation: 87

File upload using JSP and Jquery

I got a requirement where i need submit a form which contains file input asynchronously using ajax. Following is the code i written. but it is giving me error.

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>

Error i am getting is: i am getting following error in console

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

Upvotes: 1

Views: 3757

Answers (2)

codewriter
codewriter

Reputation: 87

I got following code which is working fine for me:

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

Thanks for your response Felix

Upvotes: 1

Felix
Felix

Reputation: 5619

In your code is missing this to catch the file:

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

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

Fully code should look like this. I wouldn't do such many things in one step.

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();

Instead of the .serialize();

try to do this:

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

Upvotes: 0

Related Questions