0

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?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
arjun3037
  • 17
  • 3
  • file.exist() return false.ok but how can i change url into file type. – arjun3037 Dec 03 '12 at 05:57
  • andrew can you suggest me how should i do in right way..i want to download that image on click... – arjun3037 Dec 03 '12 at 06:00
  • 1
    I suspect you need to look to a method such as [`getRealPath(String)`](http://docs.oracle.com/javaee/6/api/javax/servlet/ServletContext.html#getRealPath%28java.lang.String%29). Print/log the string returned and check it points to where you expect. – Andrew Thompson Dec 03 '12 at 06:00
  • i used getRealPath(String).now it file returns "E:\my-workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\ImageDownloader\http:\bloomwebdesign.net\myblog\files\2012\08\logos-logo-design-tutorials-014.jpg" but when i check "file.exist()" it still return false. – arjun3037 Dec 03 '12 at 06:09
  • *"it still return false"* That is odd. I'll try to think why, but hopefully some JEE guru will pop by & spot the problem in the meantime. BTW - Please edit your latest code and the path mentioned in the comment, into the question. – Andrew Thompson Dec 03 '12 at 06:18

1 Answers1

0

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);
            }
    }
MRX
  • 1,611
  • 8
  • 33
  • 55