使用JSP,servlet和ajax上载文件而不设置表单的action属性

时间:2015-04-27 10:07:17

标签: java ajax jsp servlets httpresponse

我正在尝试使用JSP和servlet上传文件。 这是JSP代码:

 <script type="text/javascript">
 function UploadFile() {
    var paramater = "hello";
    $.post('fileUploadServlet', {param : paramater});
}
</script>
<form action="" method="POST" enctype="multipart/form-data">
    <input type="file" name="datafile" size="50" /> <br /> 
    <input type="submit" value="Upload File" onclick="UploadFile()" />
    <input type="hidden" name="type" value="upload">
</form>

servlet代码如下所示:

public class fileUploadServlet 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 doGet(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
    // Check that we have a file upload request
    System.out.println(request.getContentType());
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    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")));
    // String uploadFolder = System.getProperty("java.io.tmpdir") +
    // File.separator + UUID.randomUUID().toString() + File.separator +
    // "abc.xml";
    // FileUtils.createFileParent(uploadFolder);

    // constructs the folder where uploaded file will be stored
    String uploadFolder = "C:\\Users\\IBM_ADMIN\\workspace_new\\Trees\\WebContent\\UploadedFiles";

    // String uploadFolder = getServletContext().getRealPath("")
    // + File.separator + DATA_DIRECTORY;

    System.out.println("uploadFolder : " + uploadFolder);

    // 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);
                response.getWriter().write("Work done");
            }
        }

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

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

}

当我调试时,我观察到它在行中失败了如果(!isMultipart)并且servlet返回并且无法上传任何文件。 我试图打印request.getContentType(),它打印为application / x-www-form-urlencoded; charset = UTF-8而不是multipart / form-data。 我哪里错了?

提前致谢!

2 个答案:

答案 0 :(得分:0)

在定义Servlet之前添加以下代码行,以处理必须使用Multipart注释的多部分/表单数据提交

import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;

@MultipartConfig(fileSizeThreshold = 1024 * 1024 * 2, // 2MB maxFileSize = 1024 * 1024 * 10, // 10MB maxRequestSize = 1024 * 1024 * 50)

@WebServlet("/ServletName")

答案 1 :(得分:0)

如果您使用Servlet 3.0,则可以使用“Part”类来获取多部分内容。多部分对该表单中的所有内容进行编码,以使用您首先要解密的内容。