1.jsp代码  上传图片类型的     提交使用post提交         后面一点要写上这个  enctype="multipart/form-data"
<form name="upload" method="post" enctype="multipart/form-data" >
<a href="#" onclick="formSubmit('productAction_upload','_self');this.blur();">保存</a>
<tr>
                    <td class="columnTitle">产品图片:</td>
                    <td class="tableContent">
                        <!--上传图片、文件的代码--> <input type="file" name="upload" id="upload"
                        onchange="javascript:setImagePreview();">
                        
                         <div id="localImag"> 
        <img id="preview" width=-1 height=-1 style="diplay:none" /> 
    </div> 
                    </td>
</tr>
</from>
2.在Action中
    //注意一定要记得定义这两个 private File upload 页面返回的上传数据。private String uploadFileName  文件名;
    private File upload;//动作类上传的属性必须是file类型,upload为表单的name值 
    private String uploadFileName; //上传的文件名称,固定写法:name+FileName; 
   
    @Action(value="productAction_upload")
    public String execute() throws Exception { 
       
       
        /*定义一个要保存到的路径   注意,如果想保存到项目中显示,直接更具路径找到自己想保存的地方,写上路径名就可以了,这里我是保存到我的一个项目下了,等会要在页面进行回显数据*/
  String path =  "E:ilcbs_server_web//src//main//webapp//images//upload//";
               //判断路径名是否存在,不存在则创建 mkdir
              File file = new File(path); 
                if(!file.exists()){ 
                    file.mkdir(); 
                } 
        //将页面传过来的数据通过FileUtils 拷贝到我们刚刚定义的路径下
        FileUtils.copyFile(upload, new File(file,uploadFileName)); 
      
        //获取路径名+文件名的字符串:自己做测试用的可写可不写根据需求了
        String file2 = new File(file,uploadFileName).toString();
        System.out.println("文件名:"+uploadFileName);
        System.out.println("file2:"+file2);
       
        //想把图片在页面回显,因此自保存文件名到数据库就可以了  路径通过项目的相对路径来获取
        //uploadFileName  就是文件名,不要赋值什么的直接 private String uploadFileName; 定义好getset 后就能获得上传的文件名
        
        model.setProductImage(uploadFileName);//给数据库图片的属性名赋值ProductImage上图片名字
        productService.saveOrUpdate(model);//调用保存方法保存数据
    
        return "alist"; 
    } 
    
3.页面面回显

//style="width:50px;height:50px"  设置图片显示大小     如上我的图片保存到 //E://ilcbs_server_web//src//main//webapp//images //upload//中的 ,那么我直接用${pageContext.request.contextPath }获取到webapp目录下,后面再拼接目录名直到自己的文件名


<img style="width:50px;height:50px" src="${pageContext.request.contextPath }/images/upload/${o.productImage}" />


//这种方法提交的话,每次上传完后都不会立即在页面回显数据的  可以自己手动刷新项目,再刷新页面就可以了。想解决的话可以放到tomcat中,但是下次重启服务器会丢失数据,不想放进去的话可以配置Eclipse,在设置中勾选refresh即可 。如下图:配置后就不需要刷新项目了,直接刷新页面即可。


SSH框架 进行图片上传(详细图解,注释,让你一看就看得懂)

相关文章: