繁体   English   中英

使用 Struts2 上传图片路径到数据库

[英]Upload the image path to database using Struts2

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

嗯,这是我的主意。 现在我的问题是,如何做到这一点? 我已经试过了,但现在,我被卡住了,并出现错误。

错误:

java.lang.NullPointerException

上传图片.java

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";                   
      }
}

图像Bean.java

public class ImageBean {

    public File getFile() {
        return file;
    }

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

}

局部变量

File file;

从未用数据初始化,因此例外。 使FileBean成为 Action 类中的成员变量,并为它创建一个 setter。

例如

private File file;

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

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

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

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

像这样改变你的代码

 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类型。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM