当我点击submit按钮插入用户详细信息时,我想将用户配置文件图片的图像上传到sql数据库中。我写的代码只是从一个特定的d文件夹中获取图片上传图片我写的代码上传图片但是得到错误(u.setimage(5,(inputstream)fs1,fs1.available());)我还想上传图像从任何驱动器的系统和存储到sql数据库。
servlet编码:
@WebServlet(urlPatterns = {"/Insert"})
public class Insert extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();
ServletContext context = getServletContext();
String dirName =context.getRealPath("d://Photo/");
try
{
String name = request.getParameter("name");
String address = request.getParameter("address");
String phone = request.getParameter("phone");
String image = request.getParameter("image");
String password = request.getParameter("password");
String fPath = "d:\\Photo\\" + image;
System.out.println("insert! "+image);
User u=new User();
u.setName(name);
u.setAddress(address);
u.setPhone(phone);
u.setImage(fPath);
u.setPassword(password);
int i=UserDao.save(u);
if(i>0)
{
request.getRequestDispatcher("user-list.jsp").include(request, response);
}
else
{
out.println("Sorry! unable to insert record");
}
}
catch(Exception e)
{
e.printStackTrace();
}
out.close();
}
}
用户代码:
public static int save(User u) throws FileNotFoundException{
int status=0;
File file1 = null;
FileInputStream fs = null, fs1=null;
String img = u.getImage();
System.out.println("userdao! "+img);
file1 = new File(img);
fs = new FileInputStream(file1);
try{
Connection con=getConnection();
PreparedStatement ps = con.prepareStatement(INSERT_USERS);
ps.setString(1, u.getName());
ps.setString(2, u.getAddress());
ps.setString(3, u.getPhone());
ps.setObject(4, null);
fs = new FileInputStream(img);
System.out.println(fs);
fs1=fs;
ps.setBinaryStream(4, (InputStream)fs1, fs1.available());
ps.setString(5, u.getPassword());
status=ps.executeUpdate();
}catch(Exception e){System.out.println(e);}
return status;
}
1条答案
按热度按时间wbgh16ku1#
您不应该在数据库中真正存储图像。这是一种非常糟糕的做法,数据库的性能将最差。不如用这类东西:
从用户处获取图像并将其转换为字节数组
将字节数组发送到服务器
然后服务器将字节数组转换为文件,然后将文件保存到服务器的目录中
然后将文件的位置保存为数据库中的字符串
现在发送到客户端:
从存储位置获取文件
将其转换为字节数组
将字节数组发送到客户端