需要插件:ajaxfileupload.js commons-fileupload-1.3.1.jar
web端:
<form id="saveForm" method="post" enctype="multipart/form-data"> <label>广告图片:</label><input type="file" id="image1" name="image1" data-options="required:true" /> <img src="../../imgSrc/aaaaaa.jpg" id="img" width="100px",height="100px"/> <input type="button" id="sub" value="上传"/> </form>
<script type="text/javascript"> $(function(){ $("#sub").click(function(){ $.ajaxFileUpload({ url:'upload.do', secureuri:false, fileElementId:'image1',//file标签的id dataType: 'json',//返回数据的类型 success: function (data) { $("#img").attr("src","../../imgSrc/"+data); }, }); }); }); </script>
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:
<Host appBase="webapps" autoDeploy="true" name="localhost" unpackWARs="true"> <Context docBase="D:\upload" path="/imgSrc"/>