java图片上传并预览,前台用jQuery插件AjaxFileUpload,后台用FileUtils.copyFile.

个人笔记,以备后用.

 

表体代码:

<td colspan="3">
	<s:file label="上传" name="uploadFile" id="uploadNumFile" onchange="fileUpload('uploadNumFile','goodsRecordDtl_goodsPicture','goodsPicture_img')" />
	<a href="#" title="查看" onclick="viewPic('viewPicture1','goodsPicture','goodsRecordDtl_goodsPicture');">查看图片</a>
	<div id="viewPicture1" title="图片预览" style="display: none;" align="center">
		<img id="goodsPicture" src="">
	</div>
</td>

 

js代码(记得要引入jquery库和ajaxfileupload库):

//上传文件id号
 function fileUpload(uploadFileId,filePathId,imgId){
  var imp= document.getElementById(uploadFileId);
  if(imp==null ||imp==""||imp== undefined){
   alert('请选择文件');
   return;
  }
  $.ajaxFileUpload({
    url:ct +"uploadFile.do",
    secureuri:false,
    fileElementId:uploadFileId,
    dataType: 'multipart/form-data',  
    success: function (data, status){ 
     var json = eval('(' + data + ')'); 
     if(json.msg=="1"){
      alert("上传成功");
       
      $('#'+filePathId).val(json.path);
      $('#'+imgId).attr("src",eTrade.ctx+"/upload/"+json.path);
     }else{
      alert("文件上传失败");
     }
    },
    error: function (data, status, e){
     alert(e);
    }
  });
 }
 
 function viewPic(dialogId,imgId,fileId){
  $("#"+dialogId).dialog({
    height: 350,
    width: 600,
    buttons: {
     "取消": function() {
      $("#"+imgId).attr("src","");
     $(this).dialog("close");
    }
    },
    close:function(){
     $("#"+imgId).attr("src","");
    }
  }); 
  if($("#"+fileId).val()==""){
   return;
  }
  $("#"+imgId).attr("src",ct+"/toView.do?attachment="+$("#"+fileId).val());
 }



 

后台代码(uploadFile命名必须与前台name="uploadFile"值一致):

    private File uploadFile;
    
    public File getUploadFile() {
        return uploadFile;
    }

    public void setUploadFile(File uploadFile) {
        this.uploadFile = uploadFile;
    }
	
    @Action(value = "uploadFile", results = { @Result(name = "success", type = "json", params = {
            "ignoreHierarchy", "false","contentType","text/html", "root", "dataMap" }) })
    public String uploadFile() {
        try {
            String UPLOAD_PATH= ServletActionContext.getServletContext().getRealPath("/upload/");
            String randomName= UUID.randomUUID().toString()+ ".jpg";
            if(uploadFile!=null){
                File storageFile = new File(UPLOAD_PATH +"/"+randomName);
                FileUtils.copyFile(uploadFile, storageFile);
            }
            dataMap.put("msg", 1);
            dataMap.put("path", randomName);//文件id号
        } catch (Exception e) {
            logger.error("", e);
            dataMap.put("msg", 0);
        }
        
        return SUCCESS;
    }


以上代码可能有些不全,但是大体思路就是这样,仅仅只是为了以后用的时候方便查看。

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。