使用commons-fileupload实现文件上传示例

step1 设置表单的enctype属性

<form action="upload" method="post" enctype="mutipart/form-data"></form>

step2 在服务器端,不能使用request.getParameter方法获得数据,需要调用request.getInputStream来获得InputStream,通过分析这个流来获得表单中的数据。一般都是通过一些工具来帮我们来分析这个流,比如:commons-fileupload.jar。

DiskFileItemFactory dfif = new DiskFileItemFactory();

ServletFileUpload sfu = new ServletFileUpload(dfif);

try {

    List<FileItem> items = sfu.parseRequest(request);

    for(int i = 0; i < items.size(); i++) {

        FileItem cur = items.get(i);

        if(cur.isFormField()) {

            String value = cur.getString();

            //System.out.println(value);

        } else {

            String path = getServletContext().getRealPath("upload");

            //System.out.println(path);

            String fileName = cur.getName();

            //System.out.println(fileName);

            //System.out.println(File.separator);

            File file = new File(path + File.separator + fileName);

            cur.write(file);

        }

    }

} catch (FileUploadException e) {

    //e.printStackTrace();

    throw new ServletException(e);

}

你可能感兴趣的:(使用commons-fileupload实现文件上传示例)