使用struts2和hibernate将图像存储到mysql数据库中

时间:2012-02-04 07:26:51

标签: database image hibernate struts2

大家好我正在开发基于动态网络的应用程序,我正在使用struts-2文件标签获取文件[图像文件] ..这里是代码

<s:file name="userImage" label="User Image" />

现在我的pojo类代码就在这里......

public class FileUpload {
private File userImage;

//private String userImageContentType;

private String userImageFileName;

    //private HttpServletRequest servletRequest;

public File getUserImage() {
    return userImage;
}

public void setUserImage(File userImage) {
    this.userImage = userImage;
}

public String getUserImageFileName() {
    return userImageFileName;
}

public void setUserImageFileName(String userImageFileName) {
    this.userImageFileName = userImageFileName;
}
}

现在在动作类中这样的代码.....

public class FileUploadAction extends ActionSupport implements ModelDriven{

    private FileUpload user = new FileUpload();
    public FileUploadAction()
    {
    }

    public Object getModel() {
                return user;
    }

    public FileUpload getUser() {
        return user;
    }

    public void setUser(FileUpload user) {
        this.user = user;
    }
public String execute() throws IOException
{
try{
        String filePath = ServletActionContext.getServletContext().getRealPath("/");
        System.out.println("Server path:" + filePath);
        File fileToCreate = new File(filePath, user.getUserImageFileName());
        FileUtils.copyFile(user.getUserImage(), fileToCreate);
   }
    catch (Exception e){
        e.printStackTrace();
        //addActionError(e.getMessage());
        return INPUT;
    }
    return SUCCESS;
}
 } 

现在我想使用hibernate将图像文件存储到数据库中,并且在数据库中我创建了属性 IMAGE作为BLOB数据类型所以任何人都可以帮助我在execute方法中编写什么代码,以便要存储在数据库中的图像以及如何检索它并在jsp中显示它......

先谢谢

1 个答案:

答案 0 :(得分:0)

我想在您的代码中进行更正。当您使用模型驱动方法时,无需为模型对象获取getter和setter。删除这些。

 public FileUpload getUser() {
    return user;
}

public void setUser(FileUpload user) {
    this.user = user;
}

只有以下内容足够

public Object getModel() {
            return user;
}