سؤال

I am trying to upload file through ajax but its failing. in below code I am always getting "error occured" alert populated. any help is appreciated. in IE its saying long running script but again fail to upload the image. I tried to upload 19KB file only.

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

    }

}
هل كانت مفيدة؟

المحلول

First of all file upload is not possible through Ajax. You can upload file, without refreshing page by using IFrame.

Check this link

Unrelated to question but helpful for a programmar:

You have used e.preventDefault(); where is the e ?. You should pass it to function in the change event.

Second, once you add correct console.log('error', errorThrown); and see it in the console using tools like firebug. It throws error

component does not have requested interface

This is how you should learn debugging.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top