使用JSP、servlet和ajax上传文件而不设置表单的action属性。

3
我可以帮助您进行翻译。这段内容是关于使用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);
}

}

当我调试时,我发现它在if (!isMultipart)一行出错,Servlet 返回并未能上传任何文件。 我尝试打印request.getContentType(),它打印为application/x-www-form-urlencoded;charset=UTF-8而不是multipart/form-data。 我做错了什么? 预先感谢您!

请查看以下答案:链接 - Robby Cornelissen
2个回答

0
在定义Servlet之前添加以下代码行,以处理multipart/form-data提交,您必须使用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") ```

谢谢!但这对我仍然没有用 :( - Ravz

0
如果您使用的是Servlet 3.0,您可以使用"Part"类来获取多部分内容。多部分编码了该表单中的所有内容,要使用这些内容,您首先必须对它们进行解密。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接