Wrox Programmer Forums
Go Back   Wrox Programmer Forums > Java > Java and JDK > JSP Basics
| Search | Today's Posts | Mark Forums Read
JSP Basics Beginning-level questions on JSP. More advanced coders should post to Pro JSP.
Welcome to the p2p.wrox.com Forums.

You are currently viewing the JSP Basics section of the Wrox Programmer to Programmer discussions. This is a community of software programmers and website developers including Wrox book authors and readers. New member registration was closed in 2019. New posts were shut off and the site was archived into this static format as of October 1, 2020. If you require technical support for a Wrox book please contact http://hub.wiley.com
 
Old May 30th, 2007, 08:17 AM
Registered User
 
Join Date: May 2007
Location: , , .
Posts: 8
Thanks: 0
Thanked 0 Times in 0 Posts
Default file upload validation

hi all

i need help in getting a way to validate a file input object in Html form
i have a form where users should select a file to upload and am using jsp code to upload the file

but i want to validate that if the user didnt select a file then he should get a message which says u should select a file
using java script is possible or using jsp >>> anything would work would help me

this is my form

<FORM ACTION="single_upload_page.jsp" METHOD="POST" ENCTYPE="multipart/form-data" name="form1" id="form1">
                <br>
                <br>
                <br>
                <center>
                  <table border="2" bordercolor="#006666" >
                    <tr>
                      <td colspan="3"><center>
                          <p align="center" class="style1"><span class="style3">Upload your CV <span class="style37">using MS word or PDF files </span></span>
                              <center>
                              </center>
                        </center>
                    </tr>
                    <tr>
                      <td height="64"><span class="style2">Choose the file To Upload:</span></td>
                      <td><input name="f1" type="file" required></td>
                    </tr>
                    <tr>
                      <td colspan="2"><p align="right">
                          <INPUT name="f2" TYPE="submit" id="f2" VALUE="Upload" >
                      </p></td>
                    </tr>
                  </table>
                </center>
              </FORM></td>


Thanks in advance

 
Old May 30th, 2007, 11:17 AM
Friend of Wrox
 
Join Date: Mar 2007
Location: Hyderabad, A.P., India.
Posts: 373
Thanks: 0
Thanked 1 Time in 1 Post
Default

Hi,
If you post some of the java code which deals with file upload then i can try to help you.
Usually the way is to check the available bytes in the request object using request.getInputstream().available() method call.

Regards,
Rakesh
 
Old May 31st, 2007, 07:34 AM
Registered User
 
Join Date: May 2007
Location: , , .
Posts: 8
Thanks: 0
Thanked 0 Times in 0 Posts
Default

hi again Rakesh

i dont have the java script .. i searched alot but didnt find a solution that's why i posted here


i tried to validate it using jsp and this is it

<%@ page import="java.io.*" %>


<%


    //to get the content type information from JSP Request Header

    //String uf = request.getParameter("f1");

    String contentType = request.getContentType();


    //here we are checking the content type is not equal to Null and as well as the passed data from mulitpart/form-data is greater than or equal to 0

    //if (uf.equals(""))
    //{
    //out.println("Please select a file to upload");

    //}

    if (contentType.equals(""))

    {
        out.println("sorry");
    }


    if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0))

     {
         DataInputStream in = new DataInputStream(request.getInputStream());


    //we are taking the length of Content type data

        int formDataLength = request.getContentLength();

        byte dataBytes[] = new byte[formDataLength];

        int byteRead = 0;

        int totalBytesRead = 0;

        //this loop converting the uploaded file into byte code

        while (totalBytesRead < formDataLength)

        {

        byteRead = in.read(dataBytes, totalBytesRead, formDataLength);

            totalBytesRead += byteRead;

        }


        String file = new String(dataBytes);

        //for saving the file name

        String saveFile = file.substring(file.indexOf("filename=\"") + 10);

        saveFile = saveFile.substring(0, saveFile.indexOf("\n"));

        saveFile = saveFile.substring(saveFile.lastIndexOf("\\")+ 1,saveFile.indexOf("\""));

        int lastIndex = contentType.lastIndexOf("=");

        String boundary = contentType.substring(lastIndex + 1,contentType.length());

        int pos;

        //extracting the index of file

        pos = file.indexOf("filename=\"");

        pos = file.indexOf("\n", pos) + 1;

        pos = file.indexOf("\n", pos) + 1;

        pos = file.indexOf("\n", pos) + 1;

        int boundaryLocation = file.indexOf(boundary, pos) - 4;

        int startPos = ((file.substring(0, pos)).getBytes()).length;

        int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;

        // creating a new file with the same name and writing the content in new file and saving the file in a specific file

        String dir = ("C:\\Uploaded_Files\\");

        FileOutputStream fileOut = new FileOutputStream(dir+saveFile);

        fileOut.write(dataBytes, startPos, (endPos - startPos));

        fileOut.flush();

        fileOut.close();



        %>

 
Old June 1st, 2007, 12:06 AM
Friend of Wrox
 
Join Date: Mar 2007
Location: Hyderabad, A.P., India.
Posts: 373
Thanks: 0
Thanked 1 Time in 1 Post
Default

Hi,

check the additional condition i've added [in bold letters]
that way we can verify whether the file selected by user is valid or not if the user just type some garbage in to the file input tag we'll get 0 bytes in the stream, or even if he completly omits it.

Code:
<%@ page import="java.io.*" %>
<%
    //to get the content type information from JSP Request Header
    //String uf = request.getParameter("f1");
    String contentType = request.getContentType();
    //here we are checking the content type is not equal to Null and as well as the passed data from mulitpart/form-data is greater than or equal to 0
    //if (uf.equals(""))
    //{
    //out.println("Please select a file to upload");
    //}
    if (contentType.equals(""))
    {
        out.println("sorry");
    }

    if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0))
     {
         DataInputStream in = new DataInputStream(request.getInputStream());

    //we are taking the length of Content type data
        int formDataLength = request.getContentLength();

    //Check the data availability
    if(formDataLength <= 0){
        out.println("The file you've selected in empty or it does not exisits");
    }else{

        byte dataBytes[] = new byte[formDataLength];
        int byteRead = 0;
        int totalBytesRead = 0;
        //this loop converting the uploaded file into byte code
        while (totalBytesRead < formDataLength)
        {
        byteRead = in.read(dataBytes, totalBytesRead, formDataLength);
            totalBytesRead += byteRead;
        }

        String file = new String(dataBytes);
        //for saving the file name
        String saveFile = file.substring(file.indexOf("filename=\"") + 10);
        saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
        saveFile = saveFile.substring(saveFile.lastIndexOf("\\")+ 1,saveFile.indexOf("\""));
        int lastIndex = contentType.lastIndexOf("=");
        String boundary = contentType.substring(lastIndex + 1,contentType.length());
        int pos;
        //extracting the index of file
        pos = file.indexOf("filename=\"");
        pos = file.indexOf("\n", pos) + 1;
        pos = file.indexOf("\n", pos) + 1;
        pos = file.indexOf("\n", pos) + 1;
        int boundaryLocation = file.indexOf(boundary, pos) - 4;
        int startPos = ((file.substring(0, pos)).getBytes()).length;
        int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;
        // creating a new file with the same name and writing the content in new file and saving the file in a specific file
        String dir = ("C:\\Uploaded_Files\\");
        FileOutputStream fileOut = new FileOutputStream(dir+saveFile);
        fileOut.write(dataBytes, startPos, (endPos - startPos));
        fileOut.flush();
        fileOut.close();
    }            
%>
You can also verify whether the file has been selected or not using java script. Try the following code.

Code:
    function checkFileExists(){
        createRequestObject();
        var file_component = document.getElementById("document");
        var filename = file_component.value;

        if(!filename || filename.length <=0){
            highlightRow(document.getElementById("document"));
            errorData[errorData.length] = "Select a document to upload.";
            return false;
        }else{
            var drive;
            if(filename.indexOf("\\")!=-1){
                drive = "\\";
            }else if(filename.indexOf("/")!=-1){
                drive = "/";
            }else{
                highlightRow(document.getElementById("document"));
                errorData[errorData.length] = "Invalid path, use browse button to select a document.";
                return false;
            }

            if((filename.substring(filename.lastIndexOf(drive)+1,filename.lastIndexOf('.'))).length >= 100){
                errorData[errorData.length] = "File name should be less than 100 characters.";

                var parent_td = document.getElementById("document").parentNode;
                parent_td.removeChild(document.getElementById("document"));
                temp_file = document.createElement("input");
                temp_file.type = "file";
                temp_file.id = "document";
                temp_file.name = "document";
                temp_file.defaultValue = "";
                temp_file.className = "element";
                temp_file.size = "35";
                parent_td.appendChild(temp_file);
                temp_file.value = "";
                return false;
            }else if(!checkValidDocs(file_component)){
                return false;
            }else
                return true;
        }

    }
Regards,
Rakesh
 
Old June 1st, 2007, 05:32 AM
Registered User
 
Join Date: May 2007
Location: , , .
Posts: 8
Thanks: 0
Thanked 0 Times in 0 Posts
Default

i have tried the first solution but i get an error say the saveFile is not resovled >>>> i dont know why though its indetified as it is a string
i didnt understand the java script one so i dont think i can use it

any way thanks alot Rakesh , i really appreciate that :)

 
Old June 4th, 2007, 05:37 AM
Friend of Wrox
 
Join Date: Mar 2007
Location: Hyderabad, A.P., India.
Posts: 373
Thanks: 0
Thanked 1 Time in 1 Post
Default

hi,

Quote:
quote:Originally posted by Janoo
 i have tried the first solution but i get an error say the saveFile is not resovled >>>> i dont know why though its indetified as it is a string
The problem is the saveFile object defined in the else block is visible only in the else block, which is not there previously [i mean before i added the if condition for validating the file size.], you might've been using it below that code [i.e. after closing the else block]. Check it you can solve it easily. If you want to use that saveFile variable outsied the else block declare it before the if condition and then assign the value in the else block.

Hope it solves your problem.

Regards,
Rakesh




Similar Threads
Thread Thread Starter Forum Replies Last Post
Filter File Types in ASP.NET File Upload ramuis78 ASP.NET 2.0 Basics 2 May 31st, 2007 10:50 AM
Whole Folder upload(Multi file Upload) ramasamy_rams XML 1 September 9th, 2005 12:43 PM
File upload sunilwarrior Apache Tomcat 0 April 27th, 2005 11:17 AM
upload file niy Classic ASP Databases 1 February 5th, 2005 09:14 AM
JSP file upload and delete file pandjie JSP Basics 0 January 29th, 2005 10:49 PM





Powered by vBulletin®
Copyright ©2000 - 2020, Jelsoft Enterprises Ltd.
Copyright (c) 2020 John Wiley & Sons, Inc.