SpringMVC MultipartFile文件上传

关于springmvc的MultipartFile文件上传问题,我在这里贴上代码


jsp页面

 <input type="file" value="上传文件" name="file" /> 

控制层

@RequestMapping("/edit")
@ResponseBody public Json edit(Tgoodcategory goodCategory,HttpServletRequest request,@RequestParam(value="file",required=false) MultipartFile file) {
	if(file!=null){
		String s=UploadFile.loadPicture(file,"cpsm",request);
		goodCategory.setInstruction("file/"+s);
	}
	Json j = new Json();
	try{
		j.setSuccess(true);
		j.setObj(goodCategoryService.edit(goodCategory));
		j.setMsg("编辑成功!");
	}catch(Exception ex){
		ex.printStackTrace();
		j.setMsg("编辑失败!");
	}
	return j;

}

文件上传工具类

/**
 * 文件上传
 * @param file 前台文件
 * @param name 存储名前缀
 * @param request HttpServletRequest
 * @return 数据库存储字段名:name+当前时间
*/
public static String loadPicture(MultipartFile file ,String name,HttpServletRequest request){
	String s="";
	SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
	if (!file.isEmpty()) {
		byte[] bytes;
		try {
			bytes = file.getBytes();

			String rootPath = request.getSession().getServletContext().getRealPath("file");
			File dir = new File(rootPath + File.separator);
				
				
			if (!dir.exists()) {
				dir.mkdirs();
			}
				
			//String path=dir.getAbsolutePath() + File.separator + file.getOriginalFilename();
			String[] t=file.getOriginalFilename().split("\\.");
			String pictureType=t[t.length-1];
			String pictureName=name+sdf.format(new Date())+"."+pictureType;
			String path=dir.getAbsolutePath() + File.separator +pictureName;
			s=pictureName;
				
			File serverFile = new File(path);
			BufferedOutputStream stream;
			stream = new BufferedOutputStream(new FileOutputStream(serverFile));
			stream.write(bytes);
			stream.close();
			return pictureName;
			} catch (Exception e) {
				// TODO Auto-generated catch block
				System.out.println("FileLoad Error...:"+e.getMessage());
			}								
	}
	return s;
}



springmvc的配置文件

<bean id="multipartResolver"  
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
        <!-- 默认编码 -->
        <property name="defaultEncoding" value="utf-8" />  
        <!-- 文件大小最大值 -->
        <property name="maxUploadSize" value="10485760000" />  
        <!-- 内存中的最大值 -->
        <property name="maxInMemorySize" value="40960" />  
</bean>





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值