原文鏈接:http://apps.hi.baidu.com/share/detail/34190740
jsp頁面:
<form action="upload.do" method="post" enctype="multipart/form-data">
<table border="1">
<tr>
<td>名稱:</td>
<td><input type="text" id="name" name="name"></td>
</tr>
<tr>
<td>路徑</td>
<td><input type="file" id="file" name="file"/></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="上傳"/></td>
</tr>
</table>
</form>
----------------------------------------------------------------------------
public ModelAndView handleRequest(HttpServletRequest arg0,
HttpServletResponse arg1) throws Exception {
//轉(zhuǎn)型為MultipartHttpRequest
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest)arg0;
//根據(jù)前臺的name名稱得到上傳的文件
MultipartFile file = multipartRequest.getFile("file");
// 獲得文件名:
String realFileName = file.getOriginalFilename();
System.out.println("獲得文件名:"+realFileName);
//獲取路徑
String ctxPath = arg0.getContextPath();
ctxPath = arg0.getSession().getServletContext().getRealPath("/")+"\\"+"images\\";
System.out.println("路徑:"+ctxPath);
// 創(chuàng)建文件
File dirPath = new File(ctxPath);
if(!dirPath.exists())
{
dirPath.mkdir();
}
File uploadFile = new File(ctxPath+realFileName);
//
FileCopyUtils.copy(file.getBytes(), uploadFile);
return null;
}
-----------------------------------------------------------------------
XML文件里配置上傳文件的大小
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="1048576"/>
<property name="maxInMemorySize" value="4096"/>
</bean>
--------------------------------------------------------
切記要---添加commons-fileupload-1.2.jar,,添加commons-io-1.3.1.jar
|