JSP Java使用io.common上传文件问题

时间:2013-10-31 20:12:02

标签: java jsp servlets apache-commons-io

我遇到了common-io-2.4的问题,其中FileItemFactory似乎没有方法setReposity。我使用了Apache网站上的代码(Apache File Upload)。这是相当令人愤怒的,因为我看到其他人使用它没有问题。我已经在我的项目中包含了jar文件,并且我不会从库中获取其他对象的错误,只是那个。 好像它没有得到所有的方法。

有什么想法吗?这是我的代码,我在Netbeans中编写它

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.tomcat.util.http.fileupload.FileItem;

import org.apache.tomcat.util.http.fileupload.FileItemFactory;
import org.apache.tomcat.util.http.fileupload.FileUploadException;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;


/**
 *
 * @author Harry
 */
public class FileUpload extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();


        if(ServletFileUpload.isMultipartContent(request)){ // checks if it is an upload request;
            // Create a factory for disk-based file items
            FileItemFactory factory = new DiskFileItemFactory();

            // Configure a repository (to ensure a secure temp location is used)
            ServletContext servletContext = this.getServletConfig().getServletContext();
            File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
            factory.setReposity(repository);


            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            try{
                // Parse the request
               List<FileItem> items = upload.parseRequest(request);  // this creates fileItems, which i then need to loop through and write each one to the file. 


            }catch(FileUploadException ex){
                System.out.println("Failed to upload file");
            }


        }
        else{
            response.sendRedirect("UserHome.jsp");
        }

    }

这个对象

FileItemFactory

似乎没有方法setReposity或许多其他方法。我不知道为什么?

也许我只是错过了一些简单的东西? 任何帮助都会很棒!干杯!

1 个答案:

答案 0 :(得分:0)

发现该示例使用了FileItemFactory,但发现如果将其切换到DiskFileItemFactory,则可以访问这些方法。