我想点击下载图片。我设置了内容类型,但我无法写回应的图像。在控制器中我得到图像的URL。
String image=myimageUrl;
File file = new File(image);
String contentType = getServletContext().getMimeType(file.getName());
response.setBufferSize(DEFAULT_BUFFER_SIZE);
response.setContentType(contentType);
response.setHeader("Content-Length", String.valueOf(file.length()));
为了写入回应,我使用了这段代码
DataInputStream input = new DataInputStream(new FileInputStream(file));
ServletOutputStream output = response.getOutputStream();
此处输入返回null
。
如何解决此问题?
答案 0 :(得分:0)
请检查以下代码。
用于将图像上传到数据库中。
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
String path=request.getParameter("h2");
out.println(path);
Connection connection=null;
ResultSet rs = null;
PreparedStatement psmnt = null;
FileInputStream fis;
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/image", "root", "kshitij");
File image = new File(path);
psmnt = connection.prepareStatement("insert into new1(id,imagepath)"+"values(?,?)");
String s1=request.getParameter("h1");
psmnt.setString(1,s1);
fis = new FileInputStream(image);
psmnt.setBinaryStream(2, (InputStream)fis, (int)(image.length()));
int s = psmnt.executeUpdate();
if(s>0) {
out.println("Uploaded successfully !");
}
else {
out.println("unsucessfull to upload image.");
}
}
catch (Exception ex) {
System.out.println("Found some error : "+ex);
}
并下载图片。
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
Connection connection = null;
ResultSet rs = null;
PreparedStatement psmnt = null;
InputStream sImage;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/image", "root", "kshitij");
psmnt = connection.prepareStatement("SELECT imagepath FROM new1 WHERE id = ?");
psmnt.setString(1, "23");
rs = psmnt.executeQuery();
if(rs.next()) {
byte[] bytearray = new byte[1048576];
int size=0;
sImage = rs.getBinaryStream(1);
//response.reset();
response.setContentType("image/jpeg");
while((size=sImage.read(bytearray))!= -1 ){
response.getOutputStream().write(bytearray,0,size);
}
}
}
catch(Exception ex){
// out.println("error :"+ex);
}
}