springMVC结合ajaxfileupload.js实现图片的上传及时显示

来源:互联网 发布:别人羡慕的生活知乎 编辑:程序博客网 时间:2024/05/21 09:30
<script type="text/javascript">  


function ajaxFileUpload(){  
//开始上传文件时显示一个图片,文件上传完成将图片隐藏  
 $(".pic").ajaxStart(function(){$(this).show();}).ajaxComplete(function(){$(this).hide();});  
 //执行上传文件操作的函数  
   $.ajaxFileUpload({   
  //处理文件上传操作的服务器端地址(可以传参数,已亲测可用)  
  url:'<%=request.getContextPath()%>/financecompanycontroller/projectPic.action',  
   secureuri:false,                       //是否启用安全提交,默认为false   
     fileElementId:'projectPic',           //文件选择框的id属性  
       dataType:'text',                       //服务器返回的格式,可以是json或xml等  
            success:function(data, status){        //服务器响应成功时的处理函数  


            data = data.replace("<PRE>", '');  //ajaxFileUpload会对服务器响应回来的text内容加上<pre>text</pre>前后缀  


            data = data.replace("</PRE>", '');  


             data = data.replace("<pre>", '');  


            data = data.replace("</pre>", ''); //本例中设定上传文件完毕后,服务端会返回给前台[0`filepath]  


             if(data.substring(0, 1) == 0){     //0表示上传成功(后跟上传后的文件路径),1表示失败(后跟失败描述) 
            
                $("img#pic").attr("src", data.substring(2));  
                var i=data.lastIndexOf("/")-7;
                var j=data.length;
                var g=data.substring(i,j);
              //  alert("g:"+g);
                $('#projectPicPath').val(g);


                 $('#result').html("图片上传成功<br/>");  
           }else{  


                 $('#result').html('图片上传失败,请重试!!');  


            }  


         },  


          error:function(data, status, e){ //服务器响应失败时的处理函数  


            $('#result').html('图片上传失败,请重试!!');  
  }  
  });  

 }  


 </script>  

<form name="form" method="post" enctype="multipart/form-data">
<div class="transfer">
<div class="transfer_cont5">

<div class="l_project_view">
<h4>发布项目</h4>
<dl class="l_project_details">
<dt><img name="project_pic"  id="pic" src="<%=request.getContextPath()%>/images/ih-front/pic7.jpg" title="化工贸易企业产品采购化工贸易企业产品采购化工贸易企业产品采购化工贸易企业产品采购化工贸易企业产品采购"/>
<span>

   <input type="file" name="file" id="projectPic" /><input value="文件上传" type="button" onclick="javascript:ajaxFileUpload()"/>
                                </span>
</dt>

<font>企业编号:</font><span><input  class="l_text260" type="text" name="companyCode" value="<%=cVo.getOrgcode()%>" /></span><br />
<font>融资金额:</font><span><input  name="financing_amount" class="l_text260" type="text" value="" /></span><br />
<font>年化收益:</font><span><input name="annual_yield"  class="l_text260" type="text" value=""  onblur="javascript:dataValidate()"/></span><br />
<font>还款日期:</font><span><input class="l_text260"  name="pay_borrow_date" type="text" id="date_input_f" value="2014-12-04" /></span><br />
 
</div>
</div>

</div>
<input type="hidden" class="text_field" name="finance_company_id" inputName="<%=IProjectBaseInfoConstants.TABLE_COLUMN_DISPLAY.get("finance_company_id")%>" value="<%=cVo.getId() %>" maxLength="19" /> 
<input type="hidden" class="text_field" name="guarantor_name" id="guarantor_name" inputName="<%=IProjectBaseInfoConstants.TABLE_COLUMN_DISPLAY.get("guarantor_name")%>" value="" maxLength="19" />
</form>

---------------------------------------------------------------springMVC控制器


/**
* 项目的图片上传
* @param request
* @return
* @throws Exception 
*/
@RequestMapping(value = "projectPic"+ISysConstant.ACTION_SUFFIX,produces = MediaType.APPLICATION_JSON_VALUE)


public String  headimg_upload(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request, ModelMap model,HttpServletResponse response) throws Exception {


String path=request.getSession().getServletContext().getRealPath("upload"); 
String fileName = file.getOriginalFilename();  
//获取保存项目图片
String projectPic = RmGlobalReference.get(ISysConstant.PARAM_TYPE_PATH,ISysConstant.PROJECT_DATA_PATH);
if(StringHelper.isEmpty(projectPic)){
throw new Exception("尚未配置保存项目目录参数!");
}
//获取保存头像url
String headImageUrl = RmGlobalReference.get(ISysConstant.PARAM_TYPE_URL,ISysConstant.PROJECT_PIC_URL);
if(StringHelper.isEmpty(headImageUrl)){
throw new Exception("尚未配置保存项目url参数!");
}
if(!headImageUrl.startsWith("/")){
headImageUrl  ="/"+headImageUrl;
}
if(!headImageUrl.endsWith("/")){
headImageUrl  = headImageUrl+"/";
}
        File targetFile = new File(projectPic, fileName);
        if(!targetFile.exists()){
            targetFile.mkdirs();
        }
        


        //保存
        try {
            file.transferTo(targetFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
      response.getWriter().write("0`" + request.getContextPath() + "/upload/dialog/project/" + fileName);
       return null;



}



0 0
原创粉丝点击