锁定老帖子 主题:使用spring 自带上传文件功能的问题
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
|
|
---|---|
作者 | 正文 |
发表时间:2006-09-07
如果按照spring Framework开放手册上说的,通过在表单对应的bean中定义byte[],那么文件将会全部读入内存,再做处理,这样不但上传速度慢,而且在传大文件的时候就会出现内存耗尽的异常;主要的配置方式和开放手册上说的相同,不同的地方:
1、在表单对应的bean中(Command Class)不要定义byte[] 2、在处理表单请求对应的SimpleFormController中不用定义: protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder);throws ServletException { binder.registerCustomEditor(byte[].class, new ByteArrayMultipartFileEditor(););; } 3、获取文件数据并写入磁盘: public boolean save(String path,MultipartFile file); throws Exception { boolean result = false; if(file != null && !file.isEmpty();); { String fullPath = path + file.getOriginalFilename();; DataOutputStream out = null; InputStream is = null; try { out = new DataOutputStream(new FileOutputStream(fullPath););; is = file.getInputStream();; byte[] buffer = new byte[1024]; while(is.read(buffer); > 0); { out.write(buffer);; } } finally { if(is != null); { is.close();; } if(out != null); { out.close();; } } result = true; } return result; } 4、多个文件的上传 protected ModelAndView onSubmit(HttpServletRequest request,HttpServletResponse response,Object command,BindException errors); throws Exception { MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest);request; for(Iterator it = multipartRequest.getFileNames();;it.hasNext();;); { String key = (String);it.next();; MultipartFile file = multipartRequest.getFile(key);; save(path,file);; } //....... 以上处理: 1、增加上传多个文件的处理 2、采用MultipartFile这样既可以用Commons-Upload组件,也可以用COS上传组件,只要在Spring配置中声明一下即可。 通过如上的方式,文件上传速度也比较快,而且可以上传大文件,服务器的内存和CPU消耗量都不高! |
|
返回顶楼 | |
发表时间:2006-09-13
sping的CosMutlipartResquest还存在问题就是上传的文件名如果是中文的话,不能正常显示。
|
|
返回顶楼 | |
发表时间:2006-09-14
mmmagice 写道 sping的CosMutlipartResquest还存在问题就是上传的文件名如果是中文的话,不能正常显示。 我现在的做法是表单中有个隐藏域,当文件选择后,保存用户选择的文件名,然后一起提交上去来处理它的。:(
|
|
返回顶楼 | |