struts 1 中的文件上传 Action中的部分代码

转载:http://hi.baidu.com/javajavajava/blog/category
 /**
    * 上传文件
    */
    public ActionForward upload(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        UploadFileForm formBean = (UploadFileForm) form;
               
        //JavaBean
        UploadFile file = new UploadFile();
        if (formBean.getUploadfile() != null
                && formBean.getUploadfile().getFileSize() > 0) {
            //根据当前日期设置上传目录
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd/");
            String pathdir = "images/uploadfile/"
                    + dateFormat.format(new Date());
            //得到服务器上的实际目录
            String realpathdir = request.getSession().getServletContext()
                    .getRealPath(pathdir);
            File savedir = new File(realpathdir);
            //如果目录不存在,则新建
            if (!savedir.exists()) {
                savedir.mkdirs();
            }
            //获取上传文件的扩展名
            String ext = formBean.getUploadfile().getFileName().substring(
                    formBean.getUploadfile().getFileName().lastIndexOf("."));
            //用UUID产生文件名
            String filename = UUID.randomUUID() + ext;
            //生成一个文件输出流,将文件写到指定的目录中
            FileOutputStream fileOutputStream = new FileOutputStream(new File(
                    savedir, filename));
            fileOutputStream.write(formBean.getUploadfile().getFileData());
            fileOutputStream.close();
            //将文件路径保存到数据库
            String filepath = pathdir + filename;
            file.setFilepath(filepath);
            uploadFileService.save(file);
            request.setAttribute("message", "文件上传成功!");
            request.setAttribute("urladdress", SiteUrl.readUrl("control.brand.list"));
        }

你可能感兴趣的:(struts,Blog,ext)