1. 程式人生 > >jsp檔案上傳與java檔案儲存到tomcat

jsp檔案上傳與java檔案儲存到tomcat

jsp 部分程式碼:

<form id="inputForm" action="${pageContext.request.contextPath}${fns:getFrontPath()}/background" method="post"  enctype="multipart/form-data" >
<label><input checked="checked" name="indexImg" type="radio" value="banner" />banner</label> 
<label><input name="indexImg" type="radio" value="mw" />mw</label> 
<label><input name="indexImg" type="radio" value="bp" />bp</label> 
<label><input name="indexImg" type="radio" value="feng" />feng</label> 
<input class="file" type = "file" name = "file"/>
<input class="save" type = "submit" vlaue = "儲存"/>
</form>

java部分程式碼:

@RequestMapping(value = "background")
public String saveBackground(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request,ModelMap model, String indexImg){

        String imagePath = request.getSession().getServletContext().getRealPath("/") + "/static/images/";
        if("banner".equals(indexImg)) {
        imagePath += "index-banner.png";
        }
        if("mw".equals(indexImg)) {
        imagePath += "index-img1.png";
        }
        if("bp".equals(indexImg)) {
        imagePath += "index-img2.png";
        }
        if("feng".equals(indexImg)) {
        imagePath += "index-img3.png";
        }
        File targetFile = new File(imagePath);
        if(!targetFile.exists()){  
        try {
targetFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
        }  
  
        //儲存  
        try {  
            file.transferTo(targetFile);  
        } catch (Exception e) {  
            e.printStackTrace();  
        } 
        model.addAttribute("img", "ok");
        return "redirect:" + adminPath;
}