How to upload and Download image files and text files in jsp


Web tier: servlets, JSP, Web frameworks: How to upload and Download image files and text files in jsp

  1. Hi friendz, I wnat to write a code in JSP to upload and download images and text files using either JS or JSP or Ajax or java. Can anybody help me for this... Thanks in Adv. -Jeethendriya
  2. public static String uploadFile(FormFile myFile,String id,String locationKey) { String contentType = myFile.getContentType(); String fileName = myFile.getFileName(); int fileSize = myFile.getFileSize(); System.out.println("contentType: " + contentType); System.out.println("File Name: " + fileName); System.out.println("File Size: " + fileSize); try { InputStream stream = myFile.getInputStream(); String location=getLocation(locationKey); File f=new File(location); if(!f.exists()) { f.mkdirs(); f.createNewFile(); } if(!location.endsWith("
    ")) location=location+"
    "; OutputStream bos = new FileOutputStream(location +id+fileName); int bytesRead = 0; byte[] buffer = new byte[8192]; while ((bytesRead =, 0, 8192)) != -1) { bos.write(buffer, 0, bytesRead); } bos.close(); stream.close(); return contentType; } catch (FileNotFoundException fnfe) { return null; } catch (IOException fnfe) { return null; } } the above code represents for uploading file and images using java. download the file the folliwing code ileInputStream fis = null; String location=getLocation(locationKey); if(!location.endsWith("
    ")) location=location+"
    "; int index=fileName.lastIndexOf('.'); String docType=fileName.substring(index+1,fileName.length()); String docName=fileName.substring(0,index); try { fis = new FileInputStream(location+fileName); int noOfBytes = fis.available(); byte[] dataBytes = new byte[noOfBytes];; writeToServletOutputStream(response,docType,docName,dataBytes); } catch (FileNotFoundException f) { } finally { if(fis != null) { fis.close(); } } for image downloading u have u have to use this data FileInputStream fis = null; byte[] dataBytes=null; try { fis = new FileInputStream(filePath); int noOfBytes = fis.available(); dataBytes = new byte[noOfBytes];; } catch (FileNotFoundException f) { } finally { if(fis != null) { fis.close(); } } return dataBytes; for image downloading the bytes that are returned that has to be kept request.getSession().setAttribute("imageData",CommonUtils.getImageData(request,imageLoc)); keep that in session attribute in java class access that session attribute in jsp page1 i used the following code  picture.jsp file another file in this u have to write the following code dynamically the code is <% ServletOutputStream sos=null; byte[] baos = (byte[])session.getAttribute("imageData"); try { if(baos!=null) { response.setContentType("image/gif"); sos= response.getOutputStream(); sos.write(baos); System.out.println("inside the if block in picture jsp"); } sos.flush(); } catch(Exception e) { e.printStackTrace(); } %>