需要插件:ajaxfileupload.js commons-fileupload-1.3.1.jar
web端:java后台:
@RequestMapping("upload") @ResponseBody public String upload(@RequestParam("image1") MultipartFile file,HttpServletRequest req){// String saveFilePath = req.getServletContext().getRealPath("/WEB-INF/upload"); String saveFilePath=Constant.savePath; try { if (!file.isEmpty()) { // 获取图片的文件名 String fileName = file.getOriginalFilename(); // 获取图片的扩展名 String extensionName = fileName .substring(fileName.lastIndexOf(".") + 1); // 新的图片文件名 = 获取时间戳+"."图片扩展名 String newFileName = String.valueOf(System.currentTimeMillis()) + "." + extensionName; ImgUtils.saveFile(newFileName, file, saveFilePath); return newFileName; }else{ return "exception"; } } catch (Exception e) { e.printStackTrace(); return "Exception"; } }
public static void saveFile(String newFileName, MultipartFile filedata,String saveFilePath) { // TODO Auto-generated method stub // 根据配置文件获取服务器图片存放路径 /* 构建文件目录 */ File fileDir = new File(saveFilePath); if (!fileDir.exists()) { fileDir.mkdirs(); } try { FileOutputStream out = new FileOutputStream(saveFilePath + "\\" + newFileName); // 写入文件 out.write(filedata.getBytes()); out.flush(); out.close(); } catch (Exception e) { e.printStackTrace(); } }
tomcat: