0

I need to upload a image file into the server using JSP.

Here I'm using pure Ajax not Jquery. Also I'm not using FORM for submitting, cause I don't want to refresh current page.

Here is what I have tried.

page1.jsp

<table width="60%" border="0" cellspacing="1" cellpadding="1" align="center" class="style1">    
<tr>  
  <td align="left"><b>Select a file to upload :</b></td>  
</tr>  
<tr>  
  <td align="left">  
    <input type="file" name="file" id="listfile" onchange="readURL(this);">  
    </td>  
</tr>  
<tr>  
  <td align="left">  
    <input type="submit" value="SUBMIT" />
    </td>  
</tr>  
</table>
<script>
function readURL(input) 
{
    if (input.files && input.files[0]) 
    {
        var reader = new FileReader();
        reader.onload = function (e) 
        {
            $('#img_prev').attr('src', e.target.result).width("25%").height("25%");
        };
        reader.readAsDataURL(input.files[0]);
    }
}
</script>

Now what I need to do is to send this file from "page1.jsp" to "page2.jsp". I have tried with form its working pretty well, but I don't want the user to change the current page.

Here is the code for page2.jsp

page2.jsp

<%@ page import="java.io.*,javax.servlet.http.HttpServletRequest,javax.servlet.ServletInputStream" %>  
<%@ page import="java.io.FileWriter,java.io.IOException" %>  
<%  
    String savePath = "", filepath = "", filename = "";  
    String contentType = "", fileData = "", strLocalFileName = "";  
    int startPos = 0, endPos = 0;  
    int BOF = 0, EOF = 0;  
%>  
<%! void copyByte(byte [] fromBytes, byte [] toBytes, int start, int len)  
    {  
        for(int i=start;i<(start+len);i++)  
        { 
                toBytes[i - start] = fromBytes[i]; 
        }  
    }  
%>  
<%    
    contentType = request.getContentType();  
    out.println("<br>Content type is :: " +contentType);  
    if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0))   
    {  
        DataInputStream in = new DataInputStream(request.getInputStream());  
        DataInputStream in1 = in;  
        int formDataLength = request.getContentLength();  
        byte dataBytes[] = new byte[formDataLength];  
        int byteRead = 0;  
        int totalBytesRead = 0;  
        while (totalBytesRead < formDataLength)  
        {     
            byteRead = in1.read(dataBytes, totalBytesRead, formDataLength);  
            totalBytesRead += byteRead;  
        }  
        out.println("<br>totalBytesRead : " + totalBytesRead + "    :   formDataLength = " + formDataLength);  

        byte[] line = new byte[128];  
        if (totalBytesRead < 3)   
        {  
          return;   //exit if file length is not sufficiently large  
        }  
        String boundary = "";  
        String s = "";  
        int count = 0;        
        int pos = 0;  
        do  
        {  
            copyByte(dataBytes, line, count ,1);    //read 1 byte at a time  
            count+=1;  
            s = new String(line, 0, 1);  
            fileData = fileData + s;  
            pos = fileData.indexOf("Content-Disposition: form-data; name=\"");  
            if(pos != -1)  
                endPos = pos;  
        }while(pos == -1);  
        boundary = fileData.substring(startPos, endPos);  
        startPos = endPos;  
        do  
        {  
            copyByte(dataBytes, line, count ,1);    //read 1 byte at a time  
            count+=1;  
            s = new String(line, 0, 1);  
            fileData = fileData + s;  
            pos = fileData.indexOf("filename=\"", startPos); //set the file name  
            if(pos != -1)  
                startPos = pos;  
        }while(pos == -1);                    
        do  
        {  
            copyByte(dataBytes, line, count ,1);    //read 1 byte at a time  
            count+=1;  
            s = new String(line, 0, 1);  
            fileData = fileData + s;  
            pos = fileData.indexOf("Content-Type: ", startPos);  
            if(pos != -1)  
                endPos = pos;                         
        }while(pos == -1);  
        filename = fileData.substring(startPos + 10, endPos - 3);  
        strLocalFileName = filename;
        String[] NewName = filename.split("\\.");
        out.println("Original File Name is:"+filename);%><br><%
        String rename = "newName";
        String NewName1 = rename+"."+NewName[1];
        out.println("New File Name is:"+NewName1);%><br><%
        filename = NewName1;
        int index = NewName1.lastIndexOf("\\");  
        if(index != -1) 
        { 
%>
<script language="javascript">
    alert("File already Exists!");
</script>
<%          
            NewName1 = NewName1.substring(index + 1);  
        }
        else
        {
            NewName1 = NewName1;
        }
        boolean blnNewlnFlag = false;  
        startPos = endPos;  //added length of "Content-Type: "  
        do  
        {  
            copyByte(dataBytes, line, count ,1);
            count+=1;  
            s = new String(line, 0, 1);  
            fileData = fileData + s;              
            pos = fileData.indexOf("\n", startPos);  
            if(pos != -1)  
            {  
                if(blnNewlnFlag == true)  
                    endPos = pos;                     
                else  
                {  
                    blnNewlnFlag = true;  
                    pos = -1;  
                }  
            }  
        }while(pos == -1);  
        contentType = fileData.substring(startPos + 14, endPos);  
        BOF = count + 1;  
        do  
        {  
            copyByte(dataBytes, line, count ,1);    //read 1 byte at a time  
            count+=1;  
            s = new String(line, 0, 1);  
            fileData = fileData + s;  
            pos = fileData.indexOf(boundary, startPos);           
        }while(pos == -1);  
        EOF = count - boundary.length();  
        out.println("<br><br>0. Local File Name = " + strLocalFileName);  
        out.println("<br><br>1. FILE-NAME-CHANGE = " + NewName1);  
        out.println("<br>2. contentType = " + contentType);  
        out.println("<br>3. startPos = " + BOF);  
        out.println("<br>4. endPos = " + EOF);  
        out.println("<br>5. boundary = " + boundary); 
        String appPath = application.getRealPath("/");  
        out.println("<br>appPath : " + appPath);  
        String destFolder = appPath + "images/";    //change this as required  
        NewName1= destFolder + NewName1;  
        FileOutputStream fileOut = new FileOutputStream(NewName1);  
        fileOut.write(dataBytes, BOF, (EOF - BOF));  
        fileOut.flush();  
        fileOut.close();  
        out.println("<br>File saved as >> " + NewName1);          
    }  
    else  
    {  
        out.println("Error in uploading ");  
    }  
%>

All I need to do is not to use form and to send the image file using AJAX.

                         **or**

any other way for uploading without refreshing the whole page

  • Uploading a file without a form is not possible. (You need a form, just not a normal submit button.) And resisting jquery is a waste of time. You will be assimilated. – developerwjk Sep 16 '14 at 20:03
  • @ developerwjk, So I need to use 'form' for uploading a file. _But is there is an other way of uploading a file_ **without refreshing the whole page??** – JavaLearner Sep 17 '14 at 07:17
  • Using Ajax you use a form without a `` and then there's a class called `FormData` you use to get the form's data and send it in Ajax. See http://stackoverflow.com/questions/6974684/how-to-send-formdata-objects-with-ajax-requests-in-jquery You can use forms without calling a normal http submit. – developerwjk Sep 17 '14 at 17:42
  • @ developerwjk, Will this stops **refreshing the whole page?**, Thanks for the response BTW. – JavaLearner Sep 18 '14 at 05:59
  • Yes, with Ajax rather than refreshing the page you get the response back in javascript, so with jQuery for instance you see the `success: function (data) {...}`: data is the response from the server and you have to do something with it in javascript (you can also ignore it). BTW, you should not send an Ajax request from the same page back to itself...make another page to handle the backend of the Ajax. – developerwjk Sep 18 '14 at 18:56
  • @ developerwjk, please give your valuable suggestion with an example,by answering my question so that I can mark as the answer for my question. – JavaLearner Sep 20 '14 at 05:56

0 Answers0