controller:
@RequestMapping("/bannerAd/create.do")
public String create(HttpServletRequest request, @RequestParam("bannerFile") MultipartFile bannerFile ) throws Exception {
if (!isLoggedIn(request)){
return "redirect:/logout.do";
}
String fileName = "";
if (bannerFile != null && !bannerFile.isEmpty()) {
String uploadPath = request.getSession().getServletContext().getRealPath("/upload/banners");
fileName = UploadUtils.uploadFile(bannerFile, uploadPath);
}
BannerAdDTO bannerAd = new BannerAdDTO();
bannerAd.setFileUrl(fileName);
..........................
bannerAdService.createBannerAd(bannerAd);
return "redirect:/bannerAd/list.do";
}
Jsp:
<form id="formBannerAd" method="post" enctype="multipart/form-data" action="<c:url value='/bannerAd/create.do'/>">
<dl>
<dt>
<label for="bannerFile">Banner File : </label>
</dt>
<dd>
<input id="bannerFile" name="bannerFile " type="file"/>
</dd>
..............................
</dl>
<div class="buttons">
<input type="button" value="Create" οnclick="save();"/>
<input type="button" value="Cancel" οnclick="#"/>
</div>
</form>
upload util:
public static String uploadFile(MultipartFile cFile, String uploadPath) throws Exception {
Assert.notNull(cFile, "cFile must not be null");
Assert.notNull(uploadPath, "moduleName must not be null");
String result = "";
if (cFile != null) {
if (!fileExists(uploadPath)) {
makePath(uploadPath);
}
String fileName = generateFileName(cFile.getOriginalFilename());
String fullName = uploadPath + File.separator + fileName;
DataOutputStream out = new DataOutputStream(new FileOutputStream(fullName));
InputStream is = null;
try {
is = cFile.getInputStream();
byte[] buffer = cFile.getBytes();
while (is.read(buffer) > 0) {
out.write(buffer);
}
result = fileName;
} catch (IOException e) {
e.printStackTrace();
return "";
} finally {
if (null != is) {
is.close();
}
if (null != out) {
out.close();
}
}
}
return result;
}
配置文件:action-servlet.xml
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding">
<value>utf-8</value>
</property>
</bean>