1、js代码
$(function(){ $('#upfileID').change(function(){ $.ajaxFileUpload({ url: '/upload/image',type: 'post',secureuri: false,//一般设置为false fileElementId: 'upfileID',// 上传文件的id属性名 dataType: 'text',//返回值类型,一般设置为json、application/json success: function(data,status){ //alert(data); $('#imgSrc').val(data); $('#imgv').html('<img src="'+data+'" style="max-width:80px">'); },error: function(data,status,e){ alert(e); } }); }) })
2、HTML代码
//引入ajaxFileUpload <script type="text/javascript" src="ajaxfileupload.js"></script> <input type="file" id="upfileID" name="upfile" class="can-file">
4、applicationContext.xml添加以下配置
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />
5、java代码
@RequestMapping("image") public void image(HttpServletRequest request,HttpServletResponse response,@RequestParam("upfile") MultipartFile upfile){ String originalFilename = upfile.getOriginalFilename(); // System.out.println("文件原名: " + originalFilename); // System.out.println("文件名称: " + upfile.getName()); // System.out.println("文件长度: " + upfile.getSize()); // System.out.println("文件类型: " + upfile.getContentType()); String realPath = request.getSession().getServletContext().getRealPath("/resources/upload"); File file = new File(realPath); if(!file.exists()) file.mkdirs(); try { upfile.transferTo(new File(realPath,originalFilename)); } catch (IOException e) { e.printStackTrace(); } //设置响应给前台内容的数据格式 // response.setContentType("text/plain; charset=UTF-8"); renderText(request.getContextPath() + "/resources/upload/" + originalFilename,response); }原文链接:https://www.f2er.com/ajax/164583.html