日期:2014-05-17  浏览次数:20795 次

关于structs上传图片到数据库的问题,代码如下
这是action代码: package cn.itcast.action;

import java.io.File;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class HelloWorldAction extends ActionSupport {
private File image;
  private String imageFileName;
public File getImage() {
return image;
}
public void setImage(File image) {
this.image = image;
}
public String getImageFileName() {
return imageFileName;
}
public void setImageFileName(String imageFileName) {
this.imageFileName = imageFileName;
}
 
public String execute() throws Exception {
System.out.println("reath");
String realpath=ServletActionContext.getServletContext().getRealPath("/images");
System.out.println("realpath");
if(image!=null){
File savefile=new File(new File(realpath),imageFileName);
if(!savefile.getParentFile().exists()) 
savefile.getParentFile().mkdirs();
FileUtils.copyFile(image, savefile);
 
ActionContext.getContext().put("message", "chernggong");
 
 
}
 
return "SUCCESS";
}
 
}



DAO代码package cn.itcast.DAO;


 
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import cn.itcast.DB.IWrapper;
import cn.itcast.DB.JdbcTemplate;
import cn.itcast.music.PhotoInfo;

 ;

public class PhotoDAO implements IWrapper<PhotoInfo> {
JdbcTemplate<PhotoInfo> jdbcTemplate;
public PhotoDAO(){
this.jdbcTemplate=new JdbcTemplate<PhotoInfo>(this);
}
public void add(String picture ) throws Exception{
String sql="insert into savepicture(picture) values(?)";
Object[] params=new Object[]{picture};
jdbcTemplate.executeUpdate(sql, params);
}
 
 
 
 
public List<PhotoInfo> wrap(ResultSet rs) throws Exception {
List<PhotoInfo> list=new ArrayList<PhotoInfo>();
while(rs.next()){
PhotoInfo photo=new PhotoInfo(); 
photo.setId(rs.getInt("id"));
photo.setPicture(rs.getString("picture"));
list.add(photo);
}
return list;
}
}

 sql2000的数据库就只有id,和picture,picture是image类型的,现在插入数据库不成功,求帮忙看下哪里错了,最好能帮我改代码。在DAO中实现插入数据库的功能还有jsp页面读取数据库中的代码 ,谢谢,万分火急。。给钱写也行啊。。

------解决方案--------------------
一般图片不会存入数据库的。在数据库中存入图片的存放路径即可。
这样每次读取的就根据图片的路径去加载图片
------解决方案--------------------
插入参照下面的,
Java code
public void add(String picture ) throws Exception{    

jdbcTemplate.execute(
                "insert into savepicture(picture) values(?)",
                new PreparedStatementCallback() {

                    public Object doInPreparedStatement(PreparedStatement ps)
                            throws SQLException, DataAccessException {
                       
                FileInputStream fis = null; 
                try { 
                    fis = new FileInputStream(picture); 
                    pst = con.prepareStatement("insert temp values(?)"); 
                    pst.setBinaryStream(1, fis, (int) file.