使用Struts2将映像路径上载到数据库

时间:2015-08-08 10:31:25

标签: java struts2

我是Struts2的新手,并试图了解更多信息。我只想将图像的路径上传到数据库中,而不是整个图像。我想将它存储在我的服务器上,以后可以检索。

这是我的主意。现在我的问题是,怎么做?我已经尝试了,但是现在,我陷入困境并且出错了。

错误:

  

public class UploadImageAction extends ActionSupport{ public String execute() throws FileNotFoundException, ClassNotFoundException, SQLException { ImageBean ib= new ImageBean(); FileInputStream in = new FileInputStream (ib.getFile()); Class.forName("com.mysql.jdbc.Driver"); String sql = "insert into filetable (image) value (?)"; Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/erp","root","ali$"); PreparedStatement ps = conn.prepareStatement (sql); // Specified in the settings for the specified input stream inputStream.available () used to determine the length of the stream ps.setBinaryStream (1, in); // Returns true if there is a database if (ps.executeUpdate ()> 0) { return "view"; } return "err"; } }

UploadImage.java

public class ImageBean {

    public File getFile() {
        return file;
    }

    public void setFile(File file) {
        this.file = file;
    }
    File file;

}

ImageBean.java

RefreshOrLoadDataToCache()

2 个答案:

答案 0 :(得分:0)

本地变量

File file;

永远不会用数据初始化,因此是例外。使FileBean成为Action类中的成员变量,并为其创建一个setter。

E.g。

private File file;

public void setFile(String fileName) {
    this.file = new File(fileName);
}

在此之后,您可以从HTML表单加载fileName。这将解决您的NullPointerException

PS:您说您只想将路径存储到数据库中。在这种情况下,您应该将file.getPath()作为字符串保存到数据库中:

ps.setString(1, file.getPath());

答案 1 :(得分:0)

像这样更改您的代码

 public class UploadImageAction extends ActionSupport{

 public String execute() throws FileNotFoundException, ClassNotFoundException, SQLException {
      ImageBean ib= new ImageBean();
      FileInputStream in = new FileInputStream (ib.getFile());
      Class.forName("com.mysql.jdbc.Driver");
      String sql = "insert into filetable (image) value (?)";
      Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/erp","root","ali$");
      PreparedStatement   ps = conn.prepareStatement (sql);
      // Specified in the settings for the specified input stream inputStream.available () used to determine the length of the stream
      ps.setBinaryStream (1, in,in.available());
      // Returns true if there is a database
      if (ps.executeUpdate ()> 0) {
          return "view";
      }           
      return "err";                   
  }
}

和Image Bean文件为

public class ImageBean {

File file;
public File getFile() {
    return file;
}

public void setFile(File file) {
    this.file = file;
 }
}

并且“存储图像的位置”列的数据类型必须为 blob 类型。