首页 > 代码库 > java图片上传并预览,前台用jQuery插件AjaxFileUpload,后台用FileUtils.copyFile.

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

个人笔记,以备后用.

 

表体代码:

<td colspan="3">
	<s:file label="上传" name="uploadFile" id="uploadNumFile" onchange="fileUpload('uploadNumFile','goodsRecordDtl_goodsPicture','goodsPicture_img')" />
	<a href=http://www.mamicode.com/"#" title="查看" onclick="viewPic('viewPicture1','goodsPicture','goodsRecordDtl_goodsPicture');">查看图片>

 

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 = http://www.mamicode.com/"uploadFile", results = { @Result(name = "success", type = "json", params = {>


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

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