3.Controller层
import java.io.File; import java.util.Date; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import com.appear.rwForklift.common.constant.Constant; import com.appear.rwForklift.common.utils.HtmlUtils; import com.appear.rwForklift.common.utils.Md5; /** * 文件上传 * @author APPEAR * */ @Controller @RequestMapping("fileUpload") public class FileUploadController { private final static Logger log = Logger.getLogger(FileUploadController.class); private final static String SUCCESS = "success"; /** * 图片上传服务器 并返回图片路径 */ @RequestMapping("imgUpload") @ResponseBody public void imgUpload(@RequestParam(value = "file", required = true) MultipartFile file, @RequestParam(value = "folderName", required = true) String folderName, HttpServletRequest request, HttpServletResponse response) { try { // 获取文件名称 String fileName = file.getOriginalFilename(); // 文件名称处理 fileName = handlerFileName(fileName); log.debug("图片上传fileName=" + fileName); File targetFile = new File(Constant.PICTURE_URL + folderName, fileName); if (!targetFile.exists()) { targetFile.mkdirs(); } // 将上传文件写到服务器上指定的文件。 file.transferTo(targetFile); // 设置页面数据 Map<String, Object> jsonMap = new HashMap<String, Object>(); jsonMap.put(SUCCESS, true); jsonMap.put("imgUrl", folderName + File.separator + fileName); HtmlUtils.jsonToHtml(response, jsonMap); } catch (Exception ex) { ex.printStackTrace(); //this.sendFailureMessage(response, SpringmvcExceptionHandler.getExceptionMsg(ex)); } } /** * 文件名称处理 */ private String handlerFileName(String fileName) { // 处理名称start fileName = (new Date()).getTime() + "_" + fileName; // 时间戳+文件名,防止覆盖重名文件 String pre = StringUtils.substringBeforeLast(fileName, "."); String end = StringUtils.substringAfterLast(fileName, "."); fileName = Md5.encrypt(pre) + "." + end;// 用MD5编码文件名,解析附件名称 // 处理名称end return fileName; } }未完,待续…