uploading of different file types in jsp

[nobr]hello,

i have implemented a jsp web application where you can upload either

a PDF file (file.pdf) or a latex file (file.tex).

currently i have two different upload file tags so if a user wants to

upload a pdf he/she will use the upload pdf path as shown in the

code below:

**********************************************

<!-- upload for latex file -->

<form action="upload.jsp" name="upform"enctype="multipart/form-data">

<input type="file" name="filename" size="50">

<input type="hidden" name="todo" value="upload">

<input type="submit" name="Submit" value="Upload">

</form>

<h3>

Upload for PDF Files Only </h3>

<form action="uploadPDF.jsp" name="upform"enctype="multipart/form-data">

<input type="file" name="PDFfilename" size="50">

<input type="hidden" name="todo" value="upload">

<input type="submit" name="Submit" value="Upload">

</form>

*********************************************

As you can see above that there are two different paths.

Does anyone know if a user submits a PDF the system should recognize the pdf file extension and call the uploadPDF.jsp page and

if the file is a latex file then it should call the latex method.

pls ur help will be appreciated,

thanks,

moh[/nobr]

[1443 byte] By [moh_1_and_onlya] at [2007-11-26 18:01:42]
# 1

Well the way I would do it is as follows:

1) use one form that can accept both files. I would possibly add a javascript validation that checks the extension of the file inserted before the submit.

2) The submit goes to a servlet. This servlet will then investigate what the type of the file is and act accordingly. This means invoking a method in a seperate class that can handle the specific filetype.

3) the servlet forwards to a JSP to show the results on success, or back to the upload form with an error message if something was wrong.

All the logic is nicely seperated to keep the code not only readable but reusable as well and the JSP can be easily created using JSTL only in stead of having to go back to the evil ways of scriptlets.

gimbal2a at 2007-7-9 5:31:21 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 2
would anyone help by giving the code for this,ur help will b appreciated, thanksmoh
moh_1_and_onlya at 2007-7-9 5:31:21 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 3
?
moh_1_and_onlya at 2007-7-9 5:31:21 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 4
anyone that can help me with any code
moh_1_and_onlya at 2007-7-9 5:31:21 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 5

[nobr]Hi there,

Take a look at : http://jakarta.apache.org/commons/fileupload/

You will need to download 2 additional JAR files to implement the file upload functionality

1) commons-fileupload-1.1.1.jar - get it from http://jakarta.apache.org/site/downloads/downloads_commons-fileupload.cgi

2) commons-io-1.3.jar - get it from

http://jakarta.apache.org/commons/fileupload/dependencies.html

As Gimball mentioned earlier first perform the test for the file type with Javascript - you can research on Google for the Javascript solution.

After it passes the Javascript test here's some code with JSP, Servlets that might help you write your own solution:

~~~~~~~~~~~~~~~~~~~~~~~~~~

somefile.jsp , located under for example:

\p\test29\somefile.jsp

~~~~~~~~~~~~~~~~~~~~~~~~~~

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<html>

<head><title></title></head>

<body>

<form action="/fileUploadServlet" method="post" enctype="multipart/form-data">

<input type="file" name="inputFile"/>

<br/><br/>

<input type="submit" name="submit" value="submit"/>

</form>

</body>

</html>

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

FileUploadServlet

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

package test29;

import org.apache.commons.fileupload.servlet.ServletFileUpload;

import org.apache.commons.fileupload.servlet.ServletRequestContext;

import org.apache.commons.fileupload.RequestContext;

import org.apache.commons.fileupload.FileItemFactory;

import org.apache.commons.fileupload.FileItem;

import org.apache.commons.fileupload.FileUploadException;

import org.apache.commons.fileupload.disk.DiskFileItemFactory;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import javax.servlet.ServletException;

import javax.servlet.RequestDispatcher;

import java.io.IOException;

import java.util.List;

import java.util.Iterator;

public class FileUploadServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

doPost(request, response);

}

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

RequestContext requestContext = new ServletRequestContext(request);

boolean isMultipart = ServletFileUpload.isMultipartContent(requestContext);

System.out.println(" isMultipart : " + isMultipart);

// Create a factory for disk-based file items

FileItemFactory factory = new DiskFileItemFactory();

// Create a new file upload handler

ServletFileUpload upload = new ServletFileUpload(factory);

// Parse the request

List<FileItem> items = null;

try {

items = upload.parseRequest(request);

Iterator fileItemsIter = items.iterator();

while (fileItemsIter.hasNext()) {

FileItem item = (FileItem) fileItemsIter.next();

if (item.isFormField() == false) {

String contentType = processUploadedFile(item);

if (contentType.equalsIgnoreCase("application/pdf")) {

request.setAttribute("contentType", "application/pdf");

} else if (contentType.equalsIgnoreCase("application/tex")) {

request.setAttribute("contentType", "application/tex");

} else {

request.setAttribute("contentType", "other");

}

RequestDispatcher requestDispatcher = getServletContext().getRequestDispatcher("/p/test29/fileReceive.jsp");

requestDispatcher.forward(request, response);

}

}

} catch (FileUploadException e) {

e.printStackTrace();

}

}

private String processUploadedFile(FileItem item) {

String contentType = "unknown";

if (!item.isFormField()) {

String fieldName = item.getFieldName();

String fileName = item.getName();

contentType = item.getContentType();

boolean isInMemory = item.isInMemory();

long sizeInBytes = item.getSize();

/* Print test output on console */

/*

System.out.println(" Field Name : " + fieldName);

System.out.println(" File Name : " + fileName);

System.out.println(" Content Type : " + contentType);

System.out.println(" Is in Memory : " + isInMemory);

System.out.println(" Size in Bytes : " + sizeInBytes);

if (contentType.equalsIgnoreCase("application/pdf")) {

System.out.println("This is a PDF document.");

}

*/

}//if (!item.isFormField())

return contentType;

}//private String processUploadedFile(FileItem item)

}

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Add these to your /WEB-INF/web.xml

First you define the servlet, and provide a URL pattern.

The URL pattern is the form's action in the above JSP file.

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

<servlet>

<servlet-name>FileUploadServlet</servlet-name>

<servlet-class>test29.FileUploadServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>FileUploadServlet</servlet-name>

<url-pattern>/fileUploadServlet</url-pattern>

</servlet-mapping>

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

fileReceive.jsp

located under:

\p\test29\fileReceive.jsp

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<html>

<head><title>Process File</title></head>

<body>

Uploaded File Content Type is : <%=request.getAttribute("contentType")%>

</body>

</html>

In the above JSP you can test for the contentType, if it is not PDF or TEX then perform the next action.

The above code is not very clean or the best way to accomplish this, but it should at least help you get started and it works.[/nobr]

appy77a at 2007-7-9 5:31:21 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 6

[nobr]hello again appy77,

thankyou very much for your help for the code, however

the code uses servlets and the project i am doing only

has to use jsps. i have found a java script that i think you

can use to do the same thing: it is:

*****************************

<HEAD>

<SCRIPT LANGUAGE="JavaScript">

<!-- Original: ArjoGod, Shauna Merritt -->

<!-- Modified By: Ronnie T. Moore, Editor -->

<!-- This script and many more are available free online at -->

<!-- The JavaScript Source!! http://javascript.internet.com -->

<!-- Begin

extArray = new Array(".gif", ".jpg", ".png");

function LimitAttach(form, file) {

allowSubmit = false;

if (!file) return;

while (file.indexOf("\\") != -1)

file = file.slice(file.indexOf("\\") + 1);

ext = file.slice(file.indexOf(".")).toLowerCase();

for (var i = 0; i < extArray.length; i++) {

if (extArray == ext) { allowSubmit = true; break; }

}

if (allowSubmit) form.submit();

else

alert("Please only upload files that end in types: "

+ (extArray.join(" ")) + "\nPlease select a new "

+ "file to upload and submit again.");

}

// End -->

</script>

</HEAD>

<!-- STEP TWO: Copy this code into the BODY of your HTML document -->

<BODY>

<center>

Please upload only images that end in:

<script>

document.write(extArray.join(" "));

</script>

<form method=post name=upform action="/cgi-bin/some-script.cgi" enctype="multipart/form-data">

<input type=file name=uploadfile>

<input type=button name="Submit" value="Submit" onclick="LimitAttach(this.form, this.form.uploadfile.value)">

</form>

</center>

<center>

<font face="arial, helvetica" size="-2">Free JavaScripts provided

by <a href="http://javascriptsource.com">The JavaScript Source</a></font>

</center>

******************************

what i want is if the uploaded file is a PDF file then do action

UploadPDF.jsp else if the file is a latex file then do action

uploadlatex.jsp

can you pls help me in this

thanks,

moh..........[/nobr]

moh_1_and_onlya at 2007-7-9 5:31:21 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 7

Hi there,

I think if you are able to write JSPs in your application, it should also allow you to write Servlets. Using JSPs with Servlets leads to clearner code rather than implementing all logic only inside JSPs alone.

However, since you want a JSP solution - I think the code will look a little messy.

One suggestion is that you could declare a global JavaScript variable, store the file type in that variable.

Once you have the file type,

write javascript code to write an IF statement and display one of the two

<form tags

for example

><script type="text/javascript">

if( fileType == 'PDF){

document.write("<form action="UploadPDF.jsp" method="post");

}else if(fileType=='TEX'){

document.write("><form action="UploadTEX.jsp" method="post");

}

></script>

Please note that I have not tested the above code and not sure if it will work, but you can use it as a basis to research on it .

I strongly encourage you to use the MVC model to write your applications, that means using Servlets to do the routing , and other detailed business logic. Using MVC will make your code cleaner and easier to read and maintain.

If you want to only use JSPs you can still use the above Servlet code that I wrote, but write it inside a JSP (with some modifications ofcourse).

Message was edited by:

appy77

appy77a at 2007-7-9 5:31:21 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 8

[nobr]i have a problem: when clicking upload the nothing happens

please help... the javascript code is:

**************************

<SCRIPT LANGUAGE="JavaScript">

var extArray = new Array(".pdf", ".tex", ".txt");

function LimitAttach(form, file) {

allowSubmit = false;

if (!file) return;

while (file.indexOf("\\") != -1)

file = file.slice(file.indexOf("\\") + 1);

ext = file.slice(file.indexOf(".")).toLowerCase();

for (var i = 0; i < extArray.length; i++) {

if (ext = "pdf"){

document.forms[0].action.value = "uploadPDF.jsp";

allowSubmit = true;

break;

}

}

if (allowSubmit) form.submit();

else

alert("Please only upload files that end in types: "

+ (extArray.join(" ")) + "\nPlease select a new "

+ "file to upload and submit again.");

}

</script>

</HEAD>

*****************

and the form code is

***********************

<h3>

Upload for PDF Files Only </h3>

<form action="" name="upform"enctype="multipart/form-data">

<input type="file" name="PDFfilename" size="50">

<input type="hidden" name="todo" value="upload">

<input type="submit" name="Submit" value="Upload" onclick="LimitAttach(this.form, this.form.PDFfilename.value)">

</form>

**************************

pls can anyone see any errors[/nobr]

moh_1_and_onlya at 2007-7-9 5:31:21 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...