大家好我正在尝试构建一个网络应用,用户可以在其个人资料中上传图片。所以我将表用户和图像作为此表中连续的blob现在我正在尝试使用java servlet检索它,但我只得到一个小的空白square.my代码:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class Profile extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
ServletOutputStream out = response.getOutputStream();
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection
("jdbc:mysql://195.251.267.131:3306/****","****","****");
PreparedStatement ps=con.prepareStatement
("select * from users where email=?");
HttpSession session=request.getSession(false);
if(session!=null){
String email=(String)session.getAttribute("email");
Blob photo = null;
ps.setString(1, email);
ResultSet rs =ps.executeQuery();
while(rs.next()) {
photo = rs.getBlob(1);
}
response.setContentType("image/jpg");
InputStream in = photo.getBinaryStream();
int length = (int) photo.length();
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
while ((length = in.read(buffer)) != -1) {
System.out.println("writing " + length + " bytes");
out.write(buffer, 0, length);
}
in.close();
out.flush();
}
}
}
答案 0 :(得分:0)
我在您的代码中看到了一些可能的原因:
image/jpeg
。此外,我还建议这些小修正:
length=photo.length
。这没用。out.flush()
的公寓,你也应该关闭已打开的流(out
和in
),最好是在资源试用指令中填写: try(OutputStream out=response.getOutputStream())
{
...
}
JDBC资源相同:连接,语句和结果集。
ServletException
。