使用servlet在Java上载文件

时间:2009-06-04 09:13:19

标签: java servlets file-upload

我正在使用javazoom上传

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException {
    PrintWriter out = null;
    JOptionPane.showMessageDialog(null, "Lets do this");
    try {
        response.setContentType("text/html;charset=UTF-8");
        try {
            MultipartFormDataRequest dataRequest = new MultipartFormDataRequest(request);
            //get uploaded files
            Hashtable files = dataRequest.getFiles();
            if (!files.isEmpty()) {
                UploadFile uploadFile = (UploadFile) files.get("filename");
                byte[] bytes = uploadFile.getData();
                String s = new String(bytes);

文件总是空着。 有什么帮助吗?


然后我尝试使用Apache Commons FileUpload:

 protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException {
     PrintWriter out = null;

        try {

            response.setContentType("text/html;charset=UTF-8");
            //MultipartFormDataRequest dataRequest = new MultipartFormDataRequest(request);
            //get uploaded files
            FileItemFactory factory = new DiskFileItemFactory();
            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            List files = null;
            try {
                files = upload.parseRequest(request);
            } catch (FileUploadException ex) {
                Logger.getLogger(ProcessUploadItem.class.getName()).log(Level.SEVERE, null, ex);
            }

并且在files = upload.parseRequest(request);

失败了

任何指针?

抱歉,谢谢你:)

3 个答案:

答案 0 :(得分:4)

我建议使用更受欢迎的高级库来执行此操作,例如Apache Commons FileUpload。它更有可能工作,有更好的文档,并有更多的人来帮助你使用它。

答案 1 :(得分:3)

检查发送文件的表单是否具有enctype =“multipart / form-data”定义如下:

<form enctype="multipart/form-data" action="...

其他方式根据RFC1867

永远不会上传文件

答案 2 :(得分:0)

您使用的是其他框架,例如特立尼达还是类似的?它们通常包含用于恢复上载文件的过滤器,因此当进程到达您的服务器时,请求不包含任何附加文件。