Download image on clicking an image - java

I want to download image on click. I had set content type but I couldn't write image in response. In controller I get URL of image.
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()));
For writing into response I used this code
DataInputStream input = new DataInputStream(new FileInputStream(file));
ServletOutputStream output = response.getOutputStream();
Here input returns null.
How to resolve this problem?

Please check following code.
for uploading image into database.
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);
}
and for downloading image.
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);
}
}

Related

file not found exception, system can not specified image path

System cannot specified the file error is coming. I dont know why
I am using servlet and used file input stream in it to convert image in byte form..
public class Student extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String f=request.getParameter("U_Fname");
String l=request.getParameter("U_Lname");
String p=request.getParameter("U_Pswd");
String e=request.getParameter("U_Email");
String m=request.getParameter("U_Mobile");
String a=request.getParameter("U_Address");
String c=request.getParameter("U_Category");
String g=request.getParameter("U_Gender");
String d=request.getParameter("U_Dob");
String t=request.getParameter("U_Country");
String j=request.getParameter("U_Image");
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe","system","admin");
PreparedStatement ps=con.prepareStatement("insert into Registeruser values(?,?,?,?,?,?,?,?,?,?,?)");
FileInputStream fis=new FileInputStream(new File(j));
ps.setString(1,f);
ps.setString(2,l);
ps.setString(3,p);
ps.setString(4,e);
ps.setString(5,m);
ps.setString(6,a);
ps.setString(7,c);
ps.setString(8,g);
ps.setString(9,d);
ps.setString(10,t);
ps.setBinaryStream(11,fis);
int i=ps.executeUpdate();
if(i>0)
out.print("You are successfully Registred...");
}catch(Exception e2)
{System.out.println(e2);}
out.close();
}
}
The system file cannot specified , java file not found exception
You can try the following. I assume that you are submitting the Image file not the Image path.
InputStream inputStream = null;
Part filePart = request.getPart("U_Image");
if (filePart != null) {
System.out.println(filePart.getName());
System.out.println(filePart.getSize());
System.out.println(filePart.getContentType());
inputStream = filePart.getInputStream();
}
if (inputStream != null) {
ps.setBlob(11, inputStream);
}

How to populate mysql database table with metadata of uploaded file

I created servlet for uploading files to MySQL database:
#WebServlet("/UploadFileController") #MultipartConfig(maxFileSize = 16177215)
public class UploadFileController extends HttpServlet {
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
InputStream inputStream = null;
Random rand = new Random();
int n = rand.nextInt(9999) + 1;
String idTemp=(String.valueOf(n));
String title=(request.getParameter("title"));
Part filePart = request.getPart("file_uploaded");
if (filePart != null)
{
System.out.println(filePart.getName());
System.out.println(filePart.getSize());
System.out.println(filePart.getContentType());
inputStream = filePart.getInputStream();
}
try
{
Db_Connection dbconn=new Db_Connection();
Connection conn= dbconn.Connection();
String sql = "INSERT INTO books (id, title, author, keywords, publication_year, filename, MIME, file) values (?, ?, ?, ?, ?, ?, ?, ?)";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1, idTemp);
statement.setString(2, title);
statement.setString(3, "Goran");
statement.setString(4, "Analisis");
statement.setString(5, "1995");
statement.setString(6, "OrgFileName");
statement.setString(7, "pdf");
if (inputStream != null)
{
statement.setBinaryStream(8, inputStream, (int) filePart.getSize());
}
int row = statement.executeUpdate();
if (row > 0)
{
out.println("File uploaded!!!");
conn.close();
RequestDispatcher rs = request.getRequestDispatcher("upload_form.jsp");
rs.include(request, response);
}
else
{
out.println("Couldn't upload your file!!!");
conn.close();
RequestDispatcher rs = request.getRequestDispatcher("upload_form.jsp");
rs.include(request, response);
}
}catch(Exception e){e.printStackTrace();}
}
}
Right now, I input manually some strings in database instead of real metadata of uploaded file.
I'm trying to take metadata by TIKA.
public class MetadataViewer {
public static void main(final String[] args) throws IOException, TikaException {
//Assume that boy.jpg is in your current directory
File file = new File("C:/Users/goran/Desktop/zadatak_grupa_B.pdf");
//Parser method parameters
Parser parser = new AutoDetectParser();
BodyContentHandler handler = new BodyContentHandler();
Metadata metadata = new Metadata();
FileInputStream inputstream = new FileInputStream(file);
ParseContext context = new ParseContext();
try {
parser.parse(inputstream, handler, metadata, context);
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(handler.toString());
//getting the list of all meta data elements
String[] metadataNames = metadata.names();
for(String name : metadataNames) {
System.out.println(name + ": " + metadata.get(name));
}
}
}
Obvious, currently this class, right now, work only with spcified file as here, for example: File file = new File("C:/Users/goran/Desktop/zadatak_grupa_B.pdf"); and write meta data in Console.
How to read metadata of uploaded file and input them into database?

I am trying to retrieve BLOB data(image) and display in html page using servlet

I am trying to retrieve BLOB data(image) and display in html page using servlet.
Following is my code. But it displays nothing. Thanks in advance.
In addition I have used MySQL database.
public class retriveLogo extends HttpServlet {
standardFunction sf = new standardFunction();
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
HttpSession session=request.getSession();
Blob imageBlob=null;
byte[] imgData = null;
try {
String sql1 = "select img from userLogo where userID=?";
PreparedStatement statement = sf.co.con.prepareStatement(sql1);
statement.setString(1, (String)session.getAttribute("User"));
ResultSet resultSet = statement.executeQuery();
while(resultSet.next())
{
imageBlob = resultSet.getBlob("doc");
imgData = imageBlob.getBytes(1, (int) imageBlob.length());imageBlob.length());
}
OutputStream output = response.getOutputStream();
response.setContentType("image/gif");
output.write(imgData);
output.flush();
output.close();
} catch(Exception e) {
try {
sf.co.con.rollback();
} catch (SQLException ex1) {
Logger.getLogger(insertPaperSize.class.getName()).log(Level.SEVERE, null, ex1);
}
Logger.getLogger(insertPaperSize.class.getName()).log(Level.SEVERE, null, e);
}
}
I want to call it like
<img src="retriveLogo">

Stream Corrupted Exception When calling Jasper Report

I have used a fileDownloadActionListener for opening a jasper report from an ADF form. First time, it's opening correctly. But the second time onwards it gives an error message on the application saying, "The file was not downloaded or was not downloaded correctly."
This is my code:
public void reportAction(FacesContext ctx,OutputStream output) throws FileNotFoundException,NamingException,
SQLException, IOException, JRException,
ClassNotFoundException,
InstantiationException,
IllegalAccessException,StreamCorruptedException {
File input = null;
Connection conn = null;
String branchId = getBranchId().getValue().toString();
Map reportParameters = new HashMap();
reportParameters.put("branchId", branchId);
bindings = this.getBindings();
ctx = FacesContext.getCurrentInstance();
HttpServletResponse response = (HttpServletResponse)ctx.getExternalContext().getResponse();
ServletOutputStream servletOutputStream;
servletOutputStream = response.getOutputStream();
String reportPath = ctx.getExternalContext().getInitParameter("reportpath");
input = new File(reportPath+"testJob.jasper");
byte[] bytes= null;
if(bindings!=null){
OperationBinding ob = bindings.getOperationBinding("getCurrentConnection");
ob.execute();
conn = (Connection)ob.getResult();
System.out.println("Report Path===========>"+input.getPath().toString());
if(input.getPath()!=null&&reportParameters!=null&&conn!=null){
JRPdfExporter pdfExporter = new JRPdfExporter();
bytes = JasperRunManager.runReportToPdf(input.getPath(), reportParameters, conn);
JasperPrint print = JasperFillManager.fillReport(input.getPath(),reportParameters,conn);
pdfExporter.setParameter(JRExporterParameter.JASPER_PRINT, print);
pdfExporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, input.getPath());
pdfExporter.exportReport();
response.addHeader("Content-disposition", "attachment;filename=testJob1.pdf");
response.setContentType("application/pdf");
response.setContentLength(bytes.length);
File file = new File(input.getPath());
output = response.getOutputStream();
servletOutputStream.write(bytes, 0, bytes.length);
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bui = new BufferedInputStream(fis);
int readBytes = 0;
while ((readBytes = bui.read()) != -1)
output.write(readBytes);
bui.close();
fis.close();
servletOutputStream.flush();
servletOutputStream.close();
ctx.responseComplete();
}
}
else{
ctx.addMessage(null,new FacesMessage("No bindings configured for this page"));
}
}

Applet and Servlet communication

I have an applet that needs to submit a score to a servlet and it is not working correctly.
This is the code for the applet
private URLConnection getConnection() throws MalformedURLException, IOException {
URL serverAddress = null;
URLConnection conn = null;
serverAddress = new URL("http://localhost/GamesPortal/submitScore");
conn = serverAddress.openConnection();
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/x-java-serialized-object");
return conn;
}
private void sendRecievedata(GameInfo info) {
try {
URLConnection c = this.getConnection();
OutputStream os = c.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(os);
oos.writeObject(info);
oos.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
And this is the servlet code
try {
HttpSession s = request.getSession(true);
response.setContentType("application/x-java-serialized-object");
InputStream in = request.getInputStream();
ObjectInputStream ois = new ObjectInputStream(in);
GameInfo info = (GameInfo) ois.readObject();
if (info.getUserId() > 0) {
Scores score = new Scores();
score.submitScore(info);
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
}
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet submitScore</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet submitScore at " + request.getContextPath() + "</h1>");
out.println("</body>");
out.println("</html>");
} catch {
ex.printStackTrace();
} finally {
out.close();
}
Now I have tried accessing the servlet via the browser, just to make sure that the address is correct (it is), but for some reason when I try to access it from the applet itself, it does not connect. (the debugger does not even launch).
(added the ex.printStackTrace(); to each of the try catches, as per suggestion, but I have no idea what or where I'm supposed to look for this)
The code calling the applet looks similar to this:
http://roseindia.net/jsp/simple-jsp-example/applet-in-jsp.shtml
<jsp:plugin code="Pong.class" name="Games/Pong/Pong" type="applet" width="800" height="600">
<jsp:params>
<jsp:param name="userId" value="<%= user.getUserId()%>" ></jsp:param>
</jsp:params>
</jsp:plugin>
Is there something that I am overlooking here?
I have managed to make it work.
This is the code for the applet:
private URLConnection getServletConnection()
throws MalformedURLException, IOException {
URL urlServlet = new URL("http://localhost:8080/GamePortal/submitScore");
URLConnection con = urlServlet.openConnection();
con.setDoOutput(true);
con.setRequestProperty(
"Content-Type",
"application/x-java-serialized-object");
return con;
}
private void onSendData(GameInfo info) {
try {
// send data to the servlet
URLConnection con = getServletConnection();
OutputStream outstream = con.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(outstream);
oos.writeObject(info);
oos.flush();
oos.close();
// receive result from servlet
InputStream instr = con.getInputStream();
ObjectInputStream inputFromServlet = new ObjectInputStream(instr);
String result = (String) inputFromServlet.readObject();
//JOptionPane.showMessageDialog(null, result);
inputFromServlet.close();
instr.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
This is the code for the servlet:
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
response.setContentType("application/x-java-serialized-object");
// read a String-object from applet
// instead of a String-object, you can transmit any object, which
// is known to the servlet and to the applet
InputStream in = request.getInputStream();
ObjectInputStream inputFromApplet = new ObjectInputStream(in);
GameInfo score = (GameInfo) inputFromApplet.readObject();
System.out.println(score.getScore());
GameInfo info = score;
if (info.getUserId() > 0) {
Scores instance = new Scores();
instance.submitScore(info);
}
OutputStream outstr = response.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(outstr);
oos.writeObject("reply");
oos.flush();
oos.close();
} catch (ClassNotFoundException ex) {
}
}
Thanks for your help and forgive me for taking too long to reply.

Categories

Resources