码上敲享录 > Spring框架常见问题详解分享 > springmvc上传文件源码分享

springmvc上传文件源码分享

上一章章节目录下一章 2019-03-31已有1441人阅读 评论(0)

springmvc上传文件源码分享


解决方法:

1.springmvc的配置文件添加:

<!-- 上传文件拦截,设置最大上传文件大小   100M=10*1024*1024(B)=1048576000 bytes -->  

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  

   <property name="maxUploadSize" value="1048576000" />  

</bean>

2.核心方法

@RequestMapping("/upload")

public void toUpload(@RequestParam("file") CommonsMultipartFile[] files,HttpServletRequest request,HttpServletResponse response) throws Exception{

HashMap<String, Object> context = new HashMap<String, Object>();

try{

for(CommonsMultipartFile file:files){

String dir = request.getSession().getServletContext().getRealPath("/")+"upload/";

File dirFile = new File(dir);

//如果路径不存在,新建

if(!dirFile.exists()&&!dirFile.isDirectory()) {

dirFile.mkdirs();

}

String path=dir+"/"+file.getOriginalFilename();

File newFile=new File(path);

        //通过CommonsMultipartFile的方法直接写文件(注意这个时候)

        file.transferTo(newFile);

}

String jsonString = JSONUtil.toJSONString(context);

response.setContentType("text/html;charset=utf-8");

response.getWriter().write(jsonString);

} catch (Exception e) {

//上传异常,删除临时文件

context.put("state", "fail");

String jsonString = JSONUtil.toJSONString(context);

response.setContentType("text/html;charset=utf-8");

response.getWriter().write(jsonString);

}

   

}


向大家推荐《Activiti工作流实战教程》:https://xiaozhuanlan.com/activiti
0

有建议,请留言!

  • *您的姓名:

  • *所在城市:

  • *您的联系电话:

    *您的QQ:

  • 咨询问题:

  • 提 交