Spring MVC 上传文件

Spring 对 Apache Commons FileUpload组件进行了“包装”,包装之后的API超赞!
1.配置MultipartResolver

<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- set the max upload size100MB -->
<property name="maxUploadSize">
<value>104857600</value>
</property>
<property name="maxInMemorySize">
<value>4096</value>
</property>
</bean>


2.继承SimpleFormController,创建文件上传控制器。首先将传来的HttpServletRequest cast成Spring包装好的MultipartHttpServletRequest然后开始向往常一样去传来的参数,对于文件则直接用getFile("fileName")来获得MultipartFile类型,通过调用他的transferTo(File dest)方法存储到指定位置。

public class InfoFormController2 extends SimpleFormController {
private static Log log = LogFactory.getLog(InfoFormController.class);
private String uploadDir;
private InfoDao infoDao;
private TopicDao topicDao;
private ProfileService profileService;

public InfoFormController2(){
// setCommandClass(InfoDTO.class);
setCommandClass(Info.class);
}

protected ModelAndView onSubmit(HttpServletRequest request,
HttpServletResponse response, Object cmd, BindException errors) {

// InfoDTO bean = (InfoDTO) cmd;
Info bean=(Info)cmd;
// byte[] bytes = bean.getFile();

// cast to multipart file so we can get additional information
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
String title = multipartRequest.getParameter("title");
String author= multipartRequest.getParameter("author");
String content = multipartRequest.getParameter("content");
String intro = multipartRequest.getParameter("imgIntro");
String tid = multipartRequest.getParameter("topicId");
String infoid=multipartRequest.getParameter("infoId");
String issue=multipartRequest.getParameter("issue");
MultipartFile file = multipartRequest.getFile("file");
MultipartFile video= multipartRequest.getFile("videoFile");
Info p = new Info();
if(infoid != null){
p.setInfoId(Integer.parseInt(infoid));
}
p.setContent(content);
p.setTitle(title);
p.setAuthor(author);
p.setImgIntro(intro);
p.setTopicId(Integer.parseInt(tid));
p.setPubDate(new java.util.Date());
if (! issue.isEmpty()){
p.setIssue(Integer.parseInt(issue));
}
if (!file.isEmpty()){
// String name=file.getOriginalFilename();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
String name = sdf.format(new Date()) + ".jpg";
p.setImgName(name);
// String uploadDir = this.getUploadDir();
String uploadDir=getServletContext().getRealPath("/")+ "uploaded";
File dirPath = new File(uploadDir);
if (!dirPath.exists()) {
dirPath.mkdirs();
}
String sep = System.getProperty("file.separator");
File uploadedFile = new File(uploadDir + sep + name);
// try {
// FileCopyUtils.copy(bytes, uploadedFile);
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
try {
file.transferTo(uploadedFile);
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
log.info("********************************");
log.info(uploadedFile.getAbsolutePath());
// log.info(bytes.length);
log.info("********************************");
}
if (!video.isEmpty()){
String videoName=video.getOriginalFilename();
p.setVideoName(videoName);
// String uploadDir = this.getUploadDir();
String videoDir=getServletContext().getRealPath("/")+ "video";
File dirPath = new File(videoDir);
if (!dirPath.exists()) {
dirPath.mkdirs();
}
String sep = System.getProperty("file.separator");
File videoFile = new File(videoDir + sep + videoName);
try {
video.transferTo(videoFile);
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
infoDao.saveOrUpdate(p);
return new ModelAndView(new RedirectView("listInfo.htm?pid=1&topicId="+tid));
}

protected Map referenceData(HttpServletRequest request) {
// User u=(User)request.getSession().getAttribute("user");
// int rid=u.getRoleId();
// String hql="from Topic";
// List<Topic> topics = topicDao.findAllTopics();
// List<Topic> topics=topicDao.findTopicByCondition(hql);
// List topics=topicDao.getAll(org.zfzy.model.Topic.class);
Map map = new HashMap();
HttpSession sess=request.getSession();
User u=(User) sess.getAttribute("user");
List topics=profileService.getTopicsByUser(u.getUserId());
map.put("topics", topics);
return map;
}

protected void initBinder(HttpServletRequest request,
ServletRequestDataBinder binder) throws ServletException {
// binder.registerCustomEditor(byte[].class,
// new ByteArrayMultipartFileEditor());
}

public void setInfoDao(InfoDao infoDao) {
this.infoDao = infoDao;
}
public void setTopicDao(TopicDao topicDao) {
this.topicDao = topicDao;
}

public String getUploadDir() {
return uploadDir;
}

public void setUploadDir(String uploadDir) {
this.uploadDir = uploadDir;
}
public void setProfileService(ProfileService profileService) {
this.profileService = profileService;
}
@Override
protected Object formBackingObject(HttpServletRequest request)
throws Exception {
// TODO Auto-generated method stub
// return super.formBackingObject(request);
if (request.getParameter("infoId") != null
&& request.getParameter("infoId").trim().length() > 0) {
Info i=(Info) infoDao.get(Info.class, Integer.parseInt(request.getParameter("infoId")));
// InfoDTO dto=new InfoDTO();

// dto.setInfoId(Integer.parseInt(request.getParameter("infoId")));
// dto.setContent(i.getContent());
// dto.setImgIntro(i.getImgIntro());
// dto.setTitle(i.getTitle());
// dto.setAuthor(i.getAuthor());
// dto.setIssue(i.getIssue());
// dto.setTopicId(new Integer(i.getTopicId()).toString());
// dto.setTopicId(i.getTopicId());
return i;

}
return new Info();
}

}
1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 、4下载使用后,可先查看README.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。 1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合;、下载 4使用后,可先查看README.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。 1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合;、 4下载使用后,可先查看README.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。
1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看README.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。 1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看README.m或d论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。 、1资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看README.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值