(1)在spring mvc的配置文件中配置:
<bean?id="multipartResolver"?class="org.springframework.web.multipart.commons.CommonsMultipartResolver"><property?name="uploadTempDir"?value="/tmp"?/>?<!--?臨時目錄?-->
<property?name="maxUploadSize"?value="10485760"/>?<!--?10M?-->
</bean>
(2)文件上傳表單和結果展示頁fileupload.jsp:
<%@?page?language="java"?contentType="text/html;?charset=UTF-8"pageEncoding="UTF-8"%>
<%@taglib?prefix="mvc"?uri=".zifangsky.controller;
import?java.io.File;
import?java.io.IOException;
import?javax.servlet..zifangsky.model.User;
import?cn.zifangsky.utils.StringUtile;
@Controller
public?class?UploadController?{
@RequestMapping(value?=?"/form")
public?ModelAndView?form()?{
ModelAndView?modelAndView?=?new?ModelAndView("fileupload",?"user",?new?User());
return?modelAndView;
}
@RequestMapping(value?=?"/upload",?method?=?RequestMethod.POST)
public?ModelAndView?upload(User?user,?@RequestParam("file")?MultipartFile?tmpFile,?HttpServletRequest?request)?{
ModelAndView?modelAndView?=?new?ModelAndView("fileupload");
if?(tmpFile?!=?null)?{
//?獲取物理路徑
String?targetDirectory?=?request.getSession().getServletContext().getRealPath("/uploads");
String?tmpFileName?=?tmpFile.getOriginalFilename();?//?上傳的文件名
int?dot?=?tmpFileName.lastIndexOf('.');
String?ext?=?"";?//文件後綴名
if?((dot?>?-1)?&&?(dot?<?(tmpFileName.length()?-?1)))?{
ext?=?tmpFileName.substring(dot?+?1);
}
//?其他文件格式不處理
if?("png".equalsIgnoreCase(ext)?||?"jpg".equalsIgnoreCase(ext)?||?"gif".equalsIgnoreCase(ext))?{
//?重命名上傳的文件名
String?targetFileName?=?StringUtile.renameFileName(tmpFileName);
//?保存的新文件
File?target?=?new?File(targetDirectory,?targetFileName);
try?{
//?保存文件
FileUtils.copyInputStreamToFile(tmpFile.getInputStream(),?target);
}?catch?(IOException?e)?{
e.printStackTrace();
}
User?u?=?new?User();
u.setUserName(user.getUserName());
u.setLogoSrc(request.getContextPath()?+?"/uploads/"?+?targetFileName);
modelAndView.addObject("u",?u);
}
return?modelAndView;
}
return?modelAndView;
}
}
在上面的upload方法中,為了接收上傳的文件,因此使用了壹個MultipartFile類型的變量來接收上傳的臨時文件,同時為了給文件進行重命名,我調用了壹個renameFileName方法,這個方法的具體內容如下:
/**?*?文件重命名
?*/
public?static?String?renameFileName(String?fileName)?{
String?formatDate?=?new?SimpleDateFormat("yyMMddHHmmss").format(new?Date());?//?當前時間字符串
int?random?=?new?Random().nextInt(10000);
String?extension?=?fileName.substring(fileName.lastIndexOf("."));?//?文件後綴
return?formatDate?+?random?+?extension;
}
註:上面用到的model——User.java:
package?cn.zifangsky.model;public?class?User?{
private?String?userName;?//?用戶名
private?String?logoSrc;?//?頭像地址
public?String?getUserName()?{
return?userName;
}
public?void?setUserName(String?userName)?{
this.userName?=?userName;
}
public?String?getLogoSrc()?{
return?logoSrc;
}
public?void?setLogoSrc(String?logoSrc)?{
this.logoSrc?=?logoSrc;
}
}
至此全部結束
效果如下:
(PS:純手打,望采納)