springMVC 上传文件

<form action="<%=path%>/oper/course/upload" method="post" enctype="multipart/form-data">

 

@RequestMapping(value = "/upload")

public @ResponseBody String upload(HttpServletRequest request, @RequestParam("fileUpload")

MultipartFile fileUpload) throws Exception {

 

JSONObject data = new JSONObject();

//判断是否有文件

if (!fileUpload.isEmpty()) {

try {

String fileName = fileUpload.getOriginalFilename();

// 获取文件后缀

String[] suffixs = fileName.split("\\.");

String suffix = "." + suffixs[suffixs.length - 1];

//判断上传的文件格式是否正确

if ((".xml".indexOf(suffix.toLowerCase()) != -1)) {

byte[] bytes = fileUpload.getBytes();

Integer fileSize = (int) fileUpload.getSize() / 1024;

// 如果文件小于10M,则上传文件,否则提示用户不能超过10M

if (fileSize <= 10240) {

String uploadPath = "upload/" + fileName;

File file = new File(request.getSession().getServletContext().getRealPath("upload"));

file.mkdirs();//创建文件夹

File filePath = new File(request.getSession().getServletContext().getRealPath(uploadPath));

//文件开始上传到服务器上

FileCopyUtils.copy(bytes, filePath);

 

CourseWare course = xmlUtil.wbtDescribe(filePath.toString());

 

List courseList = courseWareService.queryCourseWareId(course.getCourseNumber());

if(courseList!=null&&courseList.size()>0){

//更新数据

courseWareService.upadteCourseWare(course);

}else{

courseWareService.save(course);

}

data.put("statue", 1);

} else {

data.put("statue", 0);

data.put("errMsg ", "上传的文件太大,文件大小不能超过10M");

}

} else {

data.put("statue", 0);

data.put("errMsg ", "上传的文件格式不支持");

}

} catch (IOException e) {

e.printStackTrace();

data.put("statue", 0);

log.error("上传WBT格式错误,请上传正确的wbt文件"+e.getMessage());

}

 

}

return data.toJSONString();

}

你可能感兴趣的:(springMVC)