struts 2アバターアップロード練習とその注意事項

5332 ワード

1.jspページ
<form id="form" name="form" action="${basePath}nsfw/user_add.action" method="post" enctype="multipart/form-data">


...


<tr>
            <td class="tdBg" width="200px"></td>
            <td>
                <input type="file" name="headImg"/>
            </td>
 </tr>

注:formフォームに追加する enctype=「multipart/form-data」で、顔のinputはfileタイプを使用します
2.actionコントローラ
//    
    private File headImg;
    private String headImgContentType;
    private String headImgFileName;

...

//    
    public String add(){
        try {
            if(user != null){
                System.out.println(headImg);
                //    
                if(headImg != null){
                    //1.     upload/user
                    //           
                    String filePath = ServletActionContext.getServletContext().getRealPath("/upload/user");
                    System.out.println(filePath);
                    String fileName = UUID.randomUUID().toString().replaceAll("-", "")+headImgFileName.substring(headImgFileName.lastIndexOf("."));
                    //    
                    FileUtils.copyFile(headImg, new File(filePath, fileName));
                    
                    //2、        
                    user.setHeadImg("user/" + fileName);
                }
                userService.save(user);
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "list";
    }

注意: private File headImg; の名前はjspページからの名前(name)と一致します
問題:
String filePath = ServletActionContext.getServletContext().getRealPath("/upload/user");      "/upload/user"   "upload/user"  ,           。