使用AJAX和servlet上传多个文件

时间:2016-01-09 21:59:01

标签: javascript java jquery ajax servlets

我已经尝试了互联网上几乎所有可用的东西,但似乎没有任何工作。

我有一个HTML5文件阅读器代码,它将从客户端目录var f = $('#fileUpload')[0].files;获取所有文件。接下来我想用AJAX请求将所有这些文件上传到JAVA servlet POST方法。为此我尝试下面的代码 -

var data = new FormData();
        $.each(f, function(key, value)
        {
            data.append(key, value);
        });
postFilesData(data);
//some code..
    function postFilesData(data)
    {
     $.ajax({
        url: 'serv2',
        type: 'POST',
        //enctype: 'multipart/form-data',
        data: data,
        cache: false,
        processData: false, 
        mimetyep: 'multipart/form-data',
        contentType: 'multipart/form-data', 
        success: function(data)
        {
            //success
        },
        error: function(textStatus)
        {
            console.log('ERRORS: ' + textStatus);
        }
        });
    }

servlet代码doPOst方法 -

System.out.println("Hi what request:"+ServletFileUpload.isMultipartContent(request));
        System.out.println("hi bro");
    //  awsUpload.uploadData(foldername);
        System.out.println("outside aws");

        DiskFileItemFactory factory = new DiskFileItemFactory();


        ServletFileUpload upload = new ServletFileUpload(factory);

        String uuidValue = "";
        FileItem itemFile = null;

        try {
            // parses the request's content to extract file data
            List formItems = upload.parseRequest(request);
            Iterator iter = formItems.iterator();

            // iterates over form's fields to get UUID Value
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if (item.isFormField()) {

                }
                // processes only fields that are not form fields
                if (!item.isFormField()) {
                    itemFile = item;
                }
            }
        }
            catch (Exception e) {
                // TODO: handle exception
            }

        //System.out.println(path);
    //  response.sendRedirect(path+"/user"+"/home.html");
    //  System.out.println("done");

        if(itemFile==null)
        {
            System.out.println("File Empty Found");
        }
        System.out.println("The File Name is"+itemFile.getName());
}

HTML code:

<form method="POST" enctype="multipart/form-data" >

        <input type="file" class="input-file" name="file[]" id="fileUpload" 
        onchange="fileChanged();" multiple mozdirectory="" 
        webkitdirectory="" directory=""/> <br/>

它打印“File Empty Found”并在NullPointerException下面的行崩溃。我知道它没有得到任何数据。你能指出一些错误的代码或需要添加的代码缺失。

1 个答案:

答案 0 :(得分:1)

感谢您的回复... !! 要回答@ BalusC的问题,是的,它是分段上传。它进入while循环但没有数据从ajax调用传输,代码刚刚在行System.out.println("The File Name is"+itemFile.getName());处断开,因为没有项目可以获取FileName。我得到的唯一例外是控制台“NullPointerException”和UI控制台(在JS中调试时)“500内部服务器错误” 我能够修复代码,并能够通过AJAX调用将数据传输到Servlet。下面是代码。几乎改变/重构的AJAX调用和servlet代码 -

AJAX请求 -

var fd = new FormData();    
    //fd.append( 'file', $('#fileUpload')[0].files);//.files[0]);

    $.each($('#fileUpload')[0].files, function(k, value)
            {
                fd.append(k, value);
            });

    $.ajax({
      url: 'serv2',
      data: fd,
      processData: false,
      contentType: false,
      type: 'POST',
      success: function(data){
        alert(data);
      }
    });

Servlet code-doPost方法 -

if (!ServletFileUpload.isMultipartContent(request)) {
            PrintWriter writer = response.getWriter();
            writer.println("Request does not contain upload data");
            writer.flush();
            return;
        }
        // configures upload settings
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(THRESHOLD_SIZE);

        ServletFileUpload upload = new ServletFileUpload(factory);
        //upload.setFileSizeMax(MAX_FILE_SIZE);
        //upload.setSizeMax(MAX_REQUEST_SIZE);

        String uuidValue = "";
        FileItem itemFile = null;

        try {
            // parses the request's content to extract file data
            List formItems = upload.parseRequest(request);
            Iterator iter = formItems.iterator();

            // iterates over form's fields to get UUID Value
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if (item.isFormField()) {
                    if (item.getFieldName().equalsIgnoreCase(UUID_STRING)) {
                        uuidValue = item.getString();
                    }
                }
                // processes only fields that are not form fields
                if (!item.isFormField()) {
                    itemFile = item;
                }
            }
            System.out.println("no of items: " + formItems.size());
            System.out.println("FILE NAME IS : "+itemFile.getName());
    }
}

我能够打印从UI传递的文件对象,这些对象是正确的。谢谢你们的时间.. !! :)