java上传文件

1:前台
<tr>
<th>
上传图片:
</th>
<td>
<input type="file" name="myFile" id="myFile" class="textinput" /><span class="validate_required">*</span><span id="span_myFile"></span>
</td>
</tr>
2:在resource下创建common.properties
内容:upload.path=upload
host.url=http\://219.233.185.46\:8090
3:java Controller方法

@SuppressWarnings("unchecked") 
@RequestMapping("/updateCarousel.do") 
public String carouselUpdateHandler(HttpServletRequest request, 
HttpServletResponse response, 
@ModelAttribute("carousel") CarouselImage carousel, 
@RequestParam(value = "myFile", required = false) MultipartFile logoFile, 
ModelMap model) 
throws Exception { 
String action = this.getParameter(request, "action"); 
String id = this.getParameter(request, "id"); 
if (Utils.strIsNull(action)) { 
Map<String, Object> param = new HashMap<String, Object>(); 
param.put("validFlag", KcyglConstants.STATUS_ISVALID_YES); 
CarouselImage carouselList =this.carouselImageService.getCarouselById(id); 
model.put("carouselList",carouselList); 
return "backstage/carouselImage_update"; 
} 

String fileName =logoFile.getOriginalFilename(); 
if(!fileName.equals("")&&fileName!=null){ 
PropertiesLoader loader = new PropertiesLoader("common.properties"); 
String uploadPath = loader.getProperty("upload.path"); 
SimpleDateFormat datef = new SimpleDateFormat("yyyyMMddHHmmssSS"); 
String path = request.getSession().getServletContext().getRealPath( 
uploadPath); 
String fileType = Utils.getFileType(fileName); 
String fName = Utils.getFileName(fileName); 
fileName = subStrForMath(fName + "_" + datef.format(new Date()) + fileType); 

File targetFile = new File(path + "/", fileName); 
if (!targetFile.exists()) { 
targetFile.mkdirs(); 
} 
// 保存文件名至数据库 
carousel.setImageUrl(fileName); 
logoFile.transferTo(targetFile); 
} 
int result = 1; 
try{ 
this.carouselImageService.update(carousel); 
}catch(Exception e){ 
result = 0; 
e.printStackTrace(); 
} 

if(result == 1){ 
model.put("message", "添加轮播图成功!"); 
}else{ 
model.put("message", "添加轮播图失败!"); 
} 

return "result/success"; 
} 

 

 

你可能感兴趣的:(java)