10、文件上传

  1. 引入10、文件上传两个包;
  2. 上传页面表单如下:
    <form action="${pageContext.request.contextPath }/control/department/list_fileUpload.action" method="post" enctype="multipart/form-data">
    文件:<input type="file" name="image">
    <br>
    <input type="submit" value="上传">
  3. 处理上传文件方法如下
    private File image;
    private String imageFileName;//以上setter和getter方法省略
    public String fileUpload() throws IOException {
            String realPath = ServletActionContext.getServletContext().getRealPath("/images");
            System.out.println("realPath=" + realPath);
            if (image != null) {
                File file = new File(realPath, imageFileName);
                if (!file.getParentFile().exists()) {
                    file.getParentFile().mkdirs();
                }
                FileUtils.copyFile(image, file);
                ActionContext.getContext().put("fileMessage""文件上传成功!");
            }
            return "success";
        }
  4. 上传成功!
  5. 命名规则:表单中file的name值与接收文件的File属性命名一致;
  6. <input type="file" name="uploadImage">  //表单name值
  7. private File uploadImage;//得到上传的文件,与表单名称一直

      privateString uploadImageContentType;//得到文件的类型,前面是表单name值,后面必须是ContentType

      privateString uploadImageFileName;//得到文件的名称,前面是表单name值,后面必须是FileName

  8. 备注:可在struts.xml文件中配置常量限制上传文件大小:
  9. <!-- 限制上传文件大小,注上传大文件的话必须通过应用程序实现,如视频网站安装的浏览器插件即是通过socket编程的应用程序 -->
        <constant name="struts.multipart.maxSize" value="107015454096"/>