[英]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.