1

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
2
  • is it mentioned in which line the error is? And whats the reason for sending the form with ajax? Commented Mar 10, 2015 at 9:03
  • 1
    i got a requirement where i need upload some multiple files by multiple times without submitting entire response of current page to server. so i have to go with ajax only. And regarding line number it is just printing above message because i have a print statement in catch block Commented Mar 10, 2015 at 9:11

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

8 Comments

My example is for only one file. you have to go withe for / foreach / while over the List to get more then one.
Still i am getting same error with above code also, i guess the error is because of ajax method and its content type
Try to print the element on console to check if the file is send. Add this: // Converts the File into an Input Strem InputStream is; is = element.getInputStream(); System.out.println(is);
No it is not printing any thing on console with input stream
can you try in ajax -> async=false ?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.