ファイルのアップロード(apache commons.fileuploadを使用)


jspページ

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>File upload</title>
</head>
<body>
<form name="myform" action="/Fileupload" method="post" enctype="multipart/form-data">
    File:<br>
    <input type="file" name="myfile"><br><br>

    <input type="submit" name="submit" id="submit" value="Commit">
</form>
</body>
</html>

Fileupload.java

public class Fileupload extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {

        try {
            //      
            String uploadPath = getServletContext().getRealPath("/upload"); //            
            //String uploadPath = "F:/excise/web/upload";
            File uploadFile = new File(uploadPath);//      
            //     ,      
            if (!uploadFile.exists()) {
                uploadFile.mkdir();
            }
            //          ,    DiskFileItemFactory
            File tempfile = new File(System.getProperty("java.io.tmpdir"));
            DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
            diskFileItemFactory.setSizeThreshold(4096);  //        4kb
            diskFileItemFactory.setRepository(tempfile);  //      
            ServletFileUpload fu = new ServletFileUpload(diskFileItemFactory); //         
            fu.setHeaderEncoding("utf-8");//    ,     
            fu.setSizeMax(4194304);//      
            List<FileItem> fileItems = fu.parseRequest(request);  //        ,    List
            for (FileItem fi : fileItems) {
                String fileName = fi.getName();
                if (fileName != null) {
                    File fullFile = new File(fileName);
                    File savedFile = new File(uploadPath, fullFile.getName());
                    fi.write(savedFile); //            ,      
                }
            }
            System.out.println("upload succeed");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}