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]
# 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]
# 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]
# 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]