【问题标题】:Ajax file upload is failingAjax 文件上传失败
【发布时间】:2013-12-25 12:53:33
【问题描述】:

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

上传.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);
        }

    }

}

【问题讨论】:

  • console.log('error', errorThown) 获取更详细的服务器响应
  • 记录实际服务器错误的运气。此外,dataFile 对象值是错误的。就做$(this).val()
  • @dcodesmith 不,我的朋友不走运 :-( 。它是一样的......
  • @RajnikantDixit:有一个错字。如果应该是console.log('error', errorThrown);

标签: javascript jquery ajax jsp asyncfileupload


【解决方案1】:

首先不能通过Ajax 上传文件。您可以使用IFrame 上传文件,无需刷新页面。

Check this link

与问题无关,但对程序员有帮助:

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

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

component does not have requested interface

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-21
    • 2012-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-17
    • 2012-10-12
    • 1970-01-01
    相关资源
    最近更新 更多