GetParameter() on an uploaded file

I am using a MultipartRequest object to get the file a user uploads (type="file"), and save it to a directory that I specified in the MultipartRequest constructor.
However, I also want to get the parameter value of where the user uploaded the file from the user's machine. I don't know how to do it since you can't use getParameter() when its an uploaded file. Can someone show me how this can be done??? If it makes things easier, I don't even have to save the uploaded file, I just need the parameter value from the user's end.
Thanks!

First use the Apache fileupload package.
            if (FileUpload.isMultipartContent(request)) {
                List files = fileUpload.parseRequest(request);
                Iterator iter = files.iterator();
                String filePath = this.getServletContext().getRealPath("/") +
                                     PushServlet.fileDir + "\\" ;
                while (iter.hasNext()) {
                    FileItem file = (FileItem) iter.next();
                    if (file.isFormField() != true) {
                        System.out.println("file name = " + file.getName());
                        //Code to process the uploaded file
                       } else {
                        System.out.println(">>>>" + file.getFieldName() + " " + file.getString());
                        //Here is where you find the request parameters: subName, pubName, serverName
                        //I know it should be if/else statements
                        if (file.getFieldName().equals("subName")) {
                            subName = file.getString();
                        if (file.getFieldName().equals("pubName")) {
                            pubName = file.getString();
                        if (file.getFieldName().equals("serverName")) {
                            serverName = file.getString();
                } //End while
            } //End if

Similar Messages

  • Request.getParameter() when uploading files

    Hi, I need to upload files and do other works .. such that, in my html ..
    <form name="composer" method="post" ENCTYPE="multipart/form-data">
    <input type=hidden name="a" value="a">
    <input type=File name=inputfile>
    <inpu type=button name=Upload onClick='upload file'>
    <inpu type=button name=otherStuff onClick='do other stuff'>
    </form>
    In the jsp for 'do other stuff', I have the following statement to get the value of a
    String a = request.getParameter("a");
    However, it returns 'null', if I erase the 'ENCTYPE' part from the html file, it works. How can I get it right?

    If your ENCTYPE is multi-part/form-data, then there is another technichque to read the form parameters.
    request.getParameter() won't work.
    first u need to read the requenct explicitely and divide the contents into parameters, files etc. and then read the parameter values.
    you can get a lot of stuff regarding this on web, like 'uploading files using jsp'.
    have fun!!

  • We can use JSR-168 JPS portlet upload file,

    We can use JSR-168 JPS portlet upload file,
    here is the source for you referrence:
    upload file can use JSR168 portlet,
    1,CustomizablePortlet.java File
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.util.ResourceBundle;
    import javax.portlet.*;
    import oracle.webdb.utils.SimpleStringBuffer;
    public class CustomizablePortlet extends GenericPortlet {
    private static final String TITLE_KEY = "title";
    protected static final String OK_ACTION = "ok_action";
    protected static final String APPLY_ACTION = "apply_action";
    protected static final PortletMode PREVIEW_MODE = new PortletMode("preview");
    protected static final PortletMode EDIT_DEFAULTS_MODE = new PortletMode("EDIT_DEFAULTS");
    protected static final PortletMode ABOUT_MODE = new PortletMode("ABOUT");
    public CustomizablePortlet() {
    public String getTitle(RenderRequest request) {
    return request.getPreferences().getValue("title", getPortletConfig().getResourceBundle(request.getLocale()).getString("javax.portlet.title"));
    public void doEdit(RenderRequest request, RenderResponse response) throws PortletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.print("<FORM ACTION=\"");
    out.print(getEditFormSubmitURL(request, response));
    out.println("\" METHOD=\"POST\">");
    out.println("<TABLE BORDER=\"0\">");
    out.println("<TR>");
    out.println("<TD WIDTH=\"20%\">");
    out.println("<P CLASS=\"portlet-form-field\" ALIGN=\"RIGHT\">Title:");
    out.println("</TD>");
    out.println("<TD WIDTH=\"80%\">");
    out.print("<INPUT CLASS=\"portlet-form-input-field\" TYPE=\"TEXT\" NAME=\"");
    out.print("title");
    out.print("\" VALUE=\"");
    out.print(getTitle(request));
    out.println("\" SIZE=\"20\">");
    out.println("</TD>");
    out.println("</TR>");
    out.println("<TR>");
    out.println("<TD COLSPAN=\"2\" ALIGN=\"CENTER\">");
    out.print("<INPUT CLASS=\"portlet-form-button\" TYPE=\"SUBMIT\" NAME=\"");
    out.print("ok_action");
    out.print("\" VALUE=\"OK\">");
    out.print("<INPUT CLASS=\"portlet-form-button\" TYPE=\"SUBMIT\" NAME=\"");
    out.print("apply_action");
    out.print("\" VALUE=\"Apply\">");
    out.println("</TD>");
    out.println("</TR>");
    out.println("</TABLE>");
    out.println("</FORM>");
    protected String getEditFormSubmitURL(RenderRequest request, RenderResponse response) {
    return response.createActionURL().toString();
    public void doHelp(RenderRequest request, RenderResponse response) throws PortletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.print("Help for <i><b>");
    out.print(getTitle(request));
    out.println("</b></i>.");
    public void doAbout(RenderRequest request, RenderResponse response) throws PortletException, IOException {
    String aboutHTML = (new SimpleStringBuffer(30)).append("/about_").append(getPortletName()).append(".html").toString();
    PortletRequestDispatcher rd = getPortletContext().getRequestDispatcher(aboutHTML);
    response.setContentType("text/html");
    if(rd != null) {
    rd.include(request, response);
    } else {
    PrintWriter out = response.getWriter();
    out.print("<p class=\"portlet-font\">This is the about page for ");
    out.print(getTitle(request));
    out.print(".</p><p class=\"portlet-font\">");
    out.print("To customize the contents of this page, create a file named '");
    out.print(aboutHTML.substring(1));
    out.print("' in the Portlet web application's root directory containing HTML ");
    out.print("to appear here. ");
    out.print("Alternatively, override the <code>CustomizablePortlet</code> ");
    out.println("class's <code>doAbout()</code> method.</p>");
    public void doDispatch(RenderRequest request, RenderResponse response) throws PortletException, IOException {
    WindowState state = request.getWindowState();
    if(!state.equals(WindowState.MINIMIZED)) {
    PortletMode mode = request.getPortletMode();
    if(mode.equals(PREVIEW_MODE))
    doView(request, response);
    else
    if(mode.equals(EDIT_DEFAULTS_MODE))
    doEdit(request, response);
    else
    if(mode.equals(ABOUT_MODE))
    doAbout(request, response);
    else
    super.doDispatch(request, response);
    } else {
    super.doDispatch(request, response);
    public void processAction(ActionRequest request, ActionResponse actionResponse) throws PortletException, IOException {
    String newTitle = request.getParameter("title");
    PortletPreferences prefs = request.getPreferences();
    prefs.setValue("title", newTitle);
    prefs.store();
    if(request.getParameter("ok_action") != null) {
    actionResponse.setPortletMode(PortletMode.VIEW);
    actionResponse.setWindowState(WindowState.NORMAL);
    2,FileUploadPortlet.java file
    import java.io.*;
    import javax.activation.DataHandler;
    import javax.mail.MessagingException;
    import javax.mail.internet.MimeBodyPart;
    import javax.portlet.*;
    import oracle.portal.portlet.sample.CustomizablePortlet;
    public class FileUploadPortlet extends CustomizablePortlet
    private static final String FILE_PARAM = "file";
    private static final String SUBMIT_PARAM = "submit";
    private static final String DEFAULT_CHARSET = "ISO-8859-1";
    private static final String uploadRoot = "";
    public FileUploadPortlet()
    public void doView(RenderRequest request, RenderResponse response) throws PortletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.print("<form action=\"");
    out.print(response.createActionURL().toString());
    out.println("\" enctype=\"multipart/form-data\" method=\"post\">");
    out.println("<center><table border=\"0\">");
    out.println("<tr>");
    out.print("<td class=\"portlet-form-field\" align=\"right\">");
    out.print("Please browse to an HTML file:");
    out.println("</td>");
    out.print("<td>");
    out.print("<input class=\"portlet-form-input-field\" type=\"file\" name=\"");
    out.print("file");
    out.print("\">");
    out.println("</td>");
    out.println("</tr>");
    out.println("<tr>");
    out.println("<td colspan=\"2\" align=\"center\">");
    out.print("<input type=\"submit\" class=\"portlet-form-button\" name=\"");
    out.print("submit");
    out.print("\" value=\"Display\">");
    out.println("</td>");
    out.println("</tr>");
    out.println("</table>");
    out.println("</form>");
    String lastFile = request.getPreferences().getValue("file", null);
    if(lastFile != null) {
    out.println("<hr width=\"100%\"><br>");
    out.print(lastFile);
    public void processAction(ActionRequest request, ActionResponse actionResponse) throws PortletException, IOException {
    FormDataParser parsedRequest = new FormDataParser(request);
    MimeBodyPart mbp = parsedRequest.getMimeBodyPart("file");
    if(mbp == null)
    super.processAction(request, actionResponse);
    else
    try {
    String fileName= mbp.getFileName();
    int splash = fileName.lastIndexOf("\\");
    if(splash != -1)
    fileName = fileName.substring(splash +1, fileName.length()).trim();
    String contentType = mbp.getContentType();
    String charSet = getCharsetFromContentType(contentType);
    int sepIndex = contentType.indexOf(';');
    if(sepIndex != -1)
    contentType = contentType.substring(0, sepIndex).trim();
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    mbp.getDataHandler().writeTo(bos);
    bos.close();
    String content = new String(bos.toByteArray(), charSet);
    FileOutputStream fos = new FileOutputStream(fileName);
    fos.write(bos.toByteArray());
    fos.close();
    PortletPreferences prefs = request.getPreferences();
    prefs.setValue("file", fileName + "upload ok");
    prefs.store();
    catch(MessagingException me) {
    throw new PortletException(me);
    public static String getCharsetFromContentType(String contentType) {
    int lastPos;
    if((lastPos = contentType.indexOf(';')) == -1)
    return "ISO-8859-1";
    lastPos++;
    String lowerContentType = contentType.toLowerCase();
    int nextPos;
    do {
    nextPos = lowerContentType.indexOf(';', lastPos);
    String param;
    if(nextPos == -1)
    param = lowerContentType.substring(lastPos).trim();
    else
    param = lowerContentType.substring(lastPos, nextPos).trim();
    if(param.startsWith("charset=") && param.length() > 8)
    return param.substring(8);
    lastPos = nextPos + 1;
    } while(nextPos != -1);
    return "ISO-8859-1";
    3,FormDataParser.java file
    import java.io.*;
    import java.util.*;
    import javax.activation.DataSource;
    import javax.mail.MessagingException;
    import javax.mail.internet.MimeBodyPart;
    import javax.mail.internet.MimeMultipart;
    import javax.portlet.ActionRequest;
    import javax.portlet.PortletException;
    public class FormDataParser {
    private static final String MULTIPART_PREFIX = "multipart/";
    private static final String MULTIPART_FORM_DATA = "multipart/form-data";
    private static final String PLAIN_TEXT = "text/plain";
    private ActionRequest mWrappedRequest;
    private Map mParams;
    private Map mBodyParts;
    private boolean mIsInitialized;
    private boolean mHasMultipart;
    public FormDataParser(ActionRequest request) {
    mWrappedRequest = request;
    public String getParameter(String name) throws PortletException {
    String value = mWrappedRequest.getParameter(name);
    if(value != null)
    return value;
    initParameters();
    if(!mHasMultipart)
    return null;
    List paramList = (List)mParams.get(name);
    if(paramList != null)
    return (String)paramList.get(0);
    else
    return null;
    public String[] getParameterValues(String name) throws PortletException {
    String values[] = mWrappedRequest.getParameterValues(name);
    if(!mHasMultipart)
    return values;
    initParameters();
    List valueList = (List)mParams.get(name);
    if(valueList == null)
    return values;
    int size = valueList.size();
    if(values != null) {
    List newValueList = new ArrayList(values.length + size);
    newValueList.addAll(Arrays.asList(values));
    newValueList.addAll(valueList);
    valueList = newValueList;
    values = new String[size];
    valueList.toArray(values);
    return values;
    public MimeBodyPart getMimeBodyPart(String name) throws PortletException {
    initParameters();
    if(!mHasMultipart) {
    return null;
    } else {
    List parts = (List)mBodyParts.get(name);
    return parts != null ? (MimeBodyPart)parts.get(0) : null;
    public MimeBodyPart[] getMimeBodyParts(String name) throws PortletException {
    initParameters();
    if(!mHasMultipart)
    return null;
    List parts = (List)mBodyParts.get(name);
    if(parts == null) {
    return null;
    } else {
    MimeBodyPart mimeBodyParts[] = new MimeBodyPart[parts.size()];
    parts.toArray(mimeBodyParts);
    return mimeBodyParts;
    private void initParameters() throws PortletException {
    if(mIsInitialized)
    return;
    String contentType = mWrappedRequest.getContentType();
    if(contentType == null) {
    mIsInitialized = true;
    return;
    int sepIndex = contentType.indexOf(';');
    if(sepIndex != -1)
    contentType = contentType.substring(0, sepIndex).trim();
    if(contentType.equalsIgnoreCase("multipart/form-data")) {
    mParams = new HashMap(20);
    mBodyParts = new HashMap(20);
    DataSource ds = new DataSource() {
    public InputStream getInputStream() throws IOException {
    return mWrappedRequest.getPortletInputStream();
    public OutputStream getOutputStream() throws IOException {
    throw new IOException("OutputStream not available");
    public String getContentType() {
    return mWrappedRequest.getContentType();
    public String getName() {
    return getClass().getName();
    try {
    MimeMultipart multipartMessage = new MimeMultipart(ds);
    parseMultiPart(multipartMessage, null);
    catch(MessagingException me) {
    throw new PortletException(me);
    catch(IOException ioe) {
    throw new PortletException(ioe);
    mHasMultipart = true;
    mIsInitialized = true;
    private void parseMultiPart(MimeMultipart multipartMessage, String parentFieldName) throws MessagingException, IOException {
    int partCount = multipartMessage.getCount();
    for(int i = 0; i < partCount; i++) {
    javax.mail.BodyPart part = multipartMessage.getBodyPart(i);
    if(part instanceof MimeBodyPart) {
    MimeBodyPart mimePart = (MimeBodyPart)part;
    String disps[] = mimePart.getHeader("Content-Disposition");
    if(disps != null && disps.length != 0) {
    String disp = disps[0];
    String lcDisp = disp.toLowerCase();
    int nameStart;
    int nameEnd;
    if((nameStart = lcDisp.indexOf("name=\"")) != -1 && (nameEnd = lcDisp.indexOf("\"", nameStart + 6)) != -1)
    parentFieldName = disp.substring(nameStart + 6, nameEnd);
    if(parentFieldName != null)
    if(mimePart.getContentType().toLowerCase().startsWith("multipart/")) {
    Object content = mimePart.getContent();
    if(content instanceof MimeMultipart)
    parseMultiPart((MimeMultipart)content, parentFieldName);
    } else
    if((nameStart = lcDisp.indexOf("filename=\"")) != -1 && (nameEnd = lcDisp.indexOf("\"", nameStart + 10)) != -1) {
    List values = (List)mBodyParts.get(parentFieldName);
    if(values == null) {
    values = new ArrayList(1);
    mBodyParts.put(parentFieldName, values);
    values.add(mimePart);
    } else
    if(mimePart.getContentType().toLowerCase().startsWith("text/plain")) {
    Object content = mimePart.getContent();
    if(content instanceof String) {
    List values = (List)mParams.get(parentFieldName);
    if(values == null) {
    values = new ArrayList(1);
    mParams.put(parentFieldName, values);
    values.add((String)content);
    4.web.xml file
    <?xml version = '1.0' encoding = 'ISO-8859-1'?>
    <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
    <web-app>
    <display-name>hanhuiwen OracleSamplePortlets</display-name>
    <description>hanhuiwen Oracle Sample Portlet Application</description>
    <servlet>
    <servlet-name>portletdeploy</servlet-name>
    <servlet-class>oracle.webdb.wsrp.server.deploy.PortletDeployServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet>
    <servlet-name>portletjaxrpc</servlet-name>
    <servlet-class>com.sun.xml.rpc.server.http.JAXRPCServlet</servlet-class>
    <init-param>
    <param-name>configuration.file</param-name>
    <param-value>/WEB-INF/WSRPService_Config.properties</param-value>
    </init-param>
    </servlet>
    <servlet>
    <servlet-name>portletresource</servlet-name>
    <servlet-class>oracle.webdb.wsrp.server.ResourceServlet</servlet-class>
    </servlet>
    <servlet>
    <servlet-name>ChartServlet</servlet-name>
    <display-name>Chart Servlet</display-name>
    <description>Demo image-generating servlet</description>
    <servlet-class>oracle.portal.portlet.sample.chart.ChartServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet>
    <servlet-name>uix</servlet-name>
    <servlet-class>oracle.cabo.servlet.UIXServlet</servlet-class>
    <init-param>
    <param-name>oracle.cabo.servlet.pageBroker</param-name>
    <param-value>oracle.cabo.servlet.xml.UIXPageBroker</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
    <servlet-name>ChartServlet</servlet-name>
    <url-pattern>/chart*</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
    <servlet-name>portletjaxrpc</servlet-name>
    <url-pattern>/portlets*</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
    <servlet-name>portletresource</servlet-name>
    <url-pattern>/portletresource*</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
    <servlet-name>uix</servlet-name>
    <url-pattern>*.uix</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
    <servlet-name>uix</servlet-name>
    <url-pattern>/uix/*</url-pattern>
    </servlet-mapping>
    <session-config>
    <session-timeout>60</session-timeout>
    </session-config>
    <welcome-file-list>
    <welcome-file>index.uix</welcome-file>
    </welcome-file-list>
    <!--
    LogLevel controls the amount of information logged. There are 7 log levels:
    0 - logging disabled
    1 - configuration
    2 - severe error
    3 - warning
    4 - throwing exception
    5 - performance
    6 - information
    7 - debug
    The oracle.portal.log.Logger interface defines methods that map to these 7
    log levels. However, there are also 2 methods that do not map to log
    levels. These methods are included for backwards compatibility and data
    logged using these methods will always be logged regardless of the log level.
    -->
    <env-entry>
    <env-entry-name>oracle/portal/log/logLevel</env-entry-name>
    <env-entry-type>java.lang.Integer</env-entry-type>
    <env-entry-value>7</env-entry-value>
    </env-entry>
    </web-app>
    5.portlet.xml
    <?xml version = '1.0' encoding = 'UTF-8'?>
    <portlet-app xmlns="http://java.sun.com/xml/ns/portlet/portlet-app_1_0.xsd" version="1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/portlet/portlet-app_1_0.xsd http://java.sun.com/xml/ns/portlet/portlet-app_1_0.xsd">
    <portlet>
    <description xml:lang="en">A portlet that demonstrates the file upload features of the Java Portlet Specification.</description>
    <portlet-name>FileUpload</portlet-name>
    <portlet-class>FileUploadPortlet</portlet-class>
    <expiration-cache>0</expiration-cache>
    <supports>
    <mime-type>text/html</mime-type>
    <portlet-mode>help</portlet-mode>
    <portlet-mode>about</portlet-mode>
    <portlet-mode>edit_defaults</portlet-mode>
    </supports>
    <supported-locale>en</supported-locale>
    <portlet-info>
    <title>File Upload Portlet</title>
    <short-title>File Upload</short-title>
    <keywords>File,Upload, Portlet</keywords>
    </portlet-info>
    </portlet>
    <custom-portlet-mode>
    <description xml:lang="en">This mode should be used by the portlet to display information on the portlet's purpose, origin, version, etc.</description>
    <portlet-mode>about</portlet-mode>
    </custom-portlet-mode>
    <custom-portlet-mode>
    <description xml:lang="en">This mode signifies that the portlet should render a screen to set the default values for the modifiable preferences that are typically changed in the EDIT screen. Calling this mode requires that the user must have administrator rights.</description>
    <portlet-mode>edit_defaults</portlet-mode>
    </custom-portlet-mode>
    <custom-portlet-mode>
    <description xml:lang="en">This mode should be used by the portlet to render output without the need of having back-end connections or user specific data available.</description>
    <portlet-mode>preview</portlet-mode>
    </custom-portlet-mode>
    <user-attribute>
    <name>user.name.given</name>
    </user-attribute>
    <user-attribute>
    <name>user.name.family</name>
    </user-attribute>
    <user-attribute>
    <name>user.name.middle</name>
    </user-attribute>
    <user-attribute>
    <name>user.name.nickname</name>
    </user-attribute>
    <user-attribute>
    <name>user.bdate</name>
    </user-attribute>
    <user-attribute>
    <name>user.business-info.online.email</name>
    </user-attribute>
    </portlet-app>

    Hello i had exactly the same error, but not with file upload.
    I'm sure you have in your application lib directory to jars which aren't compatible to each other.
    And the problem occured between my myfaces and tomahawk jars .
    See this page:
    http://wiki.apache.org/myfaces/CompatibilityMatrix
    It tells you which myfaces and tomahawk jars you can use together.
    Hope it can help.
    bye

  • Fileaccess.httpUploadBean doesn't upload file in Jdevelper 9.0.3

    Hi,
    I am using Jdevelper 9.0.3 to develop a jsp Based File Upload Utility.
    I have attached Liberary "JSP RUNTIME" which reffers to "ojsp.jar","ojsputil.jar","oc4j.jar","servlet.jar","ojc.jar".
    while running the code for file upload, file doesn't get uploaded. I am not getting any exceptions too.
    But the same pease of code with same liberary "JSP RUNTIME" is working absolutly fine(Uploading File), when i am running it using Jdeveloper10.1.2, and This is Strange to me.Actualy i need to use Jdeveloper9.0.3 only.Please let me know if any patch is required to apply in Jdeveloper9.0.3.
    Please find the code below and help.
    fileaccess.properties
    fileaccess.basedir = C:/
    fileUpload.jsp
    <html><body>
    <form name = "formname" action="beanUploadExample.jsp" method=POST ENCTYPE="multipart/form-data" />
    <br>MailID: <INPUT TYPE="text" NAME="strMailId" />
    <br> File to upload: <INPUT TYPE="FILE" NAME="File" SIZE="50" MAXLENGTH="120" >
    <br><INPUT TYPE="Submit" NAME="Submit" VALUE="Send" >
    <INPUT type="reset" name="reset" value = "Cancel">
    </form>
    </body></html>
    beanUploadExample.jsp
    <%@ page contentType="text/html;charset=windows-1252"%>
    <%@ page language="java"
    import="java.util.*,java.io.*, oracle.jsp.webutil.fileaccess.*" %>
    <html><body>
    <SCRIPT language="JavaScript">
    function formAction()
    if (document.upForm.forward.value == "true")
    {//tOMORROW PASS THE FILE NAME WITH ACTION PARAM
    //alert("Submit");
    document.upForm.action = "uploadco"
    document.upForm.submit();
    </SCRIPT>
    <Form name="upForm" method ="post" > <!--action ="beanUploadExample.jsp" >-->
    <%
    String userdir = "Test";
    String strFlag = "";
    String strFileName ="";
    String strDirName ="";
    String strAbsoluteName ="";
    %>
    <jsp:useBean id="upbean"
    class="oracle.jsp.webutil.fileaccess.HttpUploadBean" >
    <jsp:setProperty name="upbean" property="destination" value="<%=userdir%"/>
    </jsp:useBean>
    <%
    try{
    upbean.setBaseDir(application, request);
    String str = upbean.getDestination();
    // application.getServletContextName();
    //out.println("The Servlet Context is "+strContext) ;
    out.println("The value of Destination is "+str) ;
    upbean.upload(request);
    String name = upbean.getParameter("strMailId");
    out.println("name-----:::::: "+name) ;
    String strDestType = upbean.getDestinationType();
    out.println("strDestType-----:::::: "+strDestType) ;
    Enumeration fileNames = upbean.getFileNames();
    while (fileNames.hasMoreElements()) {
    strFlag = "true";
    strFileName = (String)fileNames.nextElement();
    out.println("strFileName File Name Is:::::"+strFileName);
    strAbsoluteName = strFileName.substring(4,strFileName.length());
    catch(IOException ex)
    out.println("IOException is =="+ex.toString());
    catch(Exception ex)
    out.println("IOException is =="+ex.toString());
    %>
    <table width = 50% align="center" >
    <tr>
    <td align ="center"><input type = "Button" name ="Submit" value="Ok" onclick="formAction()" ></td></tr></table>
    </Form>
    </body></html>

    Hi,
    I am using Jdevelper 9.0.3 to develop a jsp Based File Upload Utility.
    I have attached Liberary "JSP RUNTIME" which reffers to "ojsp.jar","ojsputil.jar","oc4j.jar","servlet.jar","ojc.jar".
    while running the code for file upload, file doesn't get uploaded. I am not getting any exceptions too.
    But the same pease of code with same liberary "JSP RUNTIME" is working absolutly fine(Uploading File), when i am running it using Jdeveloper10.1.2, and This is Strange to me.Actualy i need to use Jdeveloper9.0.3 only.Please let me know if any patch is required to apply in Jdeveloper9.0.3.
    Please find the code below and help.
    fileaccess.properties
    fileaccess.basedir = C:/
    fileUpload.jsp
    <html><body>
    <form name = "formname" action="beanUploadExample.jsp" method=POST ENCTYPE="multipart/form-data" />
    <br>MailID: <INPUT TYPE="text" NAME="strMailId" />
    <br> File to upload: <INPUT TYPE="FILE" NAME="File" SIZE="50" MAXLENGTH="120" >
    <br><INPUT TYPE="Submit" NAME="Submit" VALUE="Send" >
    <INPUT type="reset" name="reset" value = "Cancel">
    </form>
    </body></html>
    beanUploadExample.jsp
    <%@ page contentType="text/html;charset=windows-1252"%>
    <%@ page language="java"
    import="java.util.*,java.io.*, oracle.jsp.webutil.fileaccess.*" %>
    <html><body>
    <SCRIPT language="JavaScript">
    function formAction()
    if (document.upForm.forward.value == "true")
    {//tOMORROW PASS THE FILE NAME WITH ACTION PARAM
    //alert("Submit");
    document.upForm.action = "uploadco"
    document.upForm.submit();
    </SCRIPT>
    <Form name="upForm" method ="post" > <!--action ="beanUploadExample.jsp" >-->
    <%
    String userdir = "Test";
    String strFlag = "";
    String strFileName ="";
    String strDirName ="";
    String strAbsoluteName ="";
    %>
    <jsp:useBean id="upbean"
    class="oracle.jsp.webutil.fileaccess.HttpUploadBean" >
    <jsp:setProperty name="upbean" property="destination" value="<%=userdir%"/>
    </jsp:useBean>
    <%
    try{
    upbean.setBaseDir(application, request);
    String str = upbean.getDestination();
    // application.getServletContextName();
    //out.println("The Servlet Context is "+strContext) ;
    out.println("The value of Destination is "+str) ;
    upbean.upload(request);
    String name = upbean.getParameter("strMailId");
    out.println("name-----:::::: "+name) ;
    String strDestType = upbean.getDestinationType();
    out.println("strDestType-----:::::: "+strDestType) ;
    Enumeration fileNames = upbean.getFileNames();
    while (fileNames.hasMoreElements()) {
    strFlag = "true";
    strFileName = (String)fileNames.nextElement();
    out.println("strFileName File Name Is:::::"+strFileName);
    strAbsoluteName = strFileName.substring(4,strFileName.length());
    catch(IOException ex)
    out.println("IOException is =="+ex.toString());
    catch(Exception ex)
    out.println("IOException is =="+ex.toString());
    %>
    <table width = 50% align="center" >
    <tr>
    <td align ="center"><input type = "Button" name ="Submit" value="Ok" onclick="formAction()" ></td></tr></table>
    </Form>
    </body></html>

  • Unable to retrive the uploaded file in Struts

    hi i am getting error while retrieving the uploaded file in struts. The code is
    struts-config.xml
    ===========
    <form-bean name="GreivanceForm" type="org.apache.struts.validator.DynaValidatorActionForm" >
                   <form-property name="compcode" type="java.lang.String" />
                   <form-property name="complaintName" type="java.lang.String" />
                   <form-property name="category" type="java.lang.String" />
                   <form-property name="subcategory" type="java.lang.String" />
                   <form-property name="priority" type="java.lang.String" />
                   <form-property name="occdate" type="java.lang.String" />
                   <form-property name="occtime" type="java.lang.String" />
                   <form-property name="desc" type="java.lang.String" />
                   <form-property name="comments" type="java.lang.String" />
                   <form-property name="onbehalf" type="java.lang.String"/>
                   <form-property name="employeeId" type="java.lang.String"/>
                   <form-property name="hidSelectedNames" type="java.lang.String"/>
                   <form-property name="individual" type="java.lang.String"/>
                   <form-property name="compOption" type="java.lang.String" />
                   <form-property name="selectedrequestor" type="java.lang.String" />
                   <form-property name="file" type="java.lang.String"/>
              </form-bean>
    <action path="/helpdesk/GrievanceComplaint"
                   type="com.srit.hrnet.helpdesk.grievancemechanism.GrievanceComplaintAction"
                   scope="request" name="GreivanceForm"
                   input=""
                   validate="true"
                   parameter="compOption" >
                   <forward name="success" path="/helpdesk/GrievanceRedressalMechanism/ComplaintDetails.jsp"/>
                   <forward name="showmeetingform" path="/helpdesk/complaint/MeetingDetailsForm.jsp"/>
                   <forward name="transconfirm" path="/helpdesk/GrievanceRedressalMechanism/TransConfirm.jsp"/>
                   <forward name="ViewCompForm" path="/helpdesk/GrievanceRedressalMechanism/ViewCompForm.jsp"/>
              </action>
    and
    Actionclass:
    ========
    * Created on Nov 5, 2004
    * TODO To change the template for this generated file go to
    * Window - Preferences - Java - Code Style - Code Templates
    package com.srit.hrnet.helpdesk.grievancemechanism;
    import java.io.BufferedInputStream;
    import java.io.BufferedOutputStream;
    import java.io.ByteArrayOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.util.ArrayList;
    import java.util.Date;
    import java.util.GregorianCalendar;
    import java.util.List;
    import java.util.StringTokenizer;
    import javax.servlet.ServletException;
    import javax.servlet.ServletOutputStream;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    import org.apache.commons.beanutils.BeanUtils;
    import org.apache.struts.action.ActionError;
    import org.apache.struts.action.ActionErrors;
    import org.apache.struts.action.ActionForm;
    import org.apache.struts.action.ActionForward;
    import org.apache.struts.action.ActionMapping;
    import org.apache.struts.action.ActionMessage;
    import org.apache.struts.action.ActionMessages;
    import org.apache.struts.action.DynaActionForm;
    import org.apache.struts.actions.DispatchAction;
    import org.apache.struts.upload.FormFile;
    import org.apache.struts.validator.DynaValidatorActionForm;
    import org.apache.struts.validator.DynaValidatorForm;
    import com.srit.hrnet.components.SequenceCodeGenerator;
    import com.srit.hrnet.emp.EmployeeGenTO;
    import com.srit.hrnet.emp.courier.CourierMailDAO;
    import com.srit.hrnet.emp.courier.CourierMailTO;
    import com.srit.hrnet.emp.parameter.ParamMasterTO;
    import com.srit.hrnet.helpdesk.SessionValidate;
    import com.srit.hrnet.helpdesk.category.CategoryDAO;
    import com.srit.hrnet.helpdesk.category.CategoryTO;
    import com.srit.hrnet.helpdesk.mails.HDMail;
    import com.srit.hrnet.utilities.DateUtilities;
    import com.srit.hrnet.helpdesk.complaint.TaskDAO;
    import com.srit.hrnet.helpdesk.SessionValidate;
    import com.srit.hrnet.helpdesk.grievancemechanism.GrievanceComplaintForm;
    public class GrievanceComplaintAction extends DispatchAction{
         public ActionForward submitForm(ActionMapping mapping,
                   ActionForm form, HttpServletRequest request,
                   HttpServletResponse response)throws ServletException,IOException {  
                   String msg=null;
                   DynaValidatorActionForm objDyna = (DynaValidatorActionForm)form;
                   GrievanceComplaintDAO gcDao= new GrievanceComplaintDAO();
              ActionForward forward = new ActionForward();
    //          GrievanceComplaintForm gcForm=(GrievanceComplaintForm)form;
                        String CompId = null;
              try
                             SequenceCodeGenerator seq=new SequenceCodeGenerator("GrievanceMechanism");
                             CompId=seq.generateCode();
                   GrievanceComplaintTO gcTO=new GrievanceComplaintTO();
                   System.out.println("Inside GrievanceComplaintAction ......");
                   String CompName=request.getParameter("complaintName");
                   String Category=request.getParameter("category");
                   String prority=request.getParameter("priority");
                   String dateofocc=request.getParameter("occdate");
                   String timeofocc=request.getParameter("occtime");
                   String desc=request.getParameter("desc");
                   String comments=request.getParameter("comments");
    //          String file=request.getParameter("file");
    //          String complaintcode = .generateCode();
                   System.out.println("Inside insert()::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::");
                   System.out.println("Name Of the Complaint name>>>>>>>>>>>>>>"+CompName);
                   System.out.println("Name Of the Categoryt>>>>>>>>>>>>>>"+Category);
                   System.out.println("Name Of the prority>>>>>>>>>>>>>>"+prority);
                   System.out.println("Name Of the dateofocc>>>>>>>>>>>>>>"+dateofocc);
                   System.out.println("Name Of the timeofocc>>>>>>>>>>>>>>"+timeofocc);
                   System.out.println("Name Of the desc>>>>>>>>>>>>>>"+desc);
                   System.out.println("Name Of the comments>>>>>>>>>>>>>>"+comments);
    //          System.out.println("Name Of the file>>>>>>>>>>>>>>"+file);
                   GregorianCalendar occdate=DateUtilities.getGCDateForString(objDyna.getString("occdate"),((com.srit.hrnet.emp.EmployeeGenTO)request.getSession().getAttribute("LoginUser")).getDateFormat(),'/');
                   gcTO.setComplaintCode(CompId);
                   gcTO.setComplaintName(CompName);
                   gcTO.setCategory(Category);
                   gcTO.setPriority(prority);
                   gcTO.setOccdate(occdate);
                   System.out.println("After Setting date in GTO is>>>>>>>>>>>>>>"+gcTO.getOccdate());
                   gcTO.setOcctime(timeofocc);
                   gcTO.setDesc(desc);
                   gcTO.setComments(comments);
                        HDMail mailComp = new HDMail();
                   String errorFlag = null;
                   String filePath = ""+objDyna.get("file");// Attachment path
                   StringTokenizer st=new StringTokenizer(filePath,".");
                   String extension=null;
    //               String filename=null;
                   String attachmentPath = null;
                   while(st.hasMoreTokens())
                        extension=st.nextToken();
    //          while(st1.hasMoreTokens()){
    //               filename=st1.nextToken();
                   System.out.println("Attachment path : "+attachmentPath);
              System.out.println("Extension is.........."+extension);
    //          System.out.println("Name of the file is.............."+filename);
              if(filePath != null && filePath.indexOf(".") != -1 && filePath.length()>=5 ){// If attachment exists
    //               attachmentPath = filePath.substring(filePath.indexOf(".")+1,filePath.length());// file extension
    ////               System.out.println("Attachment path : "+attachmentPath);
                   if(!extension.equalsIgnoreCase("txt") && !extension.equalsIgnoreCase("htm")
                             &&!extension.equalsIgnoreCase("doc") &&!extension.equalsIgnoreCase("rtf")
                                       &&!extension.equalsIgnoreCase("msg") &&!extension.equalsIgnoreCase("oft")
                                       && !extension.equalsIgnoreCase("xls")){
                        errorFlag = "1"; // if the file is not a valid type (not in the above mentioned extensions)
              gcTO.setAttachmentName(filePath);
              if(errorFlag.equals("1")){
    //          String attachmentName = null;
    ////          String attachmentPath = request.getParameter("agendaAttachment");
    //          DynaValidatorForm dyna=(DynaValidatorForm)form;
    //                         FormFile file= (FormFile)objDyna.get("file");
    //                         //dyna.get("file");      
    //          System.out.println("Name of the file after casting....."+file.getFileName());
    //                         if(file!=null && file.getFileName()!=null && !file.getFileName().trim().equals("")){
    //                              String fileName = null;                         
    //                              fileName = file.getFileName();
    //                              attachmentName = fileName;
    //                              if(validFile(fileName))
    //                              writeFile(file,request,fileName);
    //                              else
    //                                   ActionMessages errors=new ActionMessages();
    //                                   errors.add("Err:MsgDesc",new ActionMessage("com.srit.hrnet.helpdesk.complaint.form.fileupload"));                              
    //                                   saveErrors(request,errors);                         
    ////                                   ActionForward map1 = submitSubCategory(mapping,form,request,response);                              
    //                                   resetToken(request);     
    //                                   saveToken(request);
    //                                   return mapping.findForward("ViewCompForm");                              
    //                    int recordexists = gcDao.getComplaint(CompId);
    //                    if(recordexists == 1){
    //                         System.out.println("Calling the update method");
    //                         gcDao.updateComplaintDetails(gcTO);     
    //                    }else{
                        boolean retVal=gcDao.insert(gcTO);
              if (retVal){
                   System.out.println("Record Inserted inside Action.");
                   msg = "<font color='blue'>Record Inserted Successfully .</font>";
                             request.setAttribute("status", msg);
              else{
                   System.out.println("Unable to insert Record inside Action.");
                   msg = "<font color='red'>Unable to insert Record .</font>";
                             request.setAttribute("status", msg);
              else
                   System.out.println("Upload a file of extension(.jpg,.gif,.doc,.htm,.xls,.rtf,oft,msg) inside Action.");
                   msg = "<font color='red'>Upload a file of extension(.jpg,.gif,.doc,.htm,.xls,.rtf,.oft,.msg) </font>";
                             request.setAttribute("status", msg);
              catch (Exception e) {
                   // TODO: handle exception
                   System.out.println("Exception Occurred inside insert action....."+e.getMessage());
                   e.printStackTrace();
    //          else
    //               String insStatus="10";
    //               System.out.println("Accept:Redirecting due to resubmission");
    //               request.setAttribute("transStatus",insStatus);
    //               forward =mapping.findForward("transconfirm");
                   return mapping.findForward("success");
         public boolean validFile(String fileName){
              if(!fileName.equals("")){     
                        int filelength=fileName.length();
                        int sublength= fileName.indexOf('.');
                        String extension = fileName.substring(sublength+1,filelength);
                        if(extension.trim().equalsIgnoreCase("msg") || extension.trim().equalsIgnoreCase("txt") || extension.trim().equalsIgnoreCase("xls") || extension.trim().equalsIgnoreCase("ppt") || extension.trim().equalsIgnoreCase("jpg") || extension.trim().equalsIgnoreCase("gif")|| extension.trim().equalsIgnoreCase("doc" )|| extension.trim().equalsIgnoreCase("pdf") || extension.trim().equalsIgnoreCase("wmv") || extension.trim().equalsIgnoreCase("zip") || extension.trim().equalsIgnoreCase("jpeg") || extension.trim().equalsIgnoreCase("xml") || extension.trim().equalsIgnoreCase("html") ||extension.trim().equalsIgnoreCase("bmp") ||extension.trim().equalsIgnoreCase("htm") ||extension.trim().equalsIgnoreCase("ppt")||extension.trim().equalsIgnoreCase("oft")||extension.trim().equalsIgnoreCase("csv")){
                        return true;
                        }else{
                        return false;
                   return true;
         public int writeFile(FormFile file,HttpServletRequest request,String fileName){
                   int retValue = 0;
                   String size = (file.getFileSize() + " bytes");
                   if(file.getFileSize()>0){
                        //System.out.println("The size of the file is :" + file.getFileSize() + " bytes");
                        String data = null;
                        try {
                             //retrieve the file data
                             String fileTodelete = request.getRealPath("/helpdesk/meetingsagenda/"+fileName);
                             boolean success = (new File(fileTodelete)).delete();
                             //System.out.println("sucess......"+success);          
                             ByteArrayOutputStream baos = new ByteArrayOutputStream();
                             InputStream stream = file.getInputStream();
                             //write the file to the file specified
                             System.out.println("sfsdfkjdsfds "+request.getRealPath("/helpdesk/meetingsagenda/"+fileName));
                             OutputStream bos = new FileOutputStream(request.getRealPath("/helpdesk/meetingsagenda/"+fileName));
                             int bytesRead = 0;
                             byte[] buffer = new byte[8192];
                                  while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
                                       bos.write(buffer, 0, bytesRead);
                             bos.close();
                             data =      "The file has been written to \""+ "/helpdesk/meetingsagenda/"+ "\"";
                             System.out.println("data........."+data);
                                  //close the stream
                             stream.close();
                        }catch(FileNotFoundException fnfe) {
                                  System.out.println("com.srit.hrnet.homepage.fromceo.FromCEOAction.writeFile.Exception :"+ fnfe.toString());
                                  fnfe.printStackTrace();
                                  //retValue = FORMFILE_FILE_NA;
                        }catch(IOException ioe) {
                                  System.out.println("com.srit.hrnet.homepage.fromceo.FromCEOAction.writeFile.Exception :"+ ioe.toString());
                                  ioe.printStackTrace();
                                  //retValue = FORMFILE_ERR_UPD;
                   }//end of try catch:~
                   }else{
                        //The file was a not available
                        //retValue = FORMFILE_SIZE_ZERO;
                   }//end of if else:~
              //     System.out.println("retValue........."+retValue);
                   return retValue;                         
    }//end of ComplaintAction
    and GrievanceFormTO:(Dummy form bean)
    ==========
    * Created on Nov 4, 2004
    * TODO To change the template for this generated file go to
    * Window - Preferences - Java - Code Style - Code Templates
    package com.srit.hrnet.helpdesk.grievancemechanism;
    import java.util.GregorianCalendar;
    import org.apache.struts.upload.FormFile;
    public class GrievanceComplaintTO implements java.io.Serializable {
    private String complaintCode;
    private String compcode; //complaind Id
    private String complaintName;
    private String category;
    private String priority;
    //private GregorianCalendar date;
    private FormFile theFile;
    private String compOption;
    private String desc;
    private String comments;
    private String status;
    private String serviceperson;     //employee who is going to serve the complaint.Applicatble only in case of manual flow.
    private String loggedEmpId; //the employee who has logged the complaint
    private String applyEmpId; //employee to whom the cmplaint belongs to or owner of the complaint
    private String associateComm;
    private String associateRating;
    private GregorianCalendar occdate;
    private String occtime;
    private String attachmentName;
         public String getApplyEmpId() {
              return applyEmpId;
         public void setApplyEmpId(String applyEmpId) {
              this.applyEmpId = applyEmpId;
         public String getAssociateComm() {
              return associateComm;
         public void setAssociateComm(String associateComm) {
              this.associateComm = associateComm;
         public String getAssociateRating() {
              return associateRating;
         public void setAssociateRating(String associateRating) {
              this.associateRating = associateRating;
         public String getCategory() {
              return category;
         public void setCategory(String category) {
              this.category = category;
         public String getComments() {
              return comments;
         public void setComments(String comments) {
              this.comments = comments;
         public String getCompcode() {
              return compcode;
         public void setCompcode(String compcode) {
              this.compcode = compcode;
         public String getComplaintName() {
              return complaintName;
         public void setComplaintName(String complaintName) {
              this.complaintName = complaintName;
         public String getCompOption() {
              return compOption;
         public void setCompOption(String compOption) {
              this.compOption = compOption;
         public String getDesc() {
              return desc;
         public void setDesc(String desc) {
              this.desc = desc;
         public String getLoggedEmpId() {
              return loggedEmpId;
         public void setLoggedEmpId(String loggedEmpId) {
              this.loggedEmpId = loggedEmpId;
         public String getOcctime() {
              return occtime;
         public void setOcctime(String occtime) {
              this.occtime = occtime;
         public String getPriority() {
              return priority;
         public void setPriority(String priority) {
              this.priority = priority;
         public String getServiceperson() {
              return serviceperson;
         public void setServiceperson(String serviceperson) {
              this.serviceperson = serviceperson;
         public String getStatus() {
              return status;
         public void setStatus(String status) {
              this.status = status;
         public String getComplaintCode() {
              return complaintCode;
         public void setComplaintCode(String complaintCode) {
              this.complaintCode = complaintCode;
         public void setOccdate(GregorianCalendar occdate) {
              this.occdate = occdate;
         public GregorianCalendar getOccdate() {
              return occdate;
         public String getAttachmentName() {
              return attachmentName;
         public void setAttachmentName(String attachmentName) {
              this.attachmentName = attachmentName;
         public FormFile getTheFile() {
              return theFile;
         public void setTheFile(FormFile theFile) {
              this.theFile = theFile;
    but i am getting error
    javax.servlet.ServletException: BeanUtils.populate
         org.apache.struts.util.RequestUtils.populate(RequestUtils.java:497)
         org.apache.struts.action.RequestProcessor.processPopulate(RequestProcessor.java:798)
         org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:205)
         org.apache.struts.action.ActionServlet.process(ActionServlet.java:1164)
         org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:415)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:709)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
         com.srit.hrnet.filter.SessionValidateFilter.doFilter(SessionValidateFilter.java:81)
    root cause
    org.apache.commons.beanutils.ConversionException: Cannot assign value of type 'org.apache.struts.upload.CommonsMultipartRequestHandler$CommonsFormFile' to property 'file' of type 'java.lang.String'
         org.apache.struts.action.DynaActionForm.set(DynaActionForm.java:424)
         org.apache.commons.beanutils.PropertyUtilsBean.setSimpleProperty(PropertyUtilsBean.java:1733)
         org.apache.commons.beanutils.PropertyUtilsBean.setNestedProperty(PropertyUtilsBean.java:1648)
         org.apache.commons.beanutils.PropertyUtilsBean.setProperty(PropertyUtilsBean.java:1677)
         org.apache.commons.beanutils.BeanUtilsBean.setProperty(BeanUtilsBean.java:1022)
         org.apache.commons.beanutils.BeanUtilsBean.populate(BeanUtilsBean.java:811)
         org.apache.commons.beanutils.BeanUtils.populate(BeanUtils.java:298)
         org.apache.struts.util.RequestUtils.populate(RequestUtils.java:495)
         org.apache.struts.action.RequestProcessor.processPopulate(RequestProcessor.java:798)
         org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:205)
         org.apache.struts.action.ActionServlet.process(ActionServlet.java:1164)
         org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:415)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:709)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
         com.srit.hrnet.filter.SessionValidateFilter.doFilter(SessionValidateFilter.java:81)
    and my jsp is:
    =========
    <%@ page language="java" %>
    <%@ taglib uri="struts-bean" prefix="bean" %>
    <%@ taglib uri="struts-html" prefix="html" %>
    <%@ taglib uri="struts-logic" prefix="logic" %>
    <%@ taglib uri="TabGenerator" prefix="GenerateTab" %>
    <%@ page import="com.srit.hrnet.utilities.DateUtilities"%>
    <%@ page import="com.srit.hrnet.components.BasicDAOConstants" %>
    <%@ taglib uri="AccessLogin" prefix="GeneralAccess" %>
    <%@ taglib uri="iterateTag" prefix="iterateTag" %>
    <%@ page import="com.srit.hrnet.components.BasicDAOConstants,com.srit.hrnet.emp.EmployeeGenTO,com.srit.hrnet.helpdesk.grievancemechanism.*"%>
    <%@ page import="com.srit.hrnet.tags.*"%>
    <html:html locale="true">
    <HEAD>
         <TITLE>
                   <bean:message key="com.srit.hrnet.helpdesk.complaint.form.title"/>
         </TITLE>
         <META NAME="Generator" CONTENT="EditPlus">
         <META NAME="Author" CONTENT="">
         <META NAME="Keywords" CONTENT="">
         <META NAME="Description" CONTENT="">
    <link rel="stylesheet" type="text/css" href="<%= (session.getAttribute("LoginUser") != null ?
                             ((com.srit.hrnet.emp.EmployeeGenTO)session.getAttribute("LoginUser")).getEmpPageStyleSheet() :
                             com.srit.hrnet.components.access.AccessCodes.GLOBAL_STYLESHEET)%>">
    <script language="javaScript" src="<%= request.getContextPath()%>/jscript/GlobalValidationScript.js" purpose="include"></script>
    <%      
    int dateFormat = (session.getAttribute("LoginUser") != null ? ((com.srit.hrnet.emp.EmployeeGenTO)session.getAttribute("LoginUser")).getDateFormat() : 2);
         System.out.println("/reports/training/TRngBaseReport dateFormat = "+dateFormat);
         /* *** get the current date *** */
         java.util.GregorianCalendar gc1 = new java.util.GregorianCalendar();
         int yy = gc1.get(java.util.Calendar.YEAR);
         int mm = gc1.get(java.util.Calendar.MONTH);
         int dd = gc1.get(java.util.Calendar.DATE);     
         mm = mm + 1;
         String mon;
         String day;
         if(dd <= 9)
              day = "0" + java.lang.String.valueOf(dd);
         else
              day = java.lang.String.valueOf(dd);
         if(mm <= 9)
              mon = "0" + java.lang.String.valueOf(mm);
         else
              mon = java.lang.String.valueOf(mm);
         java.lang.String currentDate = "";
         if(dateFormat == 3){
              currentDate = java.lang.String.valueOf(yy+"/"+mon+"/"+day);/* (yyy-mm-dd format) */
         }else if(dateFormat == 1){
              currentDate = java.lang.String.valueOf(mon+"/"+day+"/"+yy);/* (mm-dd-yyy format) */
         }else if(dateFormat == 2){
              currentDate = java.lang.String.valueOf(day+"/"+mon+"/"+yy);/* (dd-mm-yyy format) */
         System.out.println("/reports/training/TRngBaseReport currentDate = "+currentDate);
    %>
    <script language="javaScript" src="<%= (session.getAttribute("LoginUser")!=null ? ((com.srit.hrnet.emp.EmployeeGenTO)session.getAttribute("LoginUser")).getScriptFile() : "")%>" purpose="include"></script>
    <script language="javaScript" src="jscript/CommonDialog.js" purpose="include"></script>
    <script language="javaScript" src="jscript/GlobalValidationScript.js"></script>
    <script language="javascript">
         var gNow = new Date("<%=currentDate%>");
         function val_complaint()
    if(document.GreivanceForm.complaintName.value.length==0)
         alert("Enter Complaint Name");
         document.GreivanceForm.complaintName.focus();
         return false;
    if(document.GreivanceForm.category.value =='NA')
         alert("select category");
         document.GreivanceForm.category.focus();
         return false;
    if(document.GreivanceForm.priority.value == 'NA')
         alert("select priority");
         document.GreivanceForm.priority.focus();
         return false;
         if(document.GreivanceForm.occdate.value == "")
              alert("Enter Date (dd/mm/yy)");
              document.GreivanceForm.occdate.focus();
              return false;
         else     
         if(document.GreivanceForm.occdate.value>document.GreivanceForm.currentDate.value){
                   alert("select Previous or Current date");
                   document.GreivanceForm.occdate.focus();
                   return false;
         if(document.GreivanceForm.occtime.value == "")
         alert("Select Time of Occurence.");
         document.GreivanceForm.occtime.focus();
         return false;
    else
    if(!IsValidTime(document.GreivanceForm.occtime.value) )
    alert("Enter Valid Time (HH:MM)");
              return false;
         if(document.GreivanceForm.desc.value == "")
         alert("Enter Description");
         document.GreivanceForm.desc.focus();
         return false;
              document.forms[0].compOption.value='submitForm';
              document.forms[0].submit();
              return false;
         function IsValidTime(givenTime)
              var hour = 0;
              var minute = 0;
              var timePat = /^(\d{1,2}):(\d{1,2})?$/;
              var matchArray = givenTime.match(timePat);
              if (matchArray == null)
                   alert("Enter Valid Time.");
                   return false;
              hour = matchArray[1];
              minute = matchArray[2];
              if(hour==0 && minute==0)
              alert("The Time You Entered is 0:0");
              return false;
              if (hour < 0 || hour > 23)
              alert("Hour must be between 0 and 23");
              return false;
              if (minute<0 || minute > 59)
              alert ("Minute must be between 0 and 59.");
              return false;
              return true;
    unction help(url)
         var attributes = 'menubar=no,toolbar=no,location=no,width=625,height=375,resizable=yes';
         var name = 'Help';
         window.open(url,name,attributes);
    //return false;
    </script>
    <script language = "javaScript" src = "<%=request.getContextPath()%>/jscript/CommonDialog.js" purpose = "include"></script>
    </HEAD>
    <body bgcolor="#FFFFFF" onload="setFocus()">
    <GenerateTab:displaytabs tabId="<%=com.srit.hrnet.masters.gui.GUIConstants.HD_GRIEVANCE_REDRESSAL_FORM%>" activeSubTab="0" >
    <table align="right">
              <tr>
                   <td>
                        <img src="<%=request.getContextPath()%>/images/help.gif" border="0" alt="Help">
                   </td>     
              </tr>     
         </table>
         <html:form action="/helpdesk/GrievanceComplaint" enctype="multipart/form-data" method="POST" onsubmit="javascript:return val_complaint()">
         <html:hidden property="compOption" value="submitForm" />
         <html:hidden property="onbehalf"/>
         <html:hidden property="employeeId"/>
         <html:hidden property="hidSelectedNames"/>
         <html:hidden property="selectedrequestor"/>
         <html:hidden property="individual"/>
         <table cellpadding="3" cellspacing="0" align="center" >
              <th align="center" class="tablehead" colspan="2">
              <b> Complaint Form </b>
              </th>
    <tr>
                   <td colspan="1" class='tablesubhead'>
                   <b><bean:message key="com.srit.hrnet.helpdesk.redressal.form.complaintname"/></b><font class="star"> *</font>
                   </td>
                   <td class='subhead'>
                   <html:text property="complaintName" maxlength="99"/>
                   </td>
              </tr>
         <tr>
                   <td class='tablesubhead' colspan="1"><b><bean:message key="com.srit.hrnet.helpdesk.redressal.form.category"/></b>
                   <font class="star">*</font></td>
                        <td class="tableright" property="category" >
                        <iterateTag:iterate propertyName='<%=IterateInterface.ITERATE_HELPDESK_GRIEVANCE_CATEGORY%>' defaultSelected='<%=request.getAttribute("category")==null?null:""+request.getAttribute("category")%>' selectSize='<%=100%>' tabInd='<%="3"%>'>
                        </iterateTag:iterate>
                   </td>
              </tr>
              <tr>
                   <td class='tablesubhead' colspan="1"><b><bean:message key="com.srit.hrnet.helpdesk.redressal.form.priority"/></b>
                   <font class="star">*</font></td>
                   <td class="subhead">
                        <iterateTag:iterate propertyName='<%=IterateInterface.ITERATE_HELPDESK_GRIEVANCE_PRIORITY%>' defaultSelected='<%=request.getAttribute("priority")==null?null:""+request.getAttribute("priority")%>' selectSize='<%=100%>' tabInd='<%="3"%>'>
                                  </iterateTag:iterate>
                   </td>
         </tr>
         <tr>
                             <td class='tablesubhead' colspan=1><b>Date of Occurence</b>
                             <font class="star">*</font> </td>
                             <td class="subhead">     
                             <html:text name="GreivanceForm" property="occdate" maxlength="10"/>
                             <input type="hidden" name="currDate" />
                             <img src="<%= request.getContextPath()%>/images/calendar.jpg" border="0" alt="Calendar" >
                             </td>                         
                   </tr>
                                  <tr>
                                       <td class='tablesubhead' colspan=1><b>Time of Occurence</b>
                                       <font class="star">*</font></td>
                                       <td class="subhead">     
                                       <html:text name="GreivanceForm" property="occtime" maxlength="10"/> (24 Hrs format)</td>
                             </tr>
                             <tr>
                        <td class="tablesubhead" colspan=1>
                             <b>Description</b>
                             <font class="star">*</font></td>
                                       <td class="subhead">
                                       <html:textarea property="desc" styleClass="formObject" cols="40" rows="4"></html:textarea>
                                       </td>
                        </tr>
                   <tr>
              <td class="tablesubhead" colspan=1>
                   <b>Comments/Suggestions</b>
              </td>
                             <td class="subhead">
                             <html:textarea property="comments" styleClass="formObject" value="" cols="40" rows="4"></html:textarea>
                             </td>
                   </tr>
                   <tr>
                   <td class="tableleft">
              <b><bean:message key="com.srit.hrnet.helpdesk.redressal.form.attachment"/> </b>
                                  </td>
                             <td class="tableright">
                                  <html:file property="file" size="18" />
                             </td>
              </tr>
                   <tr>
                   <td colspan="2" align="center" class="tablesubhead">
                   <input type="submit" class="submit" value="Submit" >
                    <html:reset property="reset" styleClass="submit" />
                   </td>
              </tr>
    </table>
         <input type="hidden" name="currentDate" value="<%=currentDate%>">
    </html:form>
    </GenerateTab:displaytabs>
    <html:javascript formName="/SubmitComplaint"/>
    </body>
    </html:html>
    please help me..

    VAS_MS wrote:
    please help me..First help yourself by posting a clear question
    You have far to much code posted and without the use of the correct code tags its almost unreadable.
    You have a question about uplaoding files with Struts then get rid of all the junk in your code thats not related to uploading files.
    If you have an error then post the relevant information on the error
    like
    org.apache.commons.beanutils.ConversionException:
    Cannot assign value of type 'org.apache.struts.upload.CommonsMultipartRequestHandler$CommonsFormFile' to property 'file' of type 'java.lang.String'
    org.apache.struts.action.DynaActionForm.set(DynaActionForm.java:424)If you had posted only that you would have given enough information, that error says it all you are trying to put your file into a String and its not working.
    reread the tutorial/documentation provided and try again
    Edited by: pgeuens on 21-mrt-2008 8:04

  • Error in upload file

    Hello,
    I have tried all thread regarding upload file on tomcat server.
    but still i dont get proper solution on that.
    In my project I want to send mail with attachment in jsp. Email sending
    is working properly but attachment is not still send.
    It gives nullpointerException error.
    for that I hv tried upload a file but my file is not uploading properly.
    So plz tell me step wise procedure for that with sample code
    Plz!!!!!!!!!!!!!!!!!!!!!!!!
    Reply me urgent

    I have tried below code but its giving me error
    NullPointerException
    After runnning following code file will be copied in specify folder.
    I also dont know how to invoke following code to attach file code
    Plz send me reply urgently with stepwise
    NewUpload.jsp
    <%@ page import="java.util.*,java.io.*"%>
    <%
    String path=request.getParameter("filename");
    String newPath="";
    int count=0;
    if(path!=null)
    ArrayList arr=new ArrayList();
    StringTokenizer st=new StringTokenizer(path,"\\");
    while(st.hasMoreTokens())
    arr.add(count,st.nextToken());
    count++;
    // create ur own path
    out.println(path);
    newPath="d:\\Shilpa\\" + arr.get(count-1);
    out.println(newPath);
    int c;
    FileInputStream fis=new FileInputStream(path);
    FileOutputStream fos=new FileOutputStream(newPath);
    while((c=fis.read())!=-1)
    fos.write((char)c);
    out.println("Thanks for using");
    out.println("<br>");
    out.println("<br>");
    out.println("1.File1 Uploaded from :: "+path);
    out.println("<br>");
    out.println("<br>");
    out.println("2.Uploaded File1 is Saved in :: "+newPath);
    %>
    Up;oadFile.html
    <!--Html Code for Browsing Purpose-->
    <html>
    <head>
    <form action="NewUpload.jsp" name="upform" enctype="multipart/form-data">
    <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="filename" size="50">
    </td>
    </tr>
    <tr>
    <td align="left">
    <input type="hidden" name="todo" value="upload">
    <input type="submit" name="Submit" value="Upload">
    <input type="reset" name="Reset" value="Cancel">
    </td>
    </tr>
    </table>
    </form>
    </body>
    </html>

  • Problem in getting the parameters from teh form html with upload file

    I have used the jspsmartupload package:
    the html file:
    <HTML>
    <BODY BGCOLOR="white">
    <H1>jspSmartUpload : Sample 5</H1>
    <HR>
    <form METHOD="POST" ACTION="sample5.jsp"
    NAME="PW" ENCTYPE="multipart/form-data">
    <table CELLSPACING="0" CELLPADDING="3" BORDER="1" WIDTH="474">
    <!-- FILE -->
    <!-- TEXT -->
    <tr>
    <td width="150">
    <div align="left">
    <p><small><font face="Verdana">Text :  </font></small>
    </div>
    </td>
    <td width="324"><small><font face="Verdana">
    <input TYPE="TEXT" name="myText" value="">
    <br>
    </font></small></td>
    </tr>
    <!-- TEXTAREA -->
    <tr>
    <td width="150">
    <div align="left">
    <p><small><font face="Verdana">Text Area :  </font></small>
    </div>
    </td>
    <td width="324"><small><font face="Verdana">
    <textarea name="myTextArea" rows="4" value=""></textarea>
    <br>
    </font></small></td>
    </tr>
    <!-- PASSWORD -->
    <tr>
    <td>
    <div align="left">
    <p><small><font face="Verdana">PassWord :  </font></small>
    </div>
    </td>
    <td><small><font face="Verdana">
    <input TYPE="PASSWORD" name="myPASSWORD" value="">
    <br>
    </font></small></td>
    </tr>
    <!-- HIDDEN -->
    <tr>
    <td>
    <div align="left">
    <p><small><font face="Verdana">Hidden :  </font></small>
    </div>
    </td>
    <td><small><font face="Verdana">
    <input TYPE="hidden" name="myHidden" value="hidden">
    <br>
    </font></small></td>
    </tr>
    <tr>
    <td><small><font face="Verdana">Select a first file : 
    </font></small></td>
    <td><small><font face="Verdana">
    <input type="file" name="FILE1">
    </font></small></td>
    </tr>
    <tr>
    <td><small><font face="Verdana">Select a second file : </font></small></td>
    <td><small><font face="Verdana">
    <input type="file" name="FILE2">
    </font></small></td>
    </tr>
    <!-- CHECKBOX -->
    <tr>
    <td>
    <div align="left">
    <p><small><font face="Verdana">CheckBox :  </font></small>
    </div>
    </td>
    <td><small><font face="Verdana">
    <input TYPE="CHECKBOX" name="myCheckBox" value="Value 1">
    Value 1<br>
    <input TYPE="CHECKBOX" name="myCheckBox" value="Value 2">
    Value 2<br>
    <input TYPE="CHECKBOX" name="myCheckBox" value="Value 3">
    Value 3<br>
    </font></small></td>
    </tr>
    <!-- RADIO -->
    <tr>
    <td>
    <div align="left">
    <p><small><font face="Verdana">Radio :  </font></small>
    </div>
    </td>
    <td><small><font face="Verdana">
    <input TYPE="radio" name="radio" value="Value 1">
    Value 1<br>
    <input TYPE="radio" name="radio" value="Value 2">
    Value 2<br>
    <input TYPE="radio" name="radio" value="Value 3">
    Value 3<br>
    </font></small></td>
    </tr>
    <!-- SELECT -->
    <tr>
    <td>
    <div align="left">
    <p><small><font face="Verdana">Simple Select :  </font></small>
    </div>
    </td>
    <td><small><font face="Verdana">
    <SELECT name="mySimpleSelect" >
    <OPTION value="Value 1">Value 1</OPTION>
    <OPTION value="Value 2">Value 2</OPTION>
    <OPTION value="Value 3">Value 3</OPTION>
    </SELECT>
    <br>
    </font></small></td>
    </tr>
    <!-- SELECT MULTIPLE -->
    <tr>
    <td>
    <div align="left">
    <p><small><font face="Verdana">Multiple Select :  </font></small>
    </div>
    </td>
    <td><small><font face="Verdana">
    <SELECT multiple name="myMultSelect" >
    <OPTION value="Value 1">Value 1</OPTION>
    <OPTION value="Value 2">Value 2</OPTION>
    <OPTION value="Value 3">Value 3</OPTION>
    </SELECT>
    <br>
    </font></small></td>
    </tr>
    <!-- SUBMIT -->
    <tr>
    <td colspan="2" width="474">
    <div align="center">
    <center>
    <p><small><font face="Verdana">
    <input
    TYPE="Submit">
    </font></small>
    </center>
    </div>
    </td>
    </tr>
    </table>
    </form>
    </BODY>
    </HTML>
    the jsp file :
    <%@page language="java" import="com.jspsmart.upload.*"%>
    <%@page import="java.util.*"%>
    <jsp:useBean id="myUpload" scope="page" class="com.jspsmart.upload.SmartUpload" />
    <HTML>
    <BODY BGCOLOR="white">
    <H1>jspSmartUpload : Sample 5</H1>
    <HR>
    <%
         // Initialization
         myUpload.initialize(pageContext);
         // Upload
         myUpload.upload();          
         // Files
         out.println("<BR><STRONG>Display information about Files</STRONG><BR>");
         out.println("Number of files = " + myUpload.getFiles().getCount() + "<BR>");
         //out.println("Total size (bytes) = " + myUpload.getFiles().getSize() +"<BR>");
         for (int i=0;i<myUpload.getFiles().getCount();i++){
              out.print(myUpload.getFiles().getFile(i).getFieldName());
              if (!myUpload.getFiles().getFile(i).isMissing())
                   out.print(" = " + myUpload.getFiles().getFile(i).getFileName() + " (" + myUpload.getFiles().getFile(i).getSize() + ")");
                   myUpload.getFiles().getFile(i).saveAs("/upload/" + myUpload.getFiles().getFile(i).getFileName());
              else
                   out.print(" = vide");          
              out.println("<BR>");
         // Request
         out.println("<BR><BR><STRONG>Display information about Requests</STRONG><BR>");
         // Retreive Requests' names
         java.util.Enumeration e = myUpload.getRequest().getParameterNames();
         // Retreive parameters
         while (e.hasMoreElements()) {
              String key = (String)e.nextElement();
              String[] values = myUpload.getRequest().getParameterValues(key);               
              // Browse the current parameter values
              for(int i = 0; i < values.length; i++) {
              out.print(key + " = ");
              out.print(values[i] + "<BR>");
    %>
    </BODY>
    </HTML>
    The result shown is:
    jspSmartUpload : Sample 5
    Display information about Files
    Number of files = 2
    FILE1 = path.txt (240)
    FILE2 = WS_FTP.LOG (146)
    Display information about Requests
    radio = Value 2
    mySimpleSelect = Value 1
    myTextArea = test
    myPASSWORD =
    myMultSelect = Value 3
    myHidden = hidden
    myText = test
    myCheckBox = Value 1
    myCheckBox = Value 2
    myCheckBox = Value 3
    I would like to know if i want to get back the parameters from the form ,
    is that i must use Enumeration.
    Because i have tried request.getParameter() to get the value of radio button, textbox, checkbox and select menu, but it get the null values.
    Also, the function of Enumeration does not get the values of parameter in sequence as html form. e.g.In the html file, the first parameters should be textbox,but it displays the radio button's values first.
    How to solve the problem .
    Thanks

    This sounds like a bug in the smart upload code. I have used this stuff before, but it's probably an older version, so maybe they broke something. Enumerations aren't usually guaranteed to keep things in any particular order. I would say for now, make a method to take the enumeration and a param name to find the value. And write to the JSPSmart people.

  • Problem in upload file using oreilly classes

    Hi
    I stucked on a problem......
    I want to upload file from html page....On this page I want only a upload button so that when I click on this button file will upload from my client m/c to server m/c....
    I have code n all but browse button on html page....now I want to remove this browse button n want to give the file path somewhere in the code itself........so that on html page there will only the uplod button and by click on this button file will upload from client to server.......server path already there in code.....Please do the needful
    Abhishek
    I m putting the code here:-
    FileUpload.java
    upload-FileUpload.java
    NOTE: This file is a generated file.
    Do not modify it by hand!
    package upload;
    //custom imports for FileUpload
    //add your custom import statements here
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.*;
    import com.oreilly.servlet.MultipartRequest;
    import java.util.*;
    public class FileUpload extends javax.servlet.http.HttpServlet
         protected boolean create() throws java.lang.Exception
              return true;
         public FileUpload()
         {   // Constructor.
         private void unhandledEvent( String listenerName, String methodName, java.lang.Object event )
         * destroy Method
         public void destroy()
              super.destroy();
              // TODO: implement
         * doGet Method
         protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
              System.out.println("abhishek");
              response.setContentType( "text/html" );
              PrintWriter out = response.getWriter();
              out.println("<HTML>");
              out.println("<HEAD><TITLE>FileUpload</TITLE></HEAD>");
              out.println("<BODY>");
              out.println("<H1>FileUpload</H1>");
              out.println("Hello World!");
              out.println("<P>Default Implementation From PowerJ</P>");
              out.println("</BODY></HTML>");
              // TODO: implement
         * doPost Method
         protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
              PrintWriter out = response.getWriter();
              try{
                   response.setContentType("text/html");
                   out.println("<HTML>");
                   out.println("<head><Title>Decoded Uploaded File</title><head>");
                   out.println("<body>");
                   out.println("<H1>UploadFile</h1>");
                   // path must be absolute to upload dir
                   // This is the decoder class that extracts the parameters and transfer file
                   // request argument = Http input stream
                   // c:\\temp\\upload = directory to save file
                   // 15*1024*1024 = 15mb max size file
                   MultipartRequest multi = new MultipartRequest(request, "c:\\temp\\upload",15*1024*1024);
                   // Lists form parameters
                   out.println("Params:");
                   Enumeration params = multi.getParameterNames();
                   out.println("<pre>");
                   while (params.hasMoreElements()) {
                        String name = (String)params.nextElement();
                        String value = multi.getParameter(name);
                        out.println(name + " = " + value);
                   out.println("</pre>");
                   // Show details of uploaded file
                   out.println("Files:");
                   Enumeration files = multi.getFileNames();
                   out.println("<pre>");
                   while (files.hasMoreElements()) {
                        String name = (String)files.nextElement();
                        String filename = multi.getFilesystemName(name);
                        String type = multi.getContentType(name);
                        File f = multi.getFile(name);
                        out.println("name: " + name);
                        out.println("filename: " + filename);
                        out.println("type: " + type);
                        if (f != null) {
                             out.println("f.toString(): " + f.toString());
                             out.println("f.getName(): " + f.getName());
                             out.println("f.exists(): " + f.exists());
                             out.println("f.length(): " + f.length());
                             out.println();
                        out.println("</pre>");
              }catch (Exception e){
                   out.println("<pre>");
                   e.printStackTrace(out);
                   out.println("</pre>");
              out.println("</body></html>");
         * init Method
         public void init(ServletConfig config) throws ServletException
              super.init(config);
              // TODO: implement
         * data members
    //     add your data members here
    UploadFile.html
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
    <meta name="GENERATOR" content="Microsoft FrontPage 4.0">
    <meta name="ProgId" content="FrontPage.Editor.Document">
    <title>File Upload using EAS</title>
    </head>
    <body>
    <form method="POST" enctype="multipart/form-data" action="upload/FileUpload">
    <p><b>File Upload using EAS </b></p>
    <p>Select file to send: <input type="file" name="name" size="30"></p>
    <p>Your Name: <input type="input" name="yourname" size="20"> </p>
    <p align="left"><input type="submit" value="Send File" name="submit"></p>
    </form>
    </body>
    </html>
    You can download the oreilly files from :- (same code is also here)
    http://www.sybase.com/detail?id=1011664

    where I should write down the file path(The file in client pc....e.g. C:\Documents and Settings\abhishek.jain\Desktop\Daily Order Manual.pdf ) in code........I m getting stuck

  • Again JSF upload file problem.

    I am using My Faces to upload files. There is a way to limit the size of uploaded files.
    <filter>
            <filter-name>ExtensionsFilter</filter-name>
            <filter-class>org.apache.myfaces.component.html.util.ExtensionsFilter</filter-class>
            <init-param>
                <param-name>uploadMaxFileSize</param-name>
                <param-value>7m</param-value>
            </init-param>
            <init-param>
                <param-name>uploadThresholdSize</param-name>
                <param-value>100k</param-value>
            </init-param>
        </filter>When I try to upload bigger than 7 MB file, I receive the following log.
    2007-05-23 13:58:20,796 [http-8080-Processor24] INFO org.apache.myfaces.component.html.util.MultipartRequestWrapper - user tried to upload a file that exceeded file-size limitations.
    org.apache.commons.fileupload.FileUploadBase$SizeLimitExceededException: the request was rejected because it's size exceeds allowed range
         at org.apache.commons.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:317)
         at org.apache.myfaces.component.html.util.MultipartRequestWrapper.parseRequest(MultipartRequestWrapper.java:70)
         at org.apache.myfaces.component.html.util.MultipartRequestWrapper.getParameter(MultipartRequestWrapper.java:151)
         at org.apache.myfaces.context.servlet.RequestParameterMap.getAttribute(RequestParameterMap.java:39)
         at org.apache.myfaces.context.servlet.AbstractAttributeMap.get(AbstractAttributeMap.java:87)
         at org.apache.myfaces.renderkit.html.HtmlResponseStateManager.getTreeStructureToRestore(HtmlResponseStateManager.java:181)
         at org.apache.myfaces.application.jsp.JspStateManagerImpl.restoreTreeStructure(JspStateManagerImpl.java:142)
         at org.apache.myfaces.application.jsp.JspStateManagerImpl.restoreView(JspStateManagerImpl.java:181)
         at org.apache.myfaces.application.jsp.JspViewHandlerImpl.restoreView(JspViewHandlerImpl.java:255)
         at org.apache.myfaces.lifecycle.LifecycleImpl.restoreView(LifecycleImpl.java:113)
         at org.apache.myfaces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:66)
         at javax.faces.webapp.FacesServlet.service(FacesServlet.java:94)
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:252)
         at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
         at org.apache.myfaces.component.html.util.ExtensionsFilter.doFilter(ExtensionsFilter.java:122)
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:202)
         at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
         at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)
         at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:178)
         at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:126)
         at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:105)
         at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:107)
         at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:148)
         at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:869)
         at org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:664)
         at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:527)
         at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:80)
         at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:684)
         at java.lang.Thread.run(Thread.java:595)
    By now, OK. Here comes the problem: The behavior of application is correct after this, which I can see from the rest of my log, BUT my browser continue to say that the request is being processed and that the page continues to load, which is not true, and I can not find where is the reason.
    Do you have any idea?

    Check this code if it is useful
    REPORT  ZSRK_046                                .
    DATA : FIR_FILE(512) VALUE '
    iltlvp01.t.st.corp\DE_Development\EP 6\Port\dept\Program Office\TEST.json'.
    TYPES: BEGIN OF TP_DATA_TAB,
           TEXT(512),
           END OF TP_DATA_TAB.
    DATA : DATA_TAB TYPE STANDARD TABLE OF TP_DATA_TAB,
           WA_DATA_TAB LIKE LINE OF DATA_TAB .
    DATA : WA(512).
    OPEN DATASET FIR_FILE FOR INPUT IN TEXT MODE ENCODING DEFAULT.
    IF SY-SUBRC EQ 0.
      DO.
        READ DATASET FIR_FILE INTO WA.
        IF SY-SUBRC NE 0.
          EXIT.
        ENDIF.
        WA_DATA_TAB-TEXT = WA.
        APPEND WA_DATA_TAB TO DATA_TAB.
        CLEAR : WA_DATA_TAB, WA.
      ENDDO.
    ENDIF.
    LOOP AT DATA_TAB INTO WA_DATA_TAB.
      WRITE : / WA_DATA_TAB-TEXT.
    ENDLOOP.

  • Upload file component in JSF 1.2

    Hi,
    I am developing an application with JSF 1.2 . I am using a custom component made with Apache Commons FileUpload 1.2.1 API which purpose is to upload files. This component work only if the form data is encoded with the “multipart/form-data” encoding instead of the usual “application x-www-form-urlencoded” encoding. From what I know JSF 1.2 doesn't handle this type of encoding. To overcome this issue, I install a servlet filter that intercepts a file upload and turns uploaded files into request attributes. The problem is that when the form data is encoded with the “multipart/form-data” encoding no characters are encoded. I have other JSF components in this form and in them I put different international characters which are lost when the form is submit because they are not encoded.
    Can somebody help me with this issue ?

    I have a filter
    import java.io.File;
    import java.io.IOException;
    import java.util.Collections;
    import java.util.Enumeration;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    import javax.servlet.Filter;
    import javax.servlet.FilterChain;
    import javax.servlet.FilterConfig;
    import javax.servlet.ServletException;
    import javax.servlet.ServletRequest;
    import javax.servlet.ServletResponse;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletRequestWrapper;
    import org.apache.commons.fileupload.FileItem;
    import org.apache.commons.fileupload.FileUploadException;
    import org.apache.commons.fileupload.disk.DiskFileItemFactory;
    import org.apache.commons.fileupload.servlet.ServletFileUpload;
    public class UploadFilter implements Filter {
    private int sizeThreshold = -1;
    private String repositoryPath;
    public void init(FilterConfig config) throws ServletException {
    repositoryPath = config.getInitParameter(
    "com.corejsf.UploadFilter.repositoryPath");
    try {
    String paramValue = config.getInitParameter(
    "com.corejsf.UploadFilter.sizeThreshold");
    if (paramValue != null)
    sizeThreshold = Integer.parseInt(paramValue);
    catch (NumberFormatException ex) {
    ServletException servletEx = new ServletException();
    servletEx.initCause(ex);
    throw servletEx;
    public void destroy() {
    public void doFilter(ServletRequest request,
    ServletResponse response, FilterChain chain)
    throws IOException, ServletException {
    if (!(request instanceof HttpServletRequest)) {
    chain.doFilter(request, response);
    return;
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    boolean isMultipartContent
    = ServletFileUpload.isMultipartContent(httpRequest);
    if (!isMultipartContent) {
    chain.doFilter(request, response);
    return;
    DiskFileItemFactory factory = new DiskFileItemFactory();
    if (sizeThreshold >= 0)
    factory.setSizeThreshold(sizeThreshold);
    if (repositoryPath != null)
    factory.setRepository(new File(repositoryPath));
    ServletFileUpload upload = new ServletFileUpload(factory);
    try {
    List<FileItem> items = (List<FileItem>) upload.parseRequest(httpRequest);
    final Map<String, String[]> map = new HashMap<String, String[]>();
    for (FileItem item : items) {
    String str = item.getString();
    if (item.isFormField())
    map.put(item.getFieldName(), new String[] { str });
    else
    httpRequest.setAttribute(item.getFieldName(), item);
    chain.doFilter(new
    HttpServletRequestWrapper(httpRequest) {
    public Map<String, String[]> getParameterMap() {
    return map;
    // busywork follows ... should have been part of the wrapper
    public String[] getParameterValues(String name) {
    Map<String, String[]> map = getParameterMap();
    return (String[]) map.get(name);
    public String getParameter(String name) {
    String[] params = getParameterValues(name);
    if (params == null) return null;
    return params[0];
    public Enumeration<String> getParameterNames() {
    Map<String, String[]> map = getParameterMap();
    return Collections.enumeration(map.keySet());
    }, response);
    } catch (FileUploadException ex) {
    ServletException servletEx = new ServletException();
    servletEx.initCause(ex);
    throw servletEx;
    a render
    import java.io.File;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.UnsupportedEncodingException;
    import javax.el.ValueExpression;
    import javax.faces.FacesException;
    import javax.faces.component.EditableValueHolder;
    import javax.faces.component.UIComponent;
    import javax.faces.context.ExternalContext;
    import javax.faces.context.FacesContext;
    import javax.faces.context.ResponseWriter;
    import javax.faces.render.Renderer;
    import javax.servlet.ServletContext;
    import javax.servlet.http.HttpServletRequest;
    import org.apache.commons.fileupload.FileItem;
    public class UploadRenderer extends Renderer {
    public void encodeBegin(FacesContext context, UIComponent component)
    throws IOException {
    if (!component.isRendered()) return;
    ResponseWriter writer = context.getResponseWriter();
    String clientId = component.getClientId(context);
    writer.startElement("input", component);
    writer.writeAttribute("type", "file", "type");
    writer.writeAttribute("name", clientId, "clientId");
    writer.endElement("input");
    writer.flush();
    public void decode(FacesContext context, UIComponent component) {
    ExternalContext external = context.getExternalContext();
    HttpServletRequest request = (HttpServletRequest) external.getRequest();
    String clientId = component.getClientId(context);
    FileItem item = (FileItem) request.getAttribute(clientId);
    Object newValue;
    ValueExpression valueExpr = component.getValueExpression("value");
    if (valueExpr != null) {
    Class valueType = valueExpr.getType(context.getELContext());
    if (valueType == byte[].class) {
    newValue = item.get();
    else if (valueType == InputStream.class) {
    try {
    newValue = item.getInputStream();
    } catch (IOException ex) {
    throw new FacesException(ex);
    else {
    String encoding = request.getCharacterEncoding();
    if (encoding != null)
    try {
    newValue = item.getString(encoding);
    } catch (UnsupportedEncodingException ex) {
    newValue = item.getString();
    else
    newValue = item.getString();
    ((EditableValueHolder) component).setSubmittedValue(newValue);
    ((EditableValueHolder) component).setValid(true);
    Object target = component.getAttributes().get("target");
    if (target != null) {
    File file;
    if (target instanceof File)
    file = (File) target;
    else {
    ServletContext servletContext
    = (ServletContext) external.getContext();
    String realPath = servletContext.getRealPath(target.toString());
    file = new File(realPath);
    try { // ugh--write is declared with "throws Exception"
    item.write(file);
    } catch (Exception ex) {
    throw new FacesException(ex);
    and a simple tag handler it is nothing special.
    This code is taken from an example in the book Core JavaServer Faces Second Edition 2007

  • Question about upload file to sever in jsp.

    i found some articles about upload file in jsp, and most of suggested that the third party classes will be used.
    but i want to know the basic technology behind them, for example what kind of class needed ( using java.io.* as usual)
    and what the process for writing a file to sever.
    any document or url link useful will be very welcomed.
    best regards

    Uploading a file is similar to sending any other kind of data, except that it must be encoded differently than a standard HTML form... Typically you will set up your form like this:
    <form action="/upload" enctype="multipart/form-data" method="POST">
    <input type="file" name="myFile">
    </form>
    The enctype declaration is necessary -- your file won't arrive intact any other way. However, the JSP/Servlet specs don't provide any code to deal with forms which are encoded this way, so things like request.getParameter() don't work. You will either have to roll your own code, or use a third party library.
    For more information, see RFC 1867, File upload in HTTP:
    http://www.faqs.org/rfcs/rfc1867.html

  • Problem in uploading file

    I stucked on a problem......
    I want to upload file from html page....On this page I want only a upload button so that when I click on this button file will upload from my client m/c to server m/c....
    I have code n all but browse button on html page....now I want to remove this browse button n want to give the file path somewhere in the code itself........so that on html page there will only the uplod button and by click on this button file will upload from client to server.......server path already there in code.....Please do the needful
    Abhishek
    I m putting the code here:-
    FileUpload.java
    upload-FileUpload.java
    NOTE: This file is a generated file.
    Do not modify it by hand!
    package upload;
    //custom imports for FileUpload
    //add your custom import statements here
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.*;
    import com.oreilly.servlet.MultipartRequest;
    import java.util.*;
    public class FileUpload extends javax.servlet.http.HttpServlet
    protected boolean create() throws java.lang.Exception
    return true;
    public FileUpload()
    { // Constructor.
    private void unhandledEvent( String listenerName, String methodName, java.lang.Object event )
    * destroy Method
    public void destroy()
    super.destroy();
    // TODO: implement
    * doGet Method
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    System.out.println("abhishek");
    response.setContentType( "text/html" );
    PrintWriter out = response.getWriter();
    out.println("<HTML>");
    out.println("<HEAD><TITLE>FileUpload</TITLE></HEAD>");
    out.println("<BODY>");
    out.println("<H1>FileUpload</H1>");
    out.println("Hello World!");
    out.println("
    Default Implementation From PowerJ
    out.println("</BODY></HTML>");
    // TODO: implement
    * doPost Method
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    PrintWriter out = response.getWriter();
    try{
    response.setContentType("text/html");
    out.println("<HTML>");
    out.println("<head><Title>Decoded Uploaded File</title><head>");
    out.println("<body>");
    out.println("<H1>UploadFile</h1>");
    // path must be absolute to upload dir
    // This is the decoder class that extracts the parameters and transfer file
    // request argument = Http input stream
    // c:\\temp\\upload = directory to save file
    // 15*1024*1024 = 15mb max size file
    MultipartRequest multi = new MultipartRequest(request, "c:\\temp\\upload",15*1024*1024);
    // Lists form parameters
    out.println("Params:");
    Enumeration params = multi.getParameterNames();
    out.println("<pre>");
    while (params.hasMoreElements()) {
    String name = (String)params.nextElement();
    String value = multi.getParameter(name);
    out.println(name + " = " + value);
    out.println("</pre>");
    // Show details of uploaded file
    out.println("Files:");
    Enumeration files = multi.getFileNames();
    out.println("<pre>");
    while (files.hasMoreElements()) {
    String name = (String)files.nextElement();
    String filename = multi.getFilesystemName(name);
    String type = multi.getContentType(name);
    File f = multi.getFile(name);
    out.println("name: " + name);
    out.println("filename: " + filename);
    out.println("type: " + type);
    if (f != null) {
    out.println("f.toString(): " + f.toString());
    out.println("f.getName(): " + f.getName());
    out.println("f.exists(): " + f.exists());
    out.println("f.length(): " + f.length());
    out.println();
    out.println("</pre>");
    }catch (Exception e){
    out.println("<pre>");
    e.printStackTrace(out);
    out.println("</pre>");
    out.println("</body></html>");
    * init Method
    public void init(ServletConfig config) throws ServletException
    super.init(config);
    // TODO: implement
    * data members
    // add your data members here
    UploadFile.html
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
    <meta name="GENERATOR" content="Microsoft FrontPage 4.0">
    <meta name="ProgId" content="FrontPage.Editor.Document">
    <title>File Upload using EAS</title>
    </head>
    <body>
    <form method="POST" enctype="multipart/form-data" action="upload/FileUpload">
    <b>File Upload using EAS </b>
    Select file to send: <input type="file" name="name" size="30">
    Your Name: <input type="input" name="yourname" size="20">
    <input type="submit" value="Send File" name="submit">
    </form>
    </body>
    </html>----------------------------------------------------------------------------------------------
    You can download the oreilly files from :- (same code is also here)
    http://www.sybase.com/detail?id=1011664

    create a hidden field in the html page with the path to file i assume it is fixed
    retrieve the name in the servlet you are already retrieving many values
    and substitute it in the place where you are now passing file name
    but the exact place you have to change you have to figure out yourself you are hardworking isn`t it?
    i hope my answer has got some meaning
    gimbal as far as i know is a good member of this forum who gives good answers so try to be polite
    Its not your Aptitude but your Attitude that determines your Altitude

  • Filename of uploaded file through messageFileUpload in table

    Hi,
    i have a table bean on a page where there is a single column of type messageFileUpload. User can add rows to table and upload files to db table containing columns file_name (varchar2) and file_data (blob). How can i populate the db table column file_name with the name of the file choosen by the user?
    If i do not use table (just a single messageFileUpload component) then on form submit in processFormRequest i can use String fileName = pageContext.getParameter("FileData"); to get the name of file, but waht to do with a messageFileUpload in a table?
    Edited by: user12086842 on 01.01.2013 3:46

    Thanks for reply.
    I replaced messageFileUpload (binded to blob table column) with messageStyledText (binded to filename attribute). Above the table placed single messageFileUpload and submitButton nearby. After user select file on submit I do:
    *if (pageContext.getParameter("DoUploadButton") != null) {*
    .. DataObject fileUploadData = pageContext.getNamedDataObject("FileData");
    .. *if (fileUploadData != null) {*
    .... String fileName = (String)fileUploadData.selectValue(null, "UPLOAD_FILE_NAME");
    .... String contentType = (String)fileUploadData.selectValue(null, "UPLOAD_FILE_MIME_TYPE");
    .... BlobDomain fileContent = (BlobDomain)fileUploadData.selectValue(null, fileName);
    .... String seqNumber = pageContext.getParameter("seqNumber");
    .... am.insertInstanceAttachRowBlob(seqNumber, fileName, fileContent, contentType);
    .... pageContext.removeNamedDataObject("FileData");
    .. return;
    Edited by: user12086842 on 02.01.2013 2:41

  • Urgent !!!!!!!!!!!!!Uploading File problem

    Hi I stucked on a problem...... I want to upload file from html page....On this page I want only a upload button so that when I click on this button file will upload from my client m/c to server m/c.... I have code n all but browse button on html page....now I want to remove this browse button n want to give the file path somewhere in the code itself........so that on html page there will only the uplod button and by click on this button file will upload from client to server.......server path already there in code.....Please do the needful  Abhishek  I m putting the code here:-  FileUpload.java  /* upload-FileUpload.java  NOTE: This file is a generated file. Do not modify it by hand! */  package upload;   //custom imports for FileUpload //add your custom import statements here  import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import com.oreilly.servlet.MultipartRequest; import java.util.*;   public class FileUpload extends javax.servlet.http.HttpServlet { protected boolean create() throws java.lang.Exception {  return true; }   public FileUpload() { // Constructor.  } private void unhandledEvent( String listenerName, String methodName, java.lang.Object event ) {  } /** * destroy Method */  public void destroy() { super.destroy(); // TODO: implement } /** * doGet Method */  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("abhishek"); response.setContentType( "text/html" );  PrintWriter out = response.getWriter();  out.println("<HTML>");  out.println("<HEAD><TITLE>FileUpload</TITLE></HEAD>");  out.println("<BODY>");  out.println("<H1>FileUpload</H1>");  out.println("Hello World!");  out.println(" Default Implementation From PowerJ  ");  out.println("</BODY></HTML>");   // TODO: implement } /** * doPost Method */  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {   PrintWriter out = response.getWriter();  try{ response.setContentType("text/html"); out.println("<HTML>"); out.println("<head><Title>Decoded Uploaded File</title><head>");  out.println("<body>"); out.println("<H1>UploadFile</h1>");  // path must be absolute to upload dir // This is the decoder class that extracts the parameters and transfer file // request argument = Http input stream // c:\\temp\\upload = directory to save file // 15*1024*1024 = 15mb max size file MultipartRequest multi = new MultipartRequest(request, "c:\\temp\\upload",15*1024*1024);   // Lists form parameters out.println("Params:"); Enumeration params = multi.getParameterNames(); out.println("<pre>");  while (params.hasMoreElements()) { String name = (String)params.nextElement(); String value = multi.getParameter(name); out.println(name + " = " + value); }  out.println("</pre>");   // Show details of uploaded file out.println("Files:"); Enumeration files = multi.getFileNames();  out.println("<pre>"); while (files.hasMoreElements()) { String name = (String)files.nextElement(); String filename = multi.getFilesystemName(name); String type = multi.getContentType(name); File f = multi.getFile(name); out.println("name: " + name); out.println("filename: " + filename); out.println("type: " + type); if (f != null) { out.println("f.toString(): " + f.toString()); out.println("f.getName(): " + f.getName()); out.println("f.exists(): " + f.exists()); out.println("f.length(): " + f.length()); out.println(); } out.println("</pre>"); }  }catch (Exception e){ out.println("<pre>"); e.printStackTrace(out); out.println("</pre>"); } out.println("</body></html>"); } /** * init Method */  public void init(ServletConfig config) throws ServletException { super.init(config); // TODO: implement } /**************************************** * data members ****************************************/   // add your data members here }  --------------------------------------------------------------------------------------------------  UploadFile.html  <html>  <head> <meta http-equiv="Content-Type" content="text/html; charset=windows-1252"> <meta name="GENERATOR" content="Microsoft FrontPage 4.0"> <meta name="ProgId" content="FrontPage.Editor.Document"> <title>File Upload using EAS</title> </head>  <body>  <form method="POST" enctype="multipart/form-data" action="upload/FileUpload">  <b>File Upload using EAS </b>    Select file to send: <input type="file" name="name" size="30">    Your Name: <input type="input" name="yourname" size="20">     <input type="submit" value="Send File" name="submit">   </form>  </body>  </html> ----------------------------------------------------------------------------------------------  You can download the oreilly files from :- (same code is also here)  http://www.sybase.com/detail?id=1011664

    I m putting the code again with code tags:-
    code is here
    FileUpload.java
    package upload;
    //custom imports for FileUpload
    //add your custom import statements here
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.*;
    import com.oreilly.servlet.MultipartRequest;
    import java.util.*;
    public class FileUpload extends javax.servlet.http.HttpServlet
    protected boolean create() throws java.lang.Exception
    return true;
    public FileUpload()
    { // Constructor.
    private void unhandledEvent( String listenerName, String methodName, java.lang.Object event )
    * destroy Method
    public void destroy()
    super.destroy();
    // TODO: implement
    * doGet Method
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    System.out.println("abhishek");
    response.setContentType( "text/html" );
    PrintWriter out = response.getWriter();
    out.println("<HTML>");
    out.println("<HEAD><TITLE>FileUpload</TITLE></HEAD>");
    out.println("<BODY>");
    out.println("<H1>FileUpload</H1>");
    out.println("Hello World!");
    out.println("
    Default Implementation From PowerJ
    out.println("</BODY></HTML>");
    // TODO: implement
    * doPost Method
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    PrintWriter out = response.getWriter();
    try{
    response.setContentType("text/html");
    out.println("<HTML>");
    out.println("<head><Title>Decoded Uploaded File</title><head>");
    out.println("<body>");
    out.println("<H1>UploadFile</h1>");
    // path must be absolute to upload dir
    // This is the decoder class that extracts the parameters and transfer file
    // request argument = Http input stream
    // c:\\temp\\upload = directory to save file
    // 15*1024*1024 = 15mb max size file
    MultipartRequest multi = new MultipartRequest(request, "c:\\temp\\upload",15*1024*1024);
    // Lists form parameters
    out.println("Params:");
    Enumeration params = multi.getParameterNames();
    out.println("<pre>");
    while (params.hasMoreElements()) {
    String name = (String)params.nextElement();
    String value = multi.getParameter(name);
    out.println(name + " = " + value);
    out.println("</pre>");
    // Show details of uploaded file
    out.println("Files:");
    Enumeration files = multi.getFileNames();
    out.println("<pre>");
    while (files.hasMoreElements()) {
    String name = (String)files.nextElement();
    String filename = multi.getFilesystemName(name);
    String type = multi.getContentType(name);
    File f = multi.getFile(name);
    out.println("name: " + name);
    out.println("filename: " + filename);
    out.println("type: " + type);
    if (f != null) {
    out.println("f.toString(): " + f.toString());
    out.println("f.getName(): " + f.getName());
    out.println("f.exists(): " + f.exists());
    out.println("f.length(): " + f.length());
    out.println();
    out.println("</pre>");
    }catch (Exception e){
    out.println("<pre>");
    e.printStackTrace(out);
    out.println("</pre>");
    out.println("</body></html>");
    * init Method
    public void init(ServletConfig config) throws ServletException
    super.init(config);
    // TODO: implement
    * data members
    // add your data members here
    }UploadFile.html
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
    <meta name="GENERATOR" content="Microsoft FrontPage 4.0">
    <meta name="ProgId" content="FrontPage.Editor.Document">
    <title>File Upload using EAS</title>
    </head>
    <body>
    <form method="POST" enctype="multipart/form-data" action="upload/FileUpload">
    <b>File Upload using EAS </b>
    Select file to send: <input type="file" name="name" size="30">
    Your Name: <input type="input" name="yourname" size="20">
    <input type="submit" value="Send File" name="submit">
    </form>
    </body>
    </html>[                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Upload file problems

    I have a jsp form which is used to upload file...following is the code..
    <form name='fileUploadFrm' METHOD="POST" ENCTYPE="multipart/form-data" action='/myServlet?prma=1&prmb=2' onSubmit="return validateForm(this);">
    <H2>Upload File <H2>
    <table class="tabledatadisplay" border='0' cellpadding='0' cellspacing='3'>
    <tr><td>File Name/ID:</td><td> <input name='fileName' type='text'></td></tr>
    <tr><td>File Description:</td><td><input name='fileDesc' type='text'></td></tr>
    <tr><td>File:</td><td> <input name='fileContent' type='file'></td></tr>
    <tr><td colspan='2'> </td></tr>
    <tr><td> </td><td><input name='attach' type='submit' value=' Upload File ' onClick="return confirm('Are you sure you want to upload the file.');"></td></tr>
    </table>
    </form>
    intially i used two hidden fields prma and prmb..it didn't work so I changed the action string to include both the hidden fields...
    Now I get null values when I use the following code in myServlet
    request.getParameter("fileName");
    request.getParameter("fileDesc");
    I do get the file, i mean from the file input element
    I am using multiparser etc..in myServlet, I could able to read the contents and save it to database, but I couldn't able ot retrieve the text field and hidden field values in myServlet
    strange...can't figure out wy it is so????
    someone pls help me with this...

    Hi I am also working on the same problem and my next task is to display the contents to the browser and give him an option to either only open the document or save it to hard disk. I am doing it through setting the response.setContentType(content-disposition, attachment, filename") but it does not display the contents, it shows the dialog box but not the contents. please help me if u can...i m sending u some helping code..
    PreparedStatement preparedStatement2 =
    conn.prepareStatement("SELECT content,filename FROM tab_file );
    ResultSet resultSet = preparedStatement2.executeQuery();
    while(resultSet.next())
    Blob blob = resultSet.getBlob(1);
    byte [] b = blob.getBytes(1, length );
    response.setHeader("Content-Disposition","attachment; filename=untitled.java");
    ServletOutputStream servletOut = response.getOutputStream();
    servletOut.write(buf);
    servletOut.close();
    thnx

Maybe you are looking for