关于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>