一、jsp页面
js下载 :
http://download.csdn.net/detail/longtingjing/9725858
js引用:
<script src="/assets/js/jquery.min.js"></script> <script src="/js/ajaxfileupload.js"></script>
<div class="am-g am-margin-top-sm"> <div class="am-u-sm-4 am-u-md-2 am-text-right"> 图片: </div> <div class="am-u-sm-8 am-u-md-4 am-u-end"> <div id="wait_loading" style="padding: 50px 0 0 0;display:none;"> <div style="width: 10px;margin: 0 auto;"><img src="/imgs/loading.gif"/></div> <br></br> <div style="width: 120px;margin: 0 auto;"><span>请稍等...</span></div> <br></br> </div> <input type="hidden" id="imgUrl" name="imgUrl" value=""> <img id="imgshow" style="width:130; height=:120;display:none;" src=" "/> <div class="am-form-group"> <input type="file" id="file" name="file"> <input type="hidden" id="flag" name="flag" value="ajax文件上传"/> <input type="button" id="btnUpload" onclick="ajaxFileUpload()" value="上传图片" /> </div> </div>
js代码:
function ajaxFileUpload() { // 开始上传文件时显示一个图片 $("#wait_loading").show(); var elementIds=["flag"]; //flag为id、name属性名 $.ajaxFileUpload({ url: '/confMana/upload.html',type: 'post',secureuri: false,//一般设置为false fileElementId: 'file',// 上传文件的id、name属性名 dataType: 'json',//返回值类型,一般设置为json、application/json elementIds: elementIds,//传递参数到服务器 success: function(data,status){ data= $.parseJSON( data ); if(data.success){ $("#wait_loading").hide(); $("#imgUrl").val(data.data.imgUrl); $("#imgshow").attr("src",data.data.imgUrl); $("#imgshow").css("display","block"); alert("上传成功!"); }else{ $("#wait_loading").hide(); alert("上传失败!"); } },error: function(data,status,e){ $("#wait_loading").hide(); alert("请求失败!"); } }); }
二、conntroller
@RequestMapping(value="/confMana/upload.html",method = RequestMethod.POST) public @ResponseBody String uploadForApp(HttpServletRequest request,@RequestParam("file") MultipartFile file) throws IllegalStateException,IOException { String relPathOfSavedDir="/uploads/app/"; try { File savedDir = prepareSavedDir(request,relPathOfSavedDir); String savedFileName=getSavedFileName(file.getOriginalFilename()); file.transferTo(new File(savedDir,savedFileName)); String imgUrl=relPathOfSavedDir+savedFileName; Map<String,Object> map=new HashMap<>(); map.put("imgUrl",imgUrl); return toObjJson(map); } catch (Exception e) { return null; } } private File prepareSavedDir(HttpServletRequest request,String relativePath) throws Exception{ File dir=new File(request.getSession().getServletContext().getRealPath(relativePath)); if(!dir.exists()){ if(!dir.mkdirs()){ throw new Exception("创建保存目录失败"); } } return dir; } private String getSavedFileName(String origFileName){ return RandomStringUtils.randomNumeric(8)+"."+FilenameUtils.getExtension(origFileName); }如果出现上传进不了success请参照:
http://blog.csdn.net/qq_32588349/article/details/52056283
原文链接:https://www.f2er.com/springmvc/161534.html