How to upload image using JSP

hi,
i am confronting a problem how to upload image from local PC to web server . I am using Tomcat 4.0
please help me by sending code
thanks

Hi,
Here is the solution for uploading images and displaying images. I am using struts with JSP, so this code has a Action and ActionForm class. You can put the same code in Java Beans or Servlet class to run it. This code has two JSP files - one for Upload (upload.jsp)and other for Image(image.jsp) display. It has a Servlet also to display the image. Here is the code file wise.
Upload.jsp **********************************************************
<%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>
<%@ taglib uri="/WEB-INF/struts-template.tld" prefix="template" %>
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<html:html>
<head>
<title>New Page 1</title>
</head>
<body>
<html:form action="uploadAction.do" enctype="multipart/form-data" method="POST">
<p>File to upload   
<html:file property="fileUpload" size="20"/></p>
<p><html:submit value="Upload" property="upload"/></p>
<p> </p>
<p><html:img src="image.jsp"/></p>
<p> </p>
</html:form>
</body>
</html:html>
Image.jsp*****************************************************************
<jsp:useBean id="upload" class="uploadtest.uploadActionForm" scope="session">
</jsp:useBean>
<%
     byte[] rgb=(byte[])session.getAttribute("byte");
     request.setAttribute("byArr", rgb);
%>
<!--
The image data is now on the request object.
Forward the user to the showImage servlet.
That servlet will process and display the image data contained on the request object.
-->
Image is<p>
<jsp:forward page="/showimage" />
Struts Action Class - UploadAction.java **************************************************
import javax.servlet.http.*;
import java.io.*;
import org.apache.struts.upload.FormFile;
import org.apache.struts.action.*;
public class uploadAction extends Action {
public ActionForward execute(ActionMapping actionMapping, ActionForm actionForm, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
uploadActionForm upload = (uploadActionForm) actionForm;
try {
int size=upload.getFileUpload().getFileSize();
//if (image != null) {
byte[] byteArr = new byte[size];
//Create an input stream to read the uploaded file.
ByteArrayInputStream bytein = new ByteArrayInputStream(upload.getFileUpload().getFileData());
// Load the input stream into the byte Array.
bytein.read(byteArr);
// Close the input stream.
bytein.close();
// Load the byte[] into the content field.
upload.setContent(byteArr);
HttpSession ses=httpServletRequest.getSession();
ses.setAttribute("byte",byteArr);
return actionMapping.findForward("success");
} catch (Exception ex) {
ex.printStackTrace();
return actionMapping.findForward("success");
Struts ActionForm class ---uploadActionForm.java***************************************************
package uploadtest;
import org.apache.struts.action.*;
import org.apache.struts.upload.*;
import javax.servlet.http.*;
public class uploadActionForm extends ActionForm {
private FormFile fileUpload;
private byte[] content;
public FormFile getFileUpload() {
return fileUpload;
public void setFileUpload(FormFile fileUpload) {
this.fileUpload = fileUpload;
public byte[] getContent()
return content;
public void setContent(byte[] theFile)
this.content = theFile;
public ActionErrors validate(ActionMapping actionMapping, HttpServletRequest httpServletRequest) {
/**@todo: finish this method, this is just the skeleton.*/
return null;
public void reset(ActionMapping actionMapping, HttpServletRequest httpServletRequest) {
Servlet to display image --- ShowImage.java ********************************************************
import java.io.*;
import java.util.*;
public class ShowImage extends HttpServlet {
//Initialize global variables
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
byte[] rgb = (byte[]) request.getAttribute("byArr");
if (rgb != null)
response.setContentType("image/gif");
OutputStream stream = response.getOutputStream();
stream.write(rgb);
else
response.setContentType("text");
response.getWriter().write("attribute byArr not found");
This code will enable to to upload and display the image. If you know Struts, then you can write the Struts-Config.xml file by yourself. Other wise write to me, I will send you that. If you want to save the image in database, then you have to keep it as BLOB datatype is database. For database you need to send the byte array in the uploadAction.java file to database. Database will keep the image as binary.
Thanks
Amit

Similar Messages

  • How to upload image using JSP under Tomcat

    Hi,
    I want to write a piece of code, which can upload the local image files to the server, also, the user can view the image by click the image name. I use jakarta_tomcat_.1.xx. Can anyone give me some reference about image transfer?
    Thanks a lot!
    Junmin

    do a search for "JSP file upload" and you should find lots of information.

  • How can I upload an image using JSP in database(MySQL)

    I have to develop an application in which users can register themselve by filling up thier information(name, address) etc along with their photo.
    Storing nam etc. is simple but i am unable to upload photo using JSP.

    Here are lot of examples: http://www.google.com/search?q=jsp+file+upload
    Or if you actually have implemented something which doesn't work as expected, then please ask specific questions.

  • How to upload image files in sqlserver from jsp

    hi friends,
    i want to upload images to sqlserver how will i store url of the image or dorectly store the file in binary format, if we store in related path,plese give some ideas on store that paths in data base and how we store that image files in user directories.
    bye

    hi jay , I know that concept , but i dont know how to upload image files to server Please help me
    here i am giving my problem
    If any user register with site, he has the option to upload his image to the site, so i am using in html file upload option, But i dont know how to store that iamge into the server
    please give me suggestion
    regards
    sudhakar

  • How to upload Images in Forms 6i

    Dear all,
    How to upload images in Forms 6i and save it in database. Please anyone help me with example.
    Thanking you
    Shekhar

    why do you need an active/X for this?
    Can't you just create 2 default blocks on dept and on emp.
    Use the relationship wizard to define the relation. and set the number of records displayed for the emp block to 10?
    This will give you all you need with no hussle.

  • How to upload images on hard drive to iPad?

    how to upload images on hard drive to iPad?

    You can import them into iTunes then use that to get them onto your iPad.
    You can download the iCloud control panel and use photo stream to get the photos onto your iPad
    You can e-mail them to yourself and them save them from that e-mail
    You can upload them to something like dropbox and then download them onto your pad from there.

  • Hello, i am new to the mac and i need to learn how to re image using an external hard drive

    Hello, i am new, like baby fresh new,...lol, to the mac and i need to learn how to re-image using an external hard drive.

    How to replace or upgrade a drive in a laptop
    Step One: Repair the Hard Drive and Permissions
    Boot from your OS X Installer disc. After the installer loads select your language and click on the Continue button. When the menu bar appears select Disk Utility from the Installer menu (Utilities menu for Tiger, Leopard or Snow Leopard.) After DU loads select your hard drive entry (mfgr.'s ID and drive size) from the the left side list.  In the DU status area you will see an entry for the S.M.A.R.T. status of the hard drive.  If it does not say "Verified" then the hard drive is failing or failed. (SMART status is not reported on external Firewire or USB drives.) If the drive is "Verified" then select your OS X volume from the list on the left (sub-entry below the drive entry,) click on the First Aid tab, then click on the Repair Disk button. If DU reports any errors that have been fixed, then re-run Repair Disk until no errors are reported. If no errors are reported click on the Repair Permissions button. Wait until the operation completes, then quit DU and return to the installer.
    If DU reports errors it cannot fix, then you will need Disk Warrior and/or Tech Tool Pro to repair the drive. If you don't have either of them or if neither of them can fix the drive, then you will need to reformat the drive and reinstall OS X.
    Step Two: Remove the old drive and install the new drive.  Place the old drive in an external USB enclosure.  You can buy one at OWC who is also a good vendor for drives.
    Step Three: Boot from the external drive.  Restart the computer and after the chime press and hold down the OPTION key until the boot manager appears.  Select the icon for the external drive then click on the downward pointing arrow button.
    Step Four: New Hard Drive Preparation
    1. Open Disk Utility in your Utilities folder.
    2. After DU loads select your new hard drive (this is the entry with the mfgr.'s ID and size) from the left side list. Note the SMART status of the drive in DU's status area.  If it does not say "Verified" then the drive is failing or has failed and will need replacing.  Otherwise, click on the Partition tab in the DU main window.
    3. Under the Volume Scheme heading set the number of partitions from the drop down menu to one. Set the format type to Mac OS Extended (Journaled.) Click on the Options button, set the partition scheme to GUID  then click on the OK button. Click on the Partition button and wait until the process has completed.
    4. Select the volume you just created (this is the sub-entry under the drive entry) from the left side list. Click on the Erase tab in the DU main window.
    5. Set the format type to Mac OS Extended (Journaled.) Click on the Options button, check the button for Zero Data and click on OK to return to the Erase window.
    6. Click on the Erase button. The format process can take up to several hours depending upon the drive size.
    Step Five: Clone the old drive to the new drive
    1. Open Disk Utility from the Utilities folder.
    2. Select the destination volume from the left side list.
    3. Click on the Restore tab in the DU main window.
    4. Check the box labeled Erase destination.
    5. Select the destination volume from the left side list and drag it to the Destination entry field.
    6. Select the source volume from the left side list and drag it to the Source entry field.
    7. Double-check you got it right, then click on the Restore button.
    Destination means the new internal drive. Source means the old external drive.
    Step Six: Open the Startup Disk preferences and select the new internal volume.  Click on the Restart button.  You should boot from the new drive.  Eject the external drive and disconnect it from the computer.

  • How to upload images in to custom table and display them in normal ABAP report?

    Hi Experts,
    Can anyone suggest me ,how to upload images into customised table and display thoes images in normal abap report.
    Thanks in Advance,
    Rgds,
    Anusha

    Hi Experts,
    Can anyone suggest me ,how to upload images into customised table and display thoes images in normal abap report.
    Thanks in Advance,
    Rgds,
    Anusha

  • How to resize image using java imageio

    Hello ,
    I want to know how to resize image using java imageio.
    I dont want to use java awt because i am writing a web application.
    help is very much needed
    thank you.

    Just use an AffineTransform !
    Its much easier

  • How to run exception using JSP?

    How to run exception using JSP?

    Why would you need the <%%> between the if else blocks? Even if you attempt to write some data within the blocks in java, you will still get an error. For example, this is illegal:
    if(done)
        System.out.println(true);
    System.out.println("Hello World");
    else
        System.out.println(false);
    }The compiler is expecting the 'else' to be directly after the body of the if. If it encounters anything else, it will complain. So you cannot do this in jsp either, regardless if it's a different technology, it's the same compiler.

  • How to Upload documents using Gateway Service in SAP UI5?

    Hi Team,
    How to upload documents using Gateway Service in UI5 app.
    This is Attachment Functionality.using Gateway Service in Controller.JS/View.JS.
    Thanks in Advance.
    Regards,
    Satya

    Hi,
    I suggest you use the search function on scn/google...
    Anyways, here are some usefull links:
    How To Upload and Download Files Using SAP NW Gateway SP06
    Uploading files to SAP using HTML5 /AJAX/Gateway media links with real-time progress bar
    Kind regards,
    RW

  • How to get image using Http and how to save in Smulator

    Hi guys,
    Am working in black berry bold. i dont know how to get image using htp connection and one more thing i need to save this image in side simulator directory............. what are the specific API i should...
    Guide me.........

    If you want the input image size you need to pass it in as parameters.
    A discussion thread on this topic is:
    http://forums.adobe.com/thread/29948
    -- Daniel R. <[email protected]> http://danielr.neophi.com/

  • How to upload data using idoc in lsmw

    plz let me know how to upload material using idoc using lsmw. urgent

    Hi Vrishali,
    refer to the link below:
    http://www.****************/Tutorials/LSMW/IDocMethod/IDocMethod1.htm
    Hope this helps.
    Reward if helpful.
    Regards,
    Sipra

  • IOS how to upLoad image

    IOS how to upload image, how the
    receiving server,can you help me?

    Hi. The iOS library for Azure Storage is currently in planning. In the meantime, please check out the following blog
    http://chrisrisner.com/Mobile-Services-and-Windows-Azure-Storage which may help with your scenario. Thanks.

  • HELP!!!!Display blob image using JSP

    Hi,
    I am trying to blob image using JSP but it did not display successfully.
    Can someone help, please?
    below are the codes snippet:
    <td>
    <img src="display_image.jsp?ID=<%=request.getParameter("ID") %>" width="115" border="0">
    </td>
    byte[] image_blob = details.getImageByteArray();
    response.setContentType("image/jpeg");
    //response.setContentType("image/gif");
    //BEGINNING OF SECTION TO DISPLAY IMAGE
    /*OutputStream fos = null;
    fos = response.getOutputStream();
    fos.write(image_blob, 0, image_blob.length);
    fos.flush();
    fos.close();*/
    java.io.FileOutputStream fos1 = new java.io.FileOutputStream("C:\\"+id+".jpg");
    fos1.write(image_blob);
    fos1.close();
    OutputStream o = response.getOutputStream();
    System.out.println("o");
    o.write(image_blob);
    System.out.println(image_blob);
    System.out.println("write image");

    Use Java Image or BufferedImage instead of obscure byte array for image data.
    Here's an example code for a JSP document:
    <%
    String wid = request.getParameter("percent");
    String cost = request.getParameter("suchi");
    response.reset(); //IMPORTANT !
    response.setContentType("image/jpeg");
    // for testing purpose
    if (wid == null) wid = "58";
    if (cost == null) cost = "3400";
    float dleng = Float.parseFloat(wid) * 2.6f;
    RenderedImage rimg = drawGraph(dleng);
    OutputStream os = response.getOutputStream();
    try{
      ImageIO.write(rimg, "jpg", os);
    catch(IOException e){
    os.flush();
    %>
    <%!
    public RenderedImage drawGraph(float barLength){
      final int w = 800;
      final int h = 18;
      final int x = 0;
      final int y = 0;
      BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
      Graphics2D g2 = img.createGraphics();
      Color c = new Color(Integer.parseInt("FF9999", 16));
      g2.setColor(Color.yellow);
      g2.fillRect(x, y, w, h);
      g2.setColor(c);
      g2.fillRect(x, y, (int)barLength, h);
      g2.dispose();
      return img;
    %>

Maybe you are looking for