Ajax文件上传失败

时间:2013-12-25 12:53:33

标签: javascript jquery ajax jsp asyncfileupload

我正在尝试通过ajax上传文件,但失败了。在下面的代码我总是得到“错误发生”警报填充。任何帮助表示赞赏。在IE中它说长时间运行的脚本,但再次无法上传图像。我试图只上传19KB文件。

upload.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
       pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>File Upload</title>
<script src="cssjs/jquery-1.9.1.js"></script>
</head>
<body>

Select file to upload:
<input type="file" name="dataFile" id="fileChooser"/><br/><br/>


<script type="text/javascript">


    $('#fileChooser').change( function(){
        $.ajax({
            url: '/UploadServlet',
            data : { dataFile: document.getElementById('fileChooser') },
            type : 'POST',
            dataType : 'text',
            mimeType: 'multipart/form-data',
            contentType: false,
            cache: false,
            processData:false,
            success: function(data, textStatus, jqXHR) {
                alert("filePath:" + data);
            }, 
            error: function(jqXHR, textStatus, errorThrown) {
                alert("error occured");
            }
        });
        e.preventDefault();
    });

</script>
</body>
</html>

UploadServlet.java

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * Servlet implementation class UploadServlet
 */
public class UploadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    private static final String DATA_DIRECTORY = "data";
    private static final int MAX_MEMORY_SIZE = 1024 * 1024 * 2;
    private static final int MAX_REQUEST_SIZE = 1024 * 1024;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // Check that we have a file upload request
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        PrintWriter out = response.getWriter();
        if (!isMultipart) {
            return;
        }

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

        // Sets the size threshold beyond which files are written directly to
        // disk.
        factory.setSizeThreshold(MAX_MEMORY_SIZE);

        // Sets the directory used to temporarily store files that are larger
        // than the configured size threshold. We use temporary directory for
        // java
        factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

        // constructs the folder where uploaded file will be stored
        String uploadFolder = getServletContext().getRealPath("")
                + File.separator + DATA_DIRECTORY;

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

        // Set overall request size constraint
        upload.setSizeMax(MAX_REQUEST_SIZE);

        try {
            // Parse the request
            List items = upload.parseRequest(request);
            Iterator iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();

                if (!item.isFormField()) {
                    String fileName = new File(item.getName()).getName();
                    String filePath = uploadFolder + File.separator + fileName;
                    File uploadedFile = new File(filePath);
                    System.out.println(filePath);
                    // saves the file to upload directory
                    item.write(uploadedFile);
                    out.write(filePath);
                }
            }

            // displays done.jsp page after upload finished
            //getServletContext().getRequestDispatcher("/done.jsp").forward(
                    //request, response);



        } catch (FileUploadException ex) {
            throw new ServletException(ex);
        } catch (Exception ex) {
            throw new ServletException(ex);
        }

    }

}

1 个答案:

答案 0 :(得分:1)

首先,Ajax无法上传文件。您可以使用IFrame上传文件,而无需刷新页面。

Check this link

无关紧要但对程序员有帮助:

您使用过的e.preventDefault();在哪里?e?您应该将其传递给change事件中的函数。

其次,添加正确的console.log('error', errorThrown);后,使用firebug等工具在控制台中查看。它抛出错误

component does not have requested interface

这是你应该学习调试的方法。