Not a multipart form upload

I created a jsp that uses my extended version of editcurrentrecord (which creates an html form to insert a new record) and a rowsetbrowser.
I am able to insert new records when running the jsp in jdev 3.1 but when I deploy it to ias and try to insert a record I get the error: not a multipart form upload
Please help.
Thanks

I upgraded to JDev 3.2 and rewrote my code to extend the new
version of EditCurrentRecord. Now when I deploy to 9ias I get a new error:
Error Message: java.lang.NullPointerException: I'm following the online help
to deploy but I must be missing something cause it works in JDev. Any
suggestions?

Similar Messages

  • Problem with transfering unicode form data in MULTIPART/FORM-DATA

    HI experts,
    I have this web based multilingual application. Page 1(form6.jsp) is basic registeration form with 5 fields and one image upload to the server. Page 2(verify.jsp) is another jsp page for verification of UTF data entered in page 1.
    page 2 (verify.jsp) also uses a bean called (verify.java) for picking up values. page 3(insertEntry.jsp) is the page for inserting that data into the Database and uses a bean called (logicbean.java).
    Now, the problem im facing here is that if i use multipart/form-data, the unicode text filled in page1 is shown as garbage when its is transfered to page2 and displayed on page2. It is all gibberish. But if i do not use multipart/form-data, the unicode text transfered from page1 to page2 is displayed perfectly on page2.Im using devenagari(UTF) language for filling in details.
    // form6.jsp
    <%@ page language="java" pageEncoding="UTF-8"%>
    <%@ page import="java.util.*,java.text.*" %>
    <%@ page import="com.oreilly.servlet.*" %>
    <%
    request.setCharacterEncoding("UTF-8");
    %>
    <HTML>
    <HEAD>
    <TITLE>
    <%=session.getValue("main.title")%>
    </TITLE>
    </HEAD>
    <h1><center><%=session.getValue("main.head")%><Center>
    <BODY background="brown.bmp">
    <form name=form6 action="verify.jsp" method="post" enctype="multipart/form-data">
    <center>
    <font>
    <table border=1>
    <tr>
    <td colspan=2><center><img src="asok.bmp"></center>
    </tr>
    <tr>
    <td >
    <b>1.)<%=session.getValue("main.ec")%></b>
    </td>
    <td></td>
    </tr>
    <tr>
    <td align="right"><b><%=session.getValue("main.ecname")%></b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<input type="text" name="votername"></td>
    <td></td>
    </tr>
    <tr>
    <td align="right"> <b><%=session.getValue("main.ecsurname")%></b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<input type="text" name="votersurname"></td>
    <td></td>
    </tr>
    <tr>
    <td align="left"><b>2.)<%=session.getValue("main.rel")%></b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
    <select name="relation" onchange="if(this.selectedIndex!=0){this.form.texthiddenrelation.value=this.options[this.selectedIndex].value}" size="1">
                                       <option>Choose</option>
    <option value="father">Father</option>
    <option value="mother">Mother</option>
    <option value="husband">Husband</option>
    </select>
    <input type="hidden" name="texthiddenrelation" />
    </td>
    </tr>
    <tr>
    <td align="right"><b><%=session.getValue("main.relname")%></b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<input type="text" name="parentname">
    <td></td>
    </tr>
    <tr>
    <td align="right"><b><%=session.getValue("main.relsurname")%>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp</b><input type="text" name="parentsurname">
    <td></td>
    </tr>
    <tr>
    <td align="right"><b>3.)<%=session.getValue("main.sex")%></b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
    &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
    <select name="sex" onchange="if(this.selectedIndex!=0){this.form.texthiddensex.value=this.options[this.selectedIndex].value}" size="1">
                                            <option>Choose</option>
                                            <option value="male">Male</option>
    <option value="female">Female</option>
    <option value="other">Other</option>
    </select>
    <input type="hidden" name="texthiddensex" /> </td>
    <td align="right"><b><%=session.getValue("form6.image")%><input type ="file" name=pic1 onchange={this.form.pic.value=this.form.pic1.value}><input type= hidden name=pic> </b></td>
    </tr>
    <tr>
    <td colspan=2><b>4.)<%=session.getValue("main.age")%></b><input type="text" name="age">
    </td>
    </tr>
    <tr>
    <td><b>5.)<%=session.getValue("main.dob")%></b>
    <td><b><%=session.getValue("main.dobday")%></b> <select name="cmbday">
    <option value="1"> 1 </option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>
    <option value="6">6</option>
    <option value="7">7</option>
    <option value="8">8</option>
    <option value="9">10</option>
    <option value="10">11</option>
    <option value="11">12</option>
    <option value="12">13</option>
    <option value="13">14</option>
    <option value="14">15</option>
    <option value="15">16</option>
    <option value="16">17</option>
    <option value="17">18</option>
    <option value="18">19</option>
    <option value="19">20</option>
    <option value="20">21</option>
    <option value="21">22</option>
    <option value="22">23</option>
    <option value="23">24</option>
    <option value="24">25</option>
    <option value="25">26</option>
    <option value="26">27</option>
    <option value="28">28</option>
    <option value="29">29</option>
    <option value="30">30</option>
    <option value="31">31</option>
    </select>
    <b><%=session.getValue("main.dobmonth")%></b><select name="cmbmonth">
    <option value="jan">JAN</option>
    <option value="feb">FEB</option>
    <option value="mar">MAR</option>
    <option value="apr">APR</option>
    <option value="may">MAY</option>
    <option value="jun">JUN</option>
    <option value="jul">JUL</option>
    <option value="aug">AUG</option>
    <option value="sep">SEPT</option>
    <option value="oct">OCT</option>
    <option value="nov">NOV</option>
    <option value="dec">DEC</option>
    </select>
    <b><%=session.getValue("main.dobyear")%></b> <select name="cmbyear" onchange="if(this.form.cmbday.selectedIndex!=0 && this.form.cmbmonth.selectedIndex!=0 && this.form.cmbyear.selectedIndex!=0){this.form.mergedage.value=this.form.cmbday.options[this.form.cmbday.selectedIndex].value +' '+this.form.cmbmonth.options[this.form.cmbmonth.selectedIndex].text +' '+ this.form.cmbyear.options[this.form.cmbmonth.selectedIndex].value}" size="1">
    <option value="1970">1970</option>
    <option value="1971">1971</option>
    <option value="1972">1972</option>
    <option value="1973">1973</option>
    <option value="1974">1974</option>
    <option value="1975">1975</option>
    <option value="1976">1976</option>
    <option value="1977">1977</option>
    <option value="1978">1978</option>
    <option value="1979">1979</option>
    <option value="1980">1980</option>
    <option value="1981">1981</option>
    <option value="1982">1982</option>
    <option value="1983">1983</option>
    <option value="1984">1984</option>
    <option value="1985">1985</option>
    <option value="1986">1986</option>
    <option value="1987">1987</option>
    <option value="1988">1988</option>
    <option value="1989">1989</option>
    <option value="1990">1990</option>
    <option>
    </select>
    <input type="hidden" name="mergedage">
    </tr>
    <tr>
    <td colspan=2><b>6.)<%=session.getValue("main.add")%></b>
    </tr>
    <tr>
    <td align="right"><b><%=session.getValue("main.addline1")%></b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<input type="text" name="address1" value=""></td>
    <td><b><%=session.getValue("main.addstate")%></b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<input type="text" name="state"></td>
    </tr>
    <tr>
    <td align="right"><b><%=session.getValue("main.addline2")%></b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<input type="text" name="address2" onChange="this.form.finaladdress.value=this.form.address1.value + ';' + this.value;"> <input type="hidden" name="finaladdress"> </td>
    <td><b><%=session.getValue("main.addcity")%>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp</b><input type="text" name="city"></td>
    </tr>
    <tr>
    <td align="right"> <b><%=session.getValue("main.addpin")%></b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<input type="text" name="pincode">
    <td></td>
    </tr>
    <tr>
    <td ><b>7.)<%=session.getValue("main.const")%></b> <input type="text" name="constituency">
    <td ><b>8.)<%=session.getValue("main.id")%></b> &nbsp&nbsp<input type="text" name="refno">
    </tr>
    <tr>
    <td colspan="2"><center><input type="reset" name="reset" value="<%=session.getValue("button.reset")%>">&nbsp&nbsp<input type=submit name=Submit value="<%=session.getValue("button.submit")%>"></center></td>
    </tr>
    <tr>
    <td>
    </td>
    </tr>
    </form>
    </font>
    </BODY>
    </HTML>
    // verify.jsp
    <%@ page language="java" pageEncoding="UTF-8"%>
    <jsp:useBean id="verify" class="pack.verify" scope="request"/>
    <%@ page import="com.oreilly.servlet.*" %>
    <%@ page import="java.util.*,java.text.*" %>
    <%!
    MultipartRequest mp;
    // ParameterParser pp;
    %>
    <!-- Perform the actions on the bean. -->
    <%
    //pp.setCharacterEncoding("utf-8");
    %>
    <%
    try
    mp = new MultipartRequest(request, "d:/Files");
    out.println("DONE");
    /* Set the request object.*/
    /* The request object is implicitly available in the JSP page.*/
    verify.setRequest(mp);
    /* Insert the employee data into the database.*/
    verify.verifyEntry();
    //verify.setscope();
    /* Run the query to retrieve the employee data from the database.*/
    //logicbean.runQuery();
    catch (Exception e)
    System.out.println(e.getMessage());
    %>
    <HTML>
    <HEAD>
    <LINK href="theme/Master.css" rel="stylesheet" type="text/css">
    <TITLE>
    </TITLE>
    </HEAD>
    <BODY background="brown.bmp">
    <form name=form6 action="insertEntry.jsp" method="POST">
    <center>
    <table border=3>
    <tr>
    <td colspan=2><center><img src="asok.bmp"></center>
    </tr>
    <tr>
    <td >
    <b>1.)<%=session.getValue("main.ec")%></b>
    </td>
    <td rowspan=3>
    <image src="<%=verify.getpic()%>" width="85" hieght="85">
    </td>
    </tr>
    <tr>
    <td > &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<b><%=session.getValue("main.ecname")%></b> <%=verify.getvotername()%>&nbsp&nbsp<input type="hidden" value= "<%=verify.getvotername()%>" name="votername"></td>
    </tr>
    <tr >
    <td> &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<b><%=session.getValue("main.ecsurname")%></b><%=verify.getvotersurname()%>
    <input type="hidden" value= "<%=verify.getvotersurname()%>" name="votersurname"></td>
    </tr>
    <tr>
    <td ><b>2.)<%=session.getValue("main.rel")%></b><input type="hidden" value= "<%=verify.getvoterrelation()%>" name="texthiddenrelation"></td>
    <td><%=verify.getvoterrelation()%></td>
    </tr>
    <tr>
    <td >&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<b><%=session.getValue("main.relname")%></b>&nbsp&nbsp&nbsp <input type="hidden" value= "<%=verify.getparentname()%>" name="parentname"></td>
    <td><%=verify.getparentname()%></td>
    </tr>
    <tr>
    <td >&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<b><%=session.getValue("main.relsurname")%></b><input type="hidden" value= "<%=verify.getparentsurname()%>" name="parentsurname"></td>
    <td><%=verify.getparentsurname()%></td>
    </tr>
    <tr>
    <td><b>3.)<%=session.getValue("main.sex")%></b><input type="hidden" value= "<%=verify.getsex()%>" name="texthiddensex"></td>
    <td><%=verify.getsex()%></td>
    </tr>
    <tr>
    <td ><b>4.)<%=session.getValue("main.age")%></B><input type="hidden" value= "<%=verify.getage()%>" name="age"></td>
    <td><%=verify.getage()%></td>
    </tr>
    <tr>
    <td><b>5.)<%=session.getValue("main.dob")%></b> <input type="hidden" value= "<%=verify.getdob()%>" name="mergedage"></td>
    <td> <%=verify.getdob()%></td>
    </tr>
    <tr>
    <td colspan=2><b>
    6.)<b><%=session.getValue("main.add")%></b></td>
    </tr>
    <tr>
    <td> &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<b><%=session.getValue("verify.add")%></b><input type="hidden" value= "<%=verify.getadderess()%>" name="finaladdress"> </td>
    <td><%=verify.getadderess()%></td>
    </tr>
    <tr>
    <td >&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<b><%=session.getValue("main.addpin")%></b><input type="hidden" value= "<%=verify.getpin()%>" name="pincode"></td>
    <td><%=verify.getpin()%></td>
    </tr>
    <tr>
    <td>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<b><%=session.getValue("main.addstate")%></b><input type="hidden" value= "<%=verify.getstate()%>" name="state"></td>
    <td><%=verify.getstate()%></td>
    </tr>
    <tr>
    <td><b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<%=session.getValue("main.addcity")%></b><input type="hidden" value= "<%=verify.getcity()%>" name="city"></td>
    <td><%=verify.getcity()%></td>
    </tr>
    <tr>
    <td><b>7.)<%=session.getValue("main.const")%></b> <input type="hidden" value= "<%=verify.getconst()%>" name="constituency"></td>
    <td><%=verify.getconst()%></td>
    </tr>
    <tr>
    <td><b>8.)<%=session.getValue("main.id")%></b> <input type="hidden" value= "<%=verify.getrefno()%>" name="refno"></td>
    <td><%=verify.getrefno()%></td>
    </tr>
    <tr>
    <td colspan="2"><center><INPUT TYPE="button" VALUE="<%=session.getValue("ie.back")%>" onClick="history.go(-1)">
    <input type=submit name=Submit value="<%=session.getValue("button.submit")%>"></center><input type="hidden" value= "<%=verify.getpic()%>" name="pic"></td>
    </tr>
    </form>
    </BODY>
    </HTML>
    //verify.java
    package pack;
    import java.lang.*;
    import java.sql.*;
    import java.util.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import com.oreilly.servlet.*;
    import com.oreilly.servlet.ParameterParser.*;
    * @author Administrator
    * To change this generated comment edit the template variable "typecomment":
    * Window>Preferences>Java>Templates.
    * To enable and disable the creation of type comments go to
    * Window>Preferences>Java>Code Generation.
    public class verify {
    String votername = "";
    String votersurname = "";
    String texthiddenrelation="";
    String parentname = "";
    String parentsurname = "";
    String gender = "";
    String texthiddensex="";
    String age = "";
    String dob = "";
    String mergedage="";
    String address = "";
    String finaladdress="";
    String pincode = "";
    String state = "";
    String city = "";
    String constituency = "";
    String refno = "";
    MultipartRequest request = null;
    Connection dbConn = null;
    ParameterParser pp;
    private String voternameParam;
    * Set the request object. This is used for getting parameters.
    public void setRequest(MultipartRequest request)
    this.request = request;
    public void verifyEntry()
    throws Exception
    /* Connect to the database.*/
    //pp.setCharacterEncoding("utf-8");
    //String nameParam = request.getParameter("name");
    MultipartRequest mp;
    System.out.println("connected to db2 through insertemployee");
    /* Get all the parameters from the calling HTML form.*/
    String voternameParam = request.getParameter("votername");
    System.out.println("the votername is " + request.getParameter("votername"));
    System.out.println(voternameParam);
    String votersurnameParam = request.getParameter("votersurname");
    System.out.println("the votersurname is " + request.getParameter("votersurname"));
    String hiddenrelationParam = request.getParameter("texthiddenrelation");
    System.out.println("the relation is " + request.getParameter("texthiddenrelation"));
    String parentnameParam = request.getParameter("parentname");
    System.out.println("the parentname is " + request.getParameter("parentname"));
    String parentsurnameParam = request.getParameter("parentsurname");
    System.out.println("the parentsurname is " + request.getParameter("parentsurname"));
    String ageParam = request.getParameter("age");
    System.out.println("the age is " + request.getParameter("age"));
    String mergedageParam = request.getParameter("mergedage");
    System.out.println("the mergedage is " + request.getParameter("mergedage"));
    String hiddensexParam = request.getParameter("texthiddensex");
    System.out.println("the hiddensex is " + request.getParameter("texthiddensex"));
    //String dobParam = request.getParameter("dob");
    //System.out.println("the dob is " + request.getParameter("dob"));
    String finaladdressParam = request.getParameter("finaladdress");
    System.out.println("the finaladdress is " + request.getParameter("finaladdress"));
    String pincodeParam = request.getParameter("pincode");
    System.out.println("the pincode is " + request.getParameter("pincode"));
    String stateParam = request.getParameter("state");
    System.out.println("the state is " + request.getParameter("state"));
    String cityParam = request.getParameter("city");
    System.out.println("the city is " + request.getParameter("city"));
    String constituencyParam = request.getParameter("constituency");
    System.out.println("the constituency is " + request.getParameter("constituency"));
    String refnoParam = request.getParameter("refno");
    System.out.println("the refno is " + request.getParameter("refno"));
    System.out.println("encoding = " + System.getProperty("file.encoding"));
    public String getvotername()
    return request.getParameter("votername");
    public String getvotersurname()
    return request.getParameter("votersurname");
    public String getvoterrelation()
    return request.getParameter("texthiddenrelation");
    public String getparentname()
    return request.getParameter("parentname");
    public String getparentsurname()
    return request.getParameter("parentsurname");
    public String getage()
    return request.getParameter("age");
    public String getsex()
    return request.getParameter("texthiddensex");
    public String getadderess()
    return request.getParameter("finaladdress");
    public String getpin()
    return request.getParameter("pincode");
    public String getstate()
    return request.getParameter("state");
    public String getcity()
    return request.getParameter("city");
    public String getconst()
    return request.getParameter("constituency");
    public String getrefno()
    return request.getParameter("refno");
    public String getdob()
    return request.getParameter("mergedage");
    public String getpic()
    //String a=request.getParameter("pic");
    //a=a.substring(a.lastIndexOf("/")+1);
    //System.out.print("Java path is "+a);     
    //Enumeration enum=request.getFileNames();
    //while(enum.hasMoreElements())
    //     String abc=(String)enum.nextElement();
    //     System.out.print("Java the path is "+abc);     
    return request.getParameter("pic");
    String votername1;
    //public void setScope()
    //request.setAttribute("votername1" ,voternameParam );
    //insertEntry.jsp
    <jsp:useBean id="logicbean" class="pack.logicbean" scope="request"/>
    <%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
    <%@ page import="java.util.*,java.text.*" %>
    <%@ page import="com.oreilly.servlet.*" %>
    <%
    request.setCharacterEncoding("UTF-8");
    %>
    <!-- Perform the actions on the bean. -->
    <%
    request.setCharacterEncoding("UTF-8");
    %>
    <%
    try
    /* Set the request object.*/
    /* The request object is implicitly available in the JSP page.*/
    logicbean.setRequest(request);
    //MultiPartRequest mp=MultiPartRequest(request,"E:\Files");
    /* Insert the employee data into the database.*/
    logicbean.insertEntry();
    /* Run the query to retrieve the employee data from the database.*/
    //logicbean.runQueryInsert();
    catch (Exception e)
    System.out.println(e.getMessage());
    %>
    <HTML>
    <HEAD>
    <TITLE>
    Insert Record
    </TITLE>
    </HEAD>
    <BODY background="brown.bmp">
    <center><H2><%=session.getValue("ie.label")%>
    </H2>
    <font face = "Devanagari MT for IBM" size = +2>
    <b><%=session.getValue("ie.sd")%>|<%=session.getValue("ie.home")%></b>
    </font>
    </center>
    </BODY>
    </HTML>
    I have narrowed down the problem to the point where i understand that the "request.getParameter()" function for multipart is not able to understand or read UTF data properly. The out.println prints garbage from this function on the console. im using WAS
    plz help
    thanx in advance
    caffaine

    hi,
    To solve your problem Servlet Filters
    FILTER PROGRAM
    ===============
    package filters;
    import java.io.IOException;
    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.UnavailableException;
    public class SetCharacterEncodingFilter implements Filter {
    // ----------------------------------------------------- Instance Variables
    * The default character encoding to set for requests that pass through
    * this filter.
    protected String encoding = null;
    * The filter configuration object we are associated with. If this value
    * is null, this filter instance is not currently configured.
    protected FilterConfig filterConfig = null;
    * Should a character encoding specified by the client be ignored?
    protected boolean ignore = true;
    // --------------------------------------------------------- Public Methods
    * Take this filter out of service.
    public void destroy() {
    this.encoding = null;
    this.filterConfig = null;
    * Select and set (if specified) the character encoding to be used to
    * interpret request parameters for this request.
    * @param request The servlet request we are processing
    * @param result The servlet response we are creating
    * @param chain The filter chain we are processing
    * @exception IOException if an input/output error occurs
    * @exception ServletException if a servlet error occurs
    public void doFilter(ServletRequest request, ServletResponse response,
    FilterChain chain)
         throws IOException, ServletException {
    // Conditionally select and set the character encoding to be used
    if (ignore || (request.getCharacterEncoding() == null)) {
    String encoding = selectEncoding(request);
    if (encoding != null)
    request.setCharacterEncoding(encoding);
         // Pass control on to the next filter
    chain.doFilter(request, response);
    * Place this filter into service.
    * @param filterConfig The filter configuration object
    public void init(FilterConfig filterConfig) throws ServletException {
         this.filterConfig = filterConfig;
    this.encoding = filterConfig.getInitParameter("encoding");
    String value = filterConfig.getInitParameter("ignore");
    if (value == null)
    this.ignore = true;
    else if (value.equalsIgnoreCase("true"))
    this.ignore = true;
    else if (value.equalsIgnoreCase("yes"))
    this.ignore = true;
    else
    this.ignore = false;
    // ------------------------------------------------------ Protected Methods
    * Select an appropriate character encoding to be used, based on the
    * characteristics of the current request and/or filter initialization
    * parameters. If no character encoding should be set, return
    * <code>null</code>.
    * <p>
    * The default implementation unconditionally returns the value configured
    * by the <strong>encoding</strong> initialization parameter for this
    * filter.
    * @param request The servlet request we are processing
    protected String selectEncoding(ServletRequest request) {
    return (this.encoding);
    web-xml entry
    +++++++++++
    <filter>     
         <filter-name>Set Character Encoding</filter-name>
    <filter-class>filters.SetCharacterEncodingFilter</filter-class>
              <init-param>
    <param-name>encoding</param-name>
    <param-value>UTF-8</param-value>
    </init-param>
    </filter>
    <filter-mapping>
    <filter-name>Set Character Encoding</filter-name>
    <url-pattern>*.jsp</url-pattern>
    </filter-mapping>

  • Hi, I am using HP11 and iPlanet web server. When trying to upload files over HTTP using FORM ENCTYPE="multipart/form-data" that are bigger than a few Kilobytes i get a 408 error. (client timeout).

    Hi, I am using HP11 and iPlanet web server. When trying to upload files over HTTP using FORM ENCTYPE="multipart/form-data" that are bigger than a few Kilobytes i get a 408 error. (client timeout). It is as if the server has decided that the client has timed out during the file upload. The default setting is 30 seconds for AcceptTimeout in the magnus.conf file. This should be ample to get the file across, even increasing this to 2 minutes just produces the same error after 2 minutes. Any help appreciated. Apologies if this is not the correct forum for this, I couldn't see one for iPlanet and Web, many thanks, Kieran.

    Hi,
    You didnt mention which version of IWS. follow these steps.
    (1)Goto Web Server Administration Server, select the server you want to manage.
    (2)Select Preference >> Perfomance Tuning.
    (3)set HTTP Persistent Connection Timeout to your choice (eg 180 sec for three minutes)
    (4) Apply changes and restart the server.
    *Setting the timeout to a lower value, however, may    prevent the transfer of large files as timeout does not refer to the time that the connection has been idle. For example, if you are using a 2400 baud modem, and the request timeout is set to 180 seconds, then the maximum file size that can be transferred before   the connection is closed is 432000 bits (2400 multiplied by 180)
    Regards
    T.Raghulan
    [email protected]

  • HTML multipart form is not working in jsp page

    Hi
    i have jsp page, has a HTML from with file upload field , when i click the send button , nothing happened as if the button did not submit the form. ie the message at line 12 is not printed out.
    can any one help please.
    <%@ page errorPage="..\error\error.jsp" %>
    <%@ page pageEncoding="windows-1256" %>
    <%@ page language="java" import="javazoom.upload.*,java.util.*,java.sql.ResultSet" %>
    <jsp:useBean id="upBean" scope="page" class="javazoom.upload.UploadBean" >
      <jsp:setProperty name="upBean" property="folderstore" value="<%=request.getRealPath("thuraya//uploads")%>"  />
    </jsp:useBean>
    <jsp:useBean id="dbc" class="mypackage.DBConnection" scope="session" />
    <!-- add news-->
    <%
    if(request.getParameter("addBTN") != null){
            out.println("addbtn");
            //do upload file + insert in database
             if (MultipartFormDataRequest.isMultipartFormData(request))
             // Uses MultipartFormDataRequest to parse the HTTP request.
             MultipartFormDataRequest mrequest = new MultipartFormDataRequest(request);
             String todo = null;
             if (mrequest != null) todo = mrequest.getParameter("todo");
                 if ( (todo != null) && (todo.equalsIgnoreCase("upload")) )
                    Hashtable files = mrequest.getFiles();
                    if ( (files != null) && (!files.isEmpty()) )
                        UploadFile file = (UploadFile) files.get("filename");
                        if (file != null)
                                            out.println("<li>Form field : uploadfile"+"<BR> Uploaded file : "+file.getFileName()+" ("+file.getFileSize()+" bytes)"+"<BR> Content Type : "+file.getContentType());
                                            String fileName=file.getFileName();
                                            String ran=System.currentTimeMillis()+"";
                                            String ext=fileName.substring(   ( fileName.length()-4),fileName.length() );
                                            file.setFileName(ran+ext);
                        // Uses the bean now to store specified by jsp:setProperty at the top.
                        upBean.store(mrequest, "filename");
                                            String title=request.getParameter("title");
                                            String content=request.getParameter("elm1");
                                            int x=dbc.addNews(title,content,file.getFileName(),2,1);
                                            if(x==1)
                                                     out.print("New Vedio has been addedd Successfully");
                                                      response.setHeader("Refresh","1;URL=uploadVedio.jsp");
                                                     else{
                                                      out.print("An Error Occured while adding new Vedio");
                                                      response.setHeader("Refresh","1;URL=uploadVedio.jsp");
                    else
                      out.println("<li>No uploaded files");
             else out.println("<BR> todo="+todo);
    %>
    <!-- end of add news-->
    <form action="" method="post" enctype="multipart/form-data" name="upform" >
      <table width="99%" border="0" align="center" cellpadding="1" cellspacing="1">
        <tr>
          <td colspan="2" align="right" bgcolor="#EAEAEA" class="borderdTable"><p>'6'A) .(1 ,/J/</p></td>
        </tr>
        <tr>
          <td width="87%" align="right"><label>
            <input name="title" type="text" class="rightText" id="title">
          </label></td>
          <td width="13%" align="right">9FH'F 'D.(1</td>
        </tr>
        <tr>
          <td align="right"><textarea name="elm1" cols="50" rows="10" id="elm1" style="direction:rtl" >
              </textarea></td>
          <td align="right">*A'5JD 'D.(1</td>
        </tr>
        <tr>
          <td align="right"><label>
            <input type="file" name="filename" id="filename">
          </label></td>
          <td align="right">5H1)</td>
        </tr>
        <tr>
          <td align="right"><label>
            <input onClick="submit()" name="addBTN" type="button" class="btn" id="addBTN" value="  '6'A) .(1 ">
          </label></td>
          <td align="right"> </td>
        </tr>
      </table>
    </form>
    <!-- TinyMCE -->
    <script type="text/javascript" src="jscripts/tiny_mce/tiny_mce.js"></script>
    <script type="text/javascript">
            tinyMCE.init({
                    mode : "textareas",
                    theme : "simple",
                    directionality : "rtl"
    </script>
    <!--end of TinyMCE -->

    the problem is not because of java code insdie jsp page
    I have removed all things but the form and it is still not working
    here is the modified code:
    <!-- add news-->
    <%
    if(request.getParameter("addBTN") != null){
            out.print("addBTN");
    %>
    <!-- end of add news-->
    <form action="" method="post" enctype="multipart/form-data" name="upform" >
      <table width="99%" border="0" align="center" cellpadding="1" cellspacing="1">
        <tr>
          <td colspan="2" align="right" bgcolor="#EAEAEA" class="borderdTable"><p>'6'A) .(1 ,/J/</p></td>
        </tr>
        <tr>
          <td width="87%" align="right"><label>
            <input name="title" type="text" class="rightText" id="title">
          </label></td>
          <td width="13%" align="right">9FH'F 'D.(1</td>
        </tr>
        <tr>
          <td align="right"><textarea name="elm1" cols="50" rows="10" id="elm1" style="direction:rtl" >
              </textarea></td>
          <td align="right">*A'5JD 'D.(1</td>
        </tr>
        <tr>
          <td align="right"><label>
            <input type="file" name="filename" id="filename">
          </label></td>
          <td align="right">5H1)</td>
        </tr>
        <tr>
          <td align="right"><label>
            <input name="addBTN" type="submit" class="btn" id="addBTN" value="  '6'A) .(1 ">
          </label></td>
          <td align="right"> </td>
        </tr>
      </table>
    </form>
    <!-- TinyMCE -->
    <script type="text/javascript" src="jscripts/tiny_mce/tiny_mce.js"></script>
    <script type="text/javascript">
            tinyMCE.init({
                    mode : "textareas",
                    theme : "simple",
                    directionality : "rtl"
    </script>
    <!--end of TinyMCE -->

  • Useful Code of the Day:  Multipart Form File Upload

    So, you want to upload files to your web server, do ya? Well, I've seen this topic posted a few times in the last month or so and many of the response I've seen here haven't included definitive answers. Of course, the actual problems vary, but ultimately, a bunch of people want to do file upload from an applet or application to an existing file upload script (CGI, PHP, JSP, etc.) on a web server. And invariably, there are problems with formatting the HTTP request to get things working.
    Well, I had a need to do the same thing. I realize there are other solutions out there, such as some sample code that comes with Jakarta Commons Upload. But since we all like reusable code, and we also all seem to like reinventing wheels, here's my go at it: MultiPartFormOutputStream!
    MultiPartFormOutputStream is a specialized OutputStream-like class. You create your URLConnection to the server (a static method included can do this for a URL for you, as some of the settings, doInput and doOutput specifically, seem to confuse people). Then get the OutputStream from it and create a boundary string (a static method to create one is provided as well) and pass them to the constructor. Now you have a MultiPartFormOutputStream which you can use to write form fields like text fields, checkboxes, etc., as well as write file data (from Files, InputStreams or raw bytes).
    There are some convenience methods for writing primative type values as well as strings, but any higher level objects (aside from Files or InputStreams) aren't supported. (You can always serialize and pass the raw bytes.)
    Sample usage code is below. Also, any recommendations for improvement are requested. The code was tested with the Jakarta Struts.
    import java.io.*;
    import java.net.*;
    * <code>MultiPartFormOutputStream</code> is used to write
    * "multipart/form-data" to a <code>java.net.URLConnection</code> for
    * POSTing.  This is primarily for file uploading to HTTP servers. 
    * @since  JDK1.3
    public class MultiPartFormOutputStream {
          * The line end characters. 
         private static final String NEWLINE = "\r\n";
          * The boundary prefix. 
         private static final String PREFIX = "--";
          * The output stream to write to. 
         private DataOutputStream out = null;
          * The multipart boundary string. 
         private String boundary = null;
          * Creates a new <code>MultiPartFormOutputStream</code> object using
          * the specified output stream and boundary.  The boundary is required
          * to be created before using this method, as described in the
          * description for the <code>getContentType(String)</code> method. 
          * The boundary is only checked for <code>null</code> or empty string,
          * but it is recommended to be at least 6 characters.  (Or use the
          * static createBoundary() method to create one.)
          * @param  os        the output stream
          * @param  boundary  the boundary
          * @see  #createBoundary()
          * @see  #getContentType(String)
         public MultiPartFormOutputStream(OutputStream os, String boundary) {
              if(os == null) {
                   throw new IllegalArgumentException("Output stream is required.");
              if(boundary == null || boundary.length() == 0) {
                   throw new IllegalArgumentException("Boundary stream is required.");
              this.out = new DataOutputStream(os);
              this.boundary = boundary;
          * Writes an boolean field value. 
          * @param  name   the field name (required)
          * @param  value  the field value
          * @throws  java.io.IOException  on input/output errors
         public void writeField(String name, boolean value)
                   throws java.io.IOException {
              writeField(name, new Boolean(value).toString());
          * Writes an double field value. 
          * @param  name   the field name (required)
          * @param  value  the field value
          * @throws  java.io.IOException  on input/output errors
         public void writeField(String name, double value)
                   throws java.io.IOException {
              writeField(name, Double.toString(value));
          * Writes an float field value. 
          * @param  name   the field name (required)
          * @param  value  the field value
          * @throws  java.io.IOException  on input/output errors
         public void writeField(String name, float value)
                   throws java.io.IOException {
              writeField(name, Float.toString(value));
          * Writes an long field value. 
          * @param  name   the field name (required)
          * @param  value  the field value
          * @throws  java.io.IOException  on input/output errors
         public void writeField(String name, long value)
                   throws java.io.IOException {
              writeField(name, Long.toString(value));
          * Writes an int field value. 
          * @param  name   the field name (required)
          * @param  value  the field value
          * @throws  java.io.IOException  on input/output errors
         public void writeField(String name, int value)
                   throws java.io.IOException {
              writeField(name, Integer.toString(value));
          * Writes an short field value. 
          * @param  name   the field name (required)
          * @param  value  the field value
          * @throws  java.io.IOException  on input/output errors
         public void writeField(String name, short value)
                   throws java.io.IOException {
              writeField(name, Short.toString(value));
          * Writes an char field value. 
          * @param  name   the field name (required)
          * @param  value  the field value
          * @throws  java.io.IOException  on input/output errors
         public void writeField(String name, char value)
                   throws java.io.IOException {
              writeField(name, new Character(value).toString());
          * Writes an string field value.  If the value is null, an empty string
          * is sent (""). 
          * @param  name   the field name (required)
          * @param  value  the field value
          * @throws  java.io.IOException  on input/output errors
         public void writeField(String name, String value)
                   throws java.io.IOException {
              if(name == null) {
                   throw new IllegalArgumentException("Name cannot be null or empty.");
              if(value == null) {
                   value = "";
              --boundary\r\n
              Content-Disposition: form-data; name="<fieldName>"\r\n
              \r\n
              <value>\r\n
              // write boundary
              out.writeBytes(PREFIX);
              out.writeBytes(boundary);
              out.writeBytes(NEWLINE);
              // write content header
              out.writeBytes("Content-Disposition: form-data; name=\"" + name + "\"");
              out.writeBytes(NEWLINE);
              out.writeBytes(NEWLINE);
              // write content
              out.writeBytes(value);
              out.writeBytes(NEWLINE);
              out.flush();
          * Writes a file's contents.  If the file is null, does not exists, or
          * is a directory, a <code>java.lang.IllegalArgumentException</code>
          * will be thrown. 
          * @param  name      the field name
          * @param  mimeType  the file content type (optional, recommended)
          * @param  file      the file (the file must exist)
          * @throws  java.io.IOException  on input/output errors
         public void writeFile(String name, String mimeType, File file)
                   throws java.io.IOException {
              if(file == null) {
                   throw new IllegalArgumentException("File cannot be null.");
              if(!file.exists()) {
                   throw new IllegalArgumentException("File does not exist.");
              if(file.isDirectory()) {
                   throw new IllegalArgumentException("File cannot be a directory.");
              writeFile(name, mimeType, file.getCanonicalPath(), new FileInputStream(file));
          * Writes a input stream's contents.  If the input stream is null, a
          * <code>java.lang.IllegalArgumentException</code> will be thrown. 
          * @param  name      the field name
          * @param  mimeType  the file content type (optional, recommended)
          * @param  fileName  the file name (required)
          * @param  is        the input stream
          * @throws  java.io.IOException  on input/output errors
         public void writeFile(String name, String mimeType,
                   String fileName, InputStream is)
                   throws java.io.IOException {
              if(is == null) {
                   throw new IllegalArgumentException("Input stream cannot be null.");
              if(fileName == null || fileName.length() == 0) {
                   throw new IllegalArgumentException("File name cannot be null or empty.");
              --boundary\r\n
              Content-Disposition: form-data; name="<fieldName>"; filename="<filename>"\r\n
              Content-Type: <mime-type>\r\n
              \r\n
              <file-data>\r\n
              // write boundary
              out.writeBytes(PREFIX);
              out.writeBytes(boundary);
              out.writeBytes(NEWLINE);
              // write content header
              out.writeBytes("Content-Disposition: form-data; name=\"" + name +
                   "\"; filename=\"" + fileName + "\"");
              out.writeBytes(NEWLINE);
              if(mimeType != null) {
                   out.writeBytes("Content-Type: " + mimeType);
                   out.writeBytes(NEWLINE);
              out.writeBytes(NEWLINE);
              // write content
              byte[] data = new byte[1024];
              int r = 0;
              while((r = is.read(data, 0, data.length)) != -1) {
                   out.write(data, 0, r);
              // close input stream, but ignore any possible exception for it
              try {
                   is.close();
              } catch(Exception e) {}
              out.writeBytes(NEWLINE);
              out.flush();
          * Writes the given bytes.  The bytes are assumed to be the contents
          * of a file, and will be sent as such.  If the data is null, a
          * <code>java.lang.IllegalArgumentException</code> will be thrown. 
          * @param  name      the field name
          * @param  mimeType  the file content type (optional, recommended)
          * @param  fileName  the file name (required)
          * @param  data      the file data
          * @throws  java.io.IOException  on input/output errors
         public void writeFile(String name, String mimeType,
                   String fileName, byte[] data)
                   throws java.io.IOException {
              if(data == null) {
                   throw new IllegalArgumentException("Data cannot be null.");
              if(fileName == null || fileName.length() == 0) {
                   throw new IllegalArgumentException("File name cannot be null or empty.");
              --boundary\r\n
              Content-Disposition: form-data; name="<fieldName>"; filename="<filename>"\r\n
              Content-Type: <mime-type>\r\n
              \r\n
              <file-data>\r\n
              // write boundary
              out.writeBytes(PREFIX);
              out.writeBytes(boundary);
              out.writeBytes(NEWLINE);
              // write content header
              out.writeBytes("Content-Disposition: form-data; name=\"" + name +
                   "\"; filename=\"" + fileName + "\"");
              out.writeBytes(NEWLINE);
              if(mimeType != null) {
                   out.writeBytes("Content-Type: " + mimeType);
                   out.writeBytes(NEWLINE);
              out.writeBytes(NEWLINE);
              // write content
              out.write(data, 0, data.length);
              out.writeBytes(NEWLINE);
              out.flush();
          * Flushes the stream.  Actually, this method does nothing, as the only
          * write methods are highly specialized and automatically flush. 
          * @throws  java.io.IOException  on input/output errors
         public void flush() throws java.io.IOException {
              // out.flush();
          * Closes the stream.  <br />
          * <br />
          * <b>NOTE:</b> This method <b>MUST</b> be called to finalize the
          * multipart stream.
          * @throws  java.io.IOException  on input/output errors
         public void close() throws java.io.IOException {
              // write final boundary
              out.writeBytes(PREFIX);
              out.writeBytes(boundary);
              out.writeBytes(PREFIX);
              out.writeBytes(NEWLINE);
              out.flush();
              out.close();
          * Gets the multipart boundary string being used by this stream. 
          * @return  the boundary
         public String getBoundary() {
              return this.boundary;
          * Creates a new <code>java.net.URLConnection</code> object from the
          * specified <code>java.net.URL</code>.  This is a convenience method
          * which will set the <code>doInput</code>, <code>doOutput</code>,
          * <code>useCaches</code> and <code>defaultUseCaches</code> fields to
          * the appropriate settings in the correct order. 
          * @return  a <code>java.net.URLConnection</code> object for the URL
          * @throws  java.io.IOException  on input/output errors
         public static URLConnection createConnection(URL url)
                   throws java.io.IOException {
              URLConnection urlConn = url.openConnection();
              if(urlConn instanceof HttpURLConnection) {
                   HttpURLConnection httpConn = (HttpURLConnection)urlConn;
                   httpConn.setRequestMethod("POST");
              urlConn.setDoInput(true);
              urlConn.setDoOutput(true);
              urlConn.setUseCaches(false);
              urlConn.setDefaultUseCaches(false);
              return urlConn;
          * Creates a multipart boundary string by concatenating 20 hyphens (-)
          * and the hexadecimal (base-16) representation of the current time in
          * milliseconds. 
          * @return  a multipart boundary string
          * @see  #getContentType(String)
         public static String createBoundary() {
              return "--------------------" +
                   Long.toString(System.currentTimeMillis(), 16);
          * Gets the content type string suitable for the
          * <code>java.net.URLConnection</code> which includes the multipart
          * boundary string.  <br />
          * <br />
          * This method is static because, due to the nature of the
          * <code>java.net.URLConnection</code> class, once the output stream
          * for the connection is acquired, it's too late to set the content
          * type (or any other request parameter).  So one has to create a
          * multipart boundary string first before using this class, such as
          * with the <code>createBoundary()</code> method. 
          * @param  boundary  the boundary string
          * @return  the content type string
          * @see  #createBoundary()
         public static String getContentType(String boundary) {
              return "multipart/form-data; boundary=" + boundary;
    }Usage: (try/catch left out to shorten the post a bit)
    URL url = new URL("http://www.domain.com/webems/upload.do");
    // create a boundary string
    String boundary = MultiPartFormOutputStream.createBoundary();
    URLConnection urlConn = MultiPartFormOutputStream.createConnection(url);
    urlConn.setRequestProperty("Accept", "*/*");
    urlConn.setRequestProperty("Content-Type",
         MultiPartFormOutputStream.getContentType(boundary));
    // set some other request headers...
    urlConn.setRequestProperty("Connection", "Keep-Alive");
    urlConn.setRequestProperty("Cache-Control", "no-cache");
    // no need to connect cuz getOutputStream() does it
    MultiPartFormOutputStream out =
         new MultiPartFormOutputStream(urlConn.getOutputStream(), boundary);
    // write a text field element
    out.writeField("myText", "text field text");
    // upload a file
    out.writeFile("myFile", "text/plain", new File("C:\\test.txt"));
    // can also write bytes directly
    //out.writeFile("myFile", "text/plain", "C:\\test.txt",
    //     "This is some file text.".getBytes("ASCII"));
    out.close();
    // read response from server
    BufferedReader in = new BufferedReader(
         new InputStreamReader(urlConn.getInputStream()));
    String line = "";
    while((line = in.readLine()) != null) {
          System.out.println(line);
    in.close();------
    "Useful Code of the Day" is supplied by the person who posted this message. This code is not guaranteed by any warranty whatsoever. The code is free to use and modify as you see fit. The code was tested and worked for the author. If anyone else has some useful code, feel free to post it under this heading.

    I have a weird problem here. I'm using the Java POST (slightly altered for my purposes) mechanism but the receiving script doesn't receive any form variables (neither files nor regular form fields). If I try using the same receiving script with a regular upload form, it works. Because I've been pulling my hair out, I even went so far as to analyze the ip-packets. I can see that the file is actually sent through the Java POST mecahnism. Anybody any ideas. Here's the ip-packet of the failing upload:
    ----- Hypertext Transfer Protocol -----
    HTTP: POST /fotoxs/upload.cfm HTTP/1.1
    HTTP: Connection: Keep-Alive
    HTTP: Content-Type: multipart/form-data; boundary=-----------------------------fb2649be18
    HTTP: User-Agent: Mozilla/4.7 [en] (WinNT; U)
    HTTP: Accept-Language: en-us
    HTTP: Accept-Encoding: gzip, deflate
    HTTP: Accept: image/gif, image/jpeg, image/pjpeg, */*
    HTTP: CACHE-CONTROL: no-cache
    HTTP: Host: newmarc
    HTTP: Content-Length: 15511
    ----- Hypertext Transfer Protocol -----
    HTTP: -----------------------------fb2649be18
    HTTP: Content-Disposition: form-data; name="uploadFile"; filename="out.jpg"
    HTTP: Content-Type: image/jpeg
    HTTP: Data
    ....[data packets]
    The one that works (from the regular post) is as follows:
    ----- Hypertext Transfer Protocol -----
    HTTP: POST /fotoxs/upload.cfm HTTP/1.1
    HTTP: Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-gsarcade-launch, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*
    HTTP: Referer: http://localhost:8500/fotoxs/test.cfm
    HTTP: Accept-Language: nl
    HTTP: Content-Type: multipart/form-data; boundary=---------------------------7d41961f201c0
    HTTP: Accept-Encoding: gzip, deflate
    HTTP: User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)
    HTTP: Host: newmarc
    HTTP: Content-Length: 59022
    HTTP: Connection: Keep-Alive
    HTTP: Cache-Control: no-cache
    ----- Hypertext Transfer Protocol -----
    HTTP: -----------------------------7d41961f201c0
    HTTP: Content-Disposition: form-data; name="FiletoUpload"; filename="D:\My Documents\My Pictures\fotomarc.jpg"
    HTTP: Content-Type: image/pjpeg
    HTTP: Data
    ----- Hypertext Transfer Protocol -----
    HTTP: HTTP/1.1 100 Continue
    HTTP: Server: Microsoft-IIS/5.0
    HTTP: Date: Sun, 07 Mar 2004 17:14:41 GMT
    ....[data packets]
    One detail worth mentioning is that I don't read a file from harddisk, I'm streaming it directly to the connection outputstream from an image compression utility. But I can see the data in the ip-packets, and even if that somehow didn't work right, it doesn't explaing the fact that the receiving scripts reports no form fields whatsoever.
    Thanks,
    Marc

  • Multipart form (file upload) processing in providers

    Hello,
    Just want to find out if anyone has successfully implemented a file upload mechanism within a Portal channel.
    According to the Provider API (http://docs.sun.com/source/816-6428-10/com/sun/portal/providers/Provider.html), the wrapped request/response objects do not support several methods that are essential to process file uploads, namely "getContentLength" and "getInputStream". I am currently trying to use the Apache commons-fileupload utility which uses those methods to process file uploads. This is also the case for another popular file upload utility from servlets.com.
    Does anyone have any info/explanation regarding this limitation in Portal Server 6, and any workarounds to this issue. One workaround is to have a window popup that interacts directly with an external webapp.
    Any ideas/suggestions will be appreciated, thanks in advance.
    jeff

    Hi Jeff,
    The Sun ONE Portal Server DesktopServlet does not have the ability to process a request with the content encoding type of multipart/form-data. DesktopServlet does not pass the input stream for the request on to the Provider.
    To accomplish handling of multipart/form-data type requests, it is necessary to create a companion servlet or JSP that process the multipart/form-data. This servlet can then pass control back to the Portal channel. The data from the file can be shared between the servlet and the provider by using static Java members or by storing the data in a back-end database and then passing a reference to the data over to the provider.
    Sanjeev

  • Upload a file to the server - multipart/form-data ?

    I need to upload a file from my local machine to the server from a jsp page. I was asked to use a form with ENCTYPE = "multipart/form-data". but I am not sure how it works. Can any one enlighten me on the process or is there any other way to do it.
    null

    You can find the jsp source & the java sources which exactly does that in the iFS CMS sample code section. Go to Products -> Internet File system -> sample code -> Content Management System. This application allows the user to upload files from a local file system into iFS. This application creates the file in the iFS repository. You may want to save it in the file system of the web server. You may have to make little changes but the functionality is exactly what you are looking for.
    Hope this helps.
    Rajesh

  • Multipart/form-data and file attachment

    Hi ,
    This question has probably been asked before, but if not then here it is. Any replies will be appreciated:
    Q. When using "Enctype=Multipart/form-data", with file attachment alongwith other form fields, is it mandatory to attach a file ? What if user selects no file to attach?
    Q. If no, then how can it be possible that a form can be submitted without attaching a file since when I try to submit a form with no file attached to it, it gives me error message saying :java.lang.NullPointerException
    Q. Does it mean that I can't have a form with a blank "File" input field, if the form's Enctype is "multipart/form-data"? Since users may not select a file to attach to the form, in other words it is an optional.
    I hope I was clear enough in explaining my questions.
    Thanks in advance.

    I am using Orielly's file attachement pacakge.
    Here's what I am doing in my JSP page: It does the following:
    int maxFileSize = 10 * 1024 * 1024; // 5MB max
    String uploadDir = "/direct/files/upload/";
    String FormResults = "";
    String FileResults = "";
    String fileName = "";
    String fileName2 = "";
    String paramName="";
    String paramValue="";     
    File f;
    int filecounter=1;
    first get the form fields using following code:
    MultipartRequest multi = new MultipartRequest(request, uploadDir, maxFileSize);
    Enumeration params = multi.getParameterNames();
    //Get the form information
    while (params.hasMoreElements())
         paramName = (String) params.nextElement();     
         paramValue = multi.getParameter(paramName);
         if (paramName.equals("emailconfirm"))
              emailconfirmation = paramValue;
         else if (paramName.equals("Requester"))
              Requester = paramValue;
         else if (paramName.equals("TodaysDate"))
              TodaysDate = paramValue;
         else if (paramName.equals("Extension"))
    }//end while
    Then it gets the file information using the following code: I have two file fields in my form so that's why I am using a filecounter to find out if user has attached two files or just one:
    Enumeration files = multi.getFileNames();
    while (files.hasMoreElements())
         String formName = (String) files.nextElement();
         if (filecounter == 2)
    fileName2 = multi.getFilesystemName(formName);
         String fileType = multi.getContentType(formName);
              f = multi.getFile(formName);
         FileResults += "<BR>" + formName + "=" + fileName2 + ": Type= " + fileType + ":
    Size= " + f.length();
         else
         {     fileName = multi.getFilesystemName(formName);
              String fileType = multi.getContentType(formName);
              f = multi.getFile(formName);
              FileResults += "<BR>" + formName + "=" + fileName + ": Type= " + fileType + ":
    Size= " + f.length();
         filecounter=filecounter+1;
    Then after composing the mail message I send email with the form fields and file attachments using following code:
    Properties props = new Properties();
    MimeBodyPart mbp1 = new MimeBodyPart();
    MimeBodyPart mbp2 = new MimeBodyPart();
    MimeBodyPart mbp3 = new MimeBodyPart();
    URLDecoder urlDecoder = new URLDecoder();
    String to1 = urlDecoder.decode(toemail);
    String from1 = urlDecoder.decode(fromemail);
    String cc1 = urlDecoder.decode(ccemail);
    props.put( "mail.host", host );
    Session session1 = Session.getDefaultInstance(props, null);
    // Construct the message
    Message msg = new MimeMessage( session1 );
    msg.setFrom( new InternetAddress( from1 ) );
    msg.setRecipients( Message.RecipientType.TO, InternetAddress.parse( to1, false ) );
    msg.setRecipients( Message.RecipientType.CC, InternetAddress.parse( cc1, false ) );
    msg.setSubject( subject );
    msg.setHeader( "X-Mailer", "ExceptionErrorMail" );
    msg.setSentDate( new Date() );
    mbp1.setText(mail_message);
    mbp1.setContent(mail_message, "text/html");
    // Send the email message
    FileDataSource fds = new FileDataSource(uploadDir + fileName);
    FileDataSource fds2 = new FileDataSource(uploadDir + fileName2);
    mbp2.setDataHandler(new DataHandler(fds));
    mbp3.setDataHandler(new DataHandler(fds2));
    mbp2.setFileName(fileName);
    mbp3.setFileName(fileName2);
    Multipart mp = new MimeMultipart();
    mp.addBodyPart(mbp1);
    mp.addBodyPart(mbp2);
    mp.addBodyPart(mbp3);
    msg.setContent(mp);
    Transport.send( msg );
    //email sent...
    //delete the two files from the server..
    File f2 =new File(uploadDir + fileName);
    f2.delete();
    File f3 =new File(uploadDir + fileName2);
    f3.delete();     
    //End of code
    So when I don't attach a file and submit my form , I get the error message that I mentioned in my previous post.
    Any more ideas?

  • Can't pass parameter from HTML form of multipart/form-dta type to JSP

    I am using request.getParameter(passed variable name) to pass data from HTML form to JSP with no problem. WHen I try to pass data from HTML form of multipart/form-dta type to JSP as following:
    < form enctype="multipart/form-data" name="theForm" method="post" ACTION="http://titan.ssd.loral.com:7778/ifs/jsp-bin/ifs-cts/stringsecond.jsp">
    The passed value is null. Why?
    How can I pass data successfully from this form to JSP?
    How can I pass data from JavaScript to JSP?
    Thank you

    I am using request.getParameter(passed variable name)
    to pass data from HTML form to JSP with no problem.
    WHen I try to pass data from HTML form of
    multipart/form-dta type to JSP as following:
    < form enctype="multipart/form-data" name="theForm"
    method="post"
    ACTION="http://titan.ssd.loral.com:7778/ifs/jsp-bin/if
    -cts/stringsecond.jsp">
    The passed value is null. Why?because the jsp most likely does not handling of POST parameters like this.
    How can I pass data successfully from this form to
    JSP?jsp's are not meant to read such amounts of data. this (= uploading) is a typical task for a specialized servlet. there you have full control over input and output. if you need to, you can still forward to a jsp after processing in the servlet.
    How can I pass data from JavaScript to JSP???? i'm not sure what exactly you mean. normally you put it into an url and submit it.
    robert

  • J2me multipart file upload-  Help Needed

    package com.mpbx;
    import javax.microedition.midlet.*;
    import javax.microedition.lcdui.*;
    import javax.microedition.io.*;
    import java.io.*;
    public class PostFile extends MIDlet implements Runnable, CommandListener{
        private final String FILE = "/image.jpg";
        private final String URL = "http://localhost/post.php"; // change this to a valit page.
        private final String CrLf = "\r\n";
        private Form form = null;
        private Gauge gauge = null;
        private Command exitCommand;
        private Command uploadCommand;
        public PostFile(){
            form = new Form("Upload File");
            gauge = new Gauge("Progress:", true, 100, 0);
            form.append(gauge);
            exitCommand = new Command("Exit", Command.EXIT, 0);
            uploadCommand = new Command("Upload", Command.SCREEN, 0);
            form.addCommand(exitCommand);
            form.addCommand(uploadCommand);
            form.setCommandListener(this);
        public void startApp() {
            Display.getDisplay(this).setCurrent(form);
        public void pauseApp() {
        public void destroyApp(boolean unconditional) {
        private void progress(int total, int current){
            int percent = (int) (100 * ((float)current/(float)total));
            gauge.setValue(percent);
        public void run() {
            httpConn();
        private void httpConn(){
            HttpConnection conn = null;
            OutputStream os = null;
            InputStream is = null;
            try{
                System.out.println("url:" + URL);
                conn = (HttpConnection)Connector.open(URL);
                conn.setRequestMethod(HttpConnection.POST);
                String postData = "";
                InputStream imgIs = getClass().getResourceAsStream(FILE);
            byte []imgData = new byte[imgIs.available()];
               imgIs.read(imgData);
                String message1 = "";
                message1 += "-----------------------------4664151417711" + CrLf;
                message1 += "Content-Disposition: form-data; name=\"uploadedfile\"; filename=\"" + FILE + "\"" + CrLf;
                message1 += "Content-Type: image/jpeg" + CrLf;
                message1 += CrLf;
                // the image is sent between the messages ni the multipart message.
                String message2 = "";
                message2 += CrLf + "-----------------------------4664151417711--" + CrLf;              
                conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=---------------------------4664151417711");
                // might not need to specify the content-length when sending chunked data.
                // conn.setRequestProperty("Content-Length", String.valueOf((message1.length() + message2.length() + imgData.length)));
                System.out.println("open os");
                os = conn.openOutputStream();
                System.out.println(message1);
                os.write(message1.getBytes());
                // SEND THE IMAGE
                int index = 0;
                int size = 1024;
                do{
                    System.out.println("write:" + index);
                    if((index+size)>imgData.length){
                        size = imgData.length - index;
                    os.write(imgData, index, size);
                    index+=size;
                    progress(imgData.length, index); // update the progress bar.
                }while(index<imgData.length);
                System.out.println("written:" + index);           
                System.out.println(message2);
                os.write(message2.getBytes());
                os.flush();
                System.out.println("open is");
                is = conn.openInputStream();
                char buff = 512;
                int len;
                byte []data = new byte[buff];
                do{
                    System.out.println("READ");
                    len = is.read(data);
                    if(len > 0){
                        System.out.println(new String(data, 0, len));
                }while(len>0);
                System.out.println("DONE");
            }catch(Exception e){
                e.printStackTrace();
            }finally{
                System.out.println("Close connection");
                try{
                    os.close();
                }catch(Exception e){}
                try{
                    is.close();
                }catch(Exception e){}
                try{
                    conn.close();           
                }catch(Exception e){}
        public void commandAction(javax.microedition.lcdui.Command command, javax.microedition.lcdui.Displayable displayable) {
            if(command == exitCommand){
                this.notifyDestroyed();
            }else if(command == uploadCommand){
                new Thread(this).start();
    }Running this yields the error below...Can someone suggest me. whats the problem.
    url:http://localhost/post.php
    java.lang.NullPointerException
            at com.mpbx.PostFile.httpConn(PostFile.java:85)
            at com.mpbx.PostFile.run(PostFile.java:68)
    Close connection

    I also faced the same problem. To make this code work you will have to include the image.jpg in the jar. To do that, copy the image file in the src directory inside your project folder (if you are using netbeans) and then build the project.
    Remember, the web server should be running in background.

  • Problem with session while sending a multipart-form (a file via post)

    I have a problem with the communication between my applet and my server. I use a method to post an xml to my server with the Content-Type "application/x-www-form-urlencoded" and with it I'm not having any problem to preserve the session.
    However I use another method I found in the forums to post files and try to adapt it, but I'm being send from the server to the login page because it's not recognizing my session
    Can anybody help me? This is my method
    public String uploadFile(String adr, BufferedImage img) {
            String res = "";
            String CONTENT_BOUNDARY = "--abvx98734732";
            String s;
            File f = null;
            URL url;
            URLConnection conn;
            try {
                url = new URL(adr);
                conn = url.openConnection();
                conn.setDoOutput(true);
                conn.setRequestProperty("Content-Type",
                        "multipart/form-data; boundary=" + CONTENT_BOUNDARY);
                conn.setRequestProperty("file-Name", "process_image.jpg");
                DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
                wr
                        .write(("--"
                                + CONTENT_BOUNDARY
                                + "\r\n"
                                + "Content-Disposition: form-data; name=\"fileData\"; filename=\""
                                + "process_image.jpg" + "\"\r\nContent-Type: image/jpg\r\n\r\n")
                                .getBytes());
                ImageIO.write(img, "jpg", wr);
                wr.write(("\r\n--" + CONTENT_BOUNDARY + "--\r\n").getBytes());
                wr.flush();
                BufferedReader in = new BufferedReader(new InputStreamReader(conn
                        .getInputStream()));
                while ((s = in.readLine()) != null) {
                    res += s;
                in.close();
            catch (MalformedURLException muo) {
                muo.printStackTrace();
            catch (IOException io) {
                io.printStackTrace();
            return res;
        }This is how I preserve session in my other method:
    private static final String SESSION_KEY = "_session_id";
    URLEncoder.encode(SESSION_KEY, "UTF-8") + "=" +
    URLEncoder.encode(sessionId, "UTF-8");
    wr.writeBytes(content);
    ....

    Yes, the only way is to pass the value u want in the query string. But make sure that the value is not too large.
    In case you have too much info i guess the only way is to circumvent multipart and handle the process in your own custom class, which wont be worth the effort if u need pass only 2-3 small parameters.
    Always,
    Leo.
    Hi,
    Before I upload a file, I want to get a few parameter
    values (getParameter) on the form first. I've tried
    using com.oreilly.servlet MultipartRequest and a few
    other free servlets but they require that the file
    must to be uploaded first. For example:
    MultipartRequest multi = new
    MultipartRequest(request,filepath, 10*1024*1024);
    //this will instantiate the object and upload the
    file
    String command = multi.getParameter("command"); //get
    the form parameter
    Is there any way I can get the parameter first before
    uploading the file? I truly appreciate any helps you
    can provide me.
    Regards,
    Lily

  • Multiple select multipart/form-data + FileUploader

    Hi
    I'm using asp multiple select form field with
    multipart/form-data +
    FileUploader to upload a file (works fine) and writing the
    contents of
    a form to a database which works fine apart from the multiple
    select
    which although allows me to select multiple items only
    returns the
    first selected item to the database.
    Anywork arounds to this??
    Thanks in advance!!
    Buzby
    There's nothing more dangerous than a resourceful idiot

    Multi-part requests are not packaged the same as regular requests, so the getParameter() method doesn't work on it (although I think it would get anything passed through the query string as part of the action parameter but I'm not sure).
    You can also try the com.oreilly.servlet class MultipartRequest. I don't know if that's the same one found in the www.servlets.com link, but it is REALLY easy. Essentially, it looks like this:
    MultipartRequest mr = new MultipartRequest(request, "[pathtosavefiles]'");
    String param = mr.getParameter("paramname");
    So instead of calling getParameter() on the request object, you now instead call it on the MultipartRequest object. When you instantiate the MultipartRequest object, it parses the request body for you, and also saves any uploaded files into the directory you specified in your path in the constructor.
    I hope that helps.
    Michael

  • Get all the values from a multiple select in a multipart form

    Hi there!
    I am using a form with enctype="multipart/form-data" in order to upload files from the form.
    I have read this page: http://commons.apache.org/fileupload/using.html and everything works well for my form.
    The only problem is that I can't get all the values from a "multiple select" html object. I get only one value.
    Using servlets I have used this method:
    public java.lang.String[] getParameterValues(java.lang.String name) But now I have enctype="multipart/form-data" in my form and I can't use this way...
    Is there a way to get all the values of a multi-valued parameter?
    Thanks a lot!
    Stefano

    Hi
    I have got solution for this problem so, I am listing here logic
    assume tag name of html
    <select name="moption" multiple="multiple">
    iterate it in as
    String moption="";
    boolean cnt=true;
    while(itr.hasNext())
    FileItem fi=(FileItem)itr.next();
    if(fi.isFormField())
    if(fi.getFieldName().equals("moption"))
    if(cnt==true)
    moption=fi.getString();
    cnt=false;
    else
    moption=moption+","+fi.getString();
    If wants more help then mail me your problem
    at [email protected]
    Thanks!
    Anand Shankar
    Edited by: AnandShankar on 6 Nov, 2009 12:54 PM

  • Problem with ENCTYPE='multipart/form-data'

    In my program I want to upload a file along with other details.
    I've dowloaded org.apache.commons.fileupload.* jar files and everything works fine only if I give
    <INPUT TYPE='file' NAME='file1'>
    i.e the file is uploaded
    But if I add any other field it becomes blank
    Title : <INPUT id=text1 maxlength="30" name=GHN1 >
    the value of GHN1 becomes blank. what cud be the problem.
    Here is my program
    <%@ page contentType="text/html; charset=iso-8859-1" language="java" import="java.sql.*,java.text.SimpleDateFormat.*,java.text.ParseException.*,java.text.*,java.text.DateFormat.*,java.util.*,java.util.Date.*,com.gh.db.*,org.apache.commons.fileupload.*,org.apache.commons.fileupload.servlet.ServletFileUpload,org.apache.commons.fileupload.disk.DiskFileItemFactory,org.apache.commons.io.FilenameUtils,java.io.*,java.io.File,java.lang.Exception" errorPage="Error.jsp" %>
    <%
    String TACm1="";
    String TASid,Nme="",Cm2="",GHN1="",GHN2="",GHN3="",Sid="";
    TACm1=((request.getParameter("TAIdCombo"))!=null?(request.getParameter("TAIdCombo")):"");
    DBconnection TApool = DBconnection.getInstance();
    Connection con2 = TApool.getConnection();
    con2.setAutoCommit(false);
    Statement TAst1 = con2.createStatement();
    ResultSet TArs1 = null,rs2=null,rs1=null;
    Cm2=((request.getParameter("TMIdCombo2"))!=null?(request.getParameter("TMIdCombo2")):"");
    java.util.Date d1;
    java.sql.Date d2;
    SimpleDateFormat format=new SimpleDateFormat("dd/MM/yyyy");
    %>
    <html>
    <head>
    <TITLE>Guest Houses of DOS</TITLE>
    </head>
    <%@ include file="StdValidations.js" %>
    <%@ page buffer="1094kb"%>
    <script Language="JavaScript">
    </script>
    <body onload="window.history.forward(1);">
    <FORM ENCTYPE='multipart/form-data' name="GHInfoDetails1"
         method='POST' action="GHInfoDetails1.jsp">'<br><br><br>
    <center>
    <%      
         String LoginName= "";
         String Name= "";
         String SectionName= "";
         try
              LoginName = session.getAttribute("LoginName").toString();
              Name = session.getAttribute("Name").toString();
              SectionName = session.getAttribute("SectionName").toString();     
         catch(NullPointerException npe)
              %>
              <jsp:forward page="LoginHere.jsp" >
              <jsp:param name="SessionMode" value="Session Expired try again to log on" />
              </jsp:forward>
              <%
    %>
    <%
              GHN1 = request.getParameter("GHN1");
              if (GHN1 == null) GHN1 = "";
              GHN2 = request.getParameter("GHN2");
              if (GHN2 == null) GHN2 = "";
              GHN3 = request.getParameter("GHN3");
              if (GHN3 == null) GHN3 = "";
    %>
         <table width="100%" bgcolor="#F7EDF7">
              <tr >
              <td align="center">
                   <img src="Images/Title2.gif">
              </td>
              </tr>
              </table>
              <table width="100%" bgcolor="#F7EDF7">
              <tr>
              <td >
                   <b><font face="Times New Roman, Times, serif" color="#402180" size="+1">Logged in as:  <%= Name %></font></b>
              </td>
              <td >
                   <b><font face="Comic Sans MS" color="#402180" size="+1">Other Details of Guest House</font></b>
              </td>
              <td align="right">
                   <b><font face="Times New Roman, Times, serif" color="#402180" size="+1">Logout</font></b>
              </td>
              </tr>
         </table>
              <table width="100%" bgcolor="#B6C7E5" border="1">
              <tr>
              <td valign="top">
              </br>
              <p><img src="Images/bullet.gif"><b><font face="Times New Roman, Times, serif" color="#402180" size="+0">Defining Guest House Information</font></b></p>
              <p><img src="Images/bullet.gif"><b><font face="Times New Roman, Times, serif" color="#402180" size="+0">Cancelling Guest House Information</font></b></p>
              </td>
              <td align="left"></br>
                   <table width="100%" bgcolor="#B6C7E5">
                   <tr>
                                  <td width="60%" align="right"></br>
                                  <P >Category :  <select onChange="TAMAssignCombo2();" name="TMIdCombo2" style="WIDTH: 120px" >
                                                                <option value="-">Select</option>
                                                                <% try
                                                                     PreparedStatement ps6=con2.prepareStatement("Select CategoryName from TableCategory order by CategoryName");
                                                                     rs2 = ps6.executeQuery();     
                                                                     while(rs2.next())
                                                                          Sid=rs2.getString(1);
                                                                               %>
                                                                                    <option value = "<% out.write(Sid); %>"><% out.write(Sid); %></option>
                                                                               <%
                                                                catch(Exception e)
                                                                     e.printStackTrace();
                                                                %>
                                                                     <Script>alert("Exception Occured : <%= e %>");</Script>
                                                                <%
                                                                %>
                                                 </select>
                                  </P>
                   </td>
                   </tr>
                   <tr align="center">
                   <td>
                        Title :     <INPUT id=text1 maxlength="30" name=GHN1 onKeyPress="if (((event.keyCode > 32) && (event.keyCode < 48)) || ((event.keyCode > 57) && (event.keyCode < 65)) || ((event.keyCode > 90) && (event.keyCode < 97))) event.returnValue=false;">
                   </td>
                   </tr>
                   <tr align="center">
                   <td>
                        Reference No :     <INPUT id=text1 maxlength="100" name=GHN2 onKeyPress="if (((event.keyCode > 32) && (event.keyCode < 48)) || ((event.keyCode > 57) && (event.keyCode < 65)) || ((event.keyCode > 90) && (event.keyCode < 97))) event.returnValue=false;">
                   </td>
                   </tr>
                   <tr align="center">
                   <td>
                        Date :     <INPUT id=text1 maxlength="30" name=GHN3 >
                   </td>
                   </tr>
                   <tr align="center">
                   <td >
                   </br>
                                           File Name:        <INPUT TYPE='file' NAME='file1'></p>
                   </td></tr>
                   <tr>
                   <td align="center">
                                                         <INPUT TYPE='submit' VALUE='Submit' ></br>
                   <b><font face="Times New Roman, Times, serif" color="#402180" size="3">(Information like distance,direction from central places such as Railway station, Airport, Bus Terminal....etc can be added in a file of windows format(such as word, pdf...) and can be uploaded through this screen. This will be displayed for the ISRO Guests.</font></b>)
                   </td>
                   </tr>
                   </table>
              </td>
              </tr>
              </table>
              <table width="100%" bgcolor="#B6C7E5">
              <tr>
              <td align="center">
                   </br>
                   <img src="Images/Home.jpg">
              </td>
              </tr>
              </table>     
    <% if (ServletFileUpload.isMultipartContent(request))
         GHN1 = request.getParameter("GHN1");
         if (GHN1 == null) GHN1 = "";
         GHN2 = request.getParameter("GHN2");
         if (GHN2 == null) GHN2 = "";
         GHN3 = request.getParameter("GHN3");
         if (GHN3 == null) GHN3 = "";
         DiskFileUpload fileUpload = new DiskFileUpload();
         List list = null;
         try
              list = fileUpload.parseRequest(request);
         catch(FileUploadException ex)
              throw new ServletException("Wrapped",ex);
         Iterator iter = list.iterator();
         while (iter.hasNext())
         FileItem item = (FileItem) iter.next();
         if (!item.isFormField())
              File itemFile = new File(item.getName());
              Nme=itemFile.getName();
              %>
              <%
              File destDir = new File(getServletContext().getRealPath("/")
                                       +"stored");
         if(!destDir.exists())
              destDir.mkdirs();
         File destFile = new File(getServletContext().getRealPath("/")
                                       +"stored"+File.separator+itemFile.getName());
         try
              item.write(destFile);
         catch(Exception ex)
              //throw new ServletException("Wrapped",ex);
         TACm1=SectionName;
         %><script>alert("<%=GHN1%>");</script><%
         try
              PreparedStatement ps26=     con2.prepareStatement("select CategoryNo from TableCategory where CategoryName=?");
              ps26.setString(1,Cm2);
              rs1=ps26.executeQuery();
              while (rs1.next())
                   PreparedStatement ps16=con2.prepareStatement("inset into TableMetaData (CategoryNo,Title,RefernceNo,Date,FileName) values(?,?,?,?,?)");
                   ps16.setString(1,rs1.getString(1));
                   ps16.setString(2,GHN1);
                   ps16.setString(3,GHN2);
                   d1=format.parse(GHN3);
                   d2=new java.sql.Date(d1.getTime());     
                   ps16.setDate(4,d2);
                   ps16.setString(5,Nme);
                   int NoOfRows=ps16.executeUpdate();
                   con2.commit();
         catch(Exception e)
              e.printStackTrace();
         %>
                             <script> alert("Error : <%= e %>"); </script>
         <%
    %>
    <%
              if (TAst1 != null) TAst1.close();
                                  if (con2 != null)
                                       con2.rollback();
                                       con2.setAutoCommit(true);
                                       TApool.returnConnection(con2);
              %>
    <input name="HomePage" type="hidden">
    </form>
    </body>
    </html>

    This article is worth reading: http://balusc.blogspot.com/2007/11/multipartfilter.html

  • Multipart/form-data using HTTPService, sending a binary file and some text in the same request.

    Hi There,
             I am new to FLEX and also new to writing a client for a web service.
    My question is more about flex (Flash builder 4.5) APIs, what APIs to use.
    I want to access a web service, that's published here.
    https://build.phonegap.com/docs/write_api
    here is the description of webservice
    ===========
    1) I have to do a post on POST https://build.phonegap.com/api/v1/apps
    2) content type has to be "multipart/form-data"
    3) JSON bodies of requests are expected to have the name 'data'
      data will be someting like this
    'data={"title":"API V1 App","package":"com.alunny.apiv1","version":"0.1.0","create_method":"file"}'
    4) include a zip file in the multipart body of your post, with the parameter name 'file'.
    ===========
    I want to make a 'multipart/form-data' Post and send
    one string and one zip file.
    My first question to self was If i send both string + binary data in the body ...
    how will server understand where string end and where zip file starts?
    Then read on W3.org( http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.2 )
    How is text + binary data can be sent through "multipart/form-data" post requst.
    there has to be some boundries.
    After this I read and example in flex and  tried following it.
    http://codeio.wordpress.com/2010/04/03/5-minutes-on-adobe-flex-mimic-file-upload-for-in-me mory-contents/
    but it doesn't seems to be working for me.
                        public function createNewApp(cb:Function , appFile : File):void
                                  var service:HTTPService = new HTTPService();
                                  service.url = ROOT+"apps";
                                  service.showBusyCursor = true;
                                  service.addEventListener(ResultEvent.RESULT, function(e:ResultEvent):void {
                                            //translate JSON
                                            trace(e.result);
                                            var result:String = e.result.toString();
                                            var data:Object = JSON.parse(result);
                                            cb(data.link);
                                  service.addEventListener(FaultEvent.FAULT, defaultFaultHandler); //todo : allow user to add his own as well
                                  authAndUploadNewApp(service,appFile);
                        private function authAndUploadNewApp(service:HTTPService,appFile : File):void {
                                  var encoder:Base64Encoder = new Base64Encoder();
                                  encoder.encode(username + ":"+password);
                                  service.headers = {Accept:"application/json", Authorization:"Basic " + encoder.toString()};
                                  service.method ="POST";
                                  var boundary:String = UIDUtil.createUID();
                                  service.contentType = "multipart/form-data; boundary=—————————" + boundary;
                                  var stream:FileStream = new FileStream();
                                  stream.open(appFile, FileMode.READ);
                                  var binaryData:ByteArray = new ByteArray();
                                  var fileData : String = new String();
                                  stream.readBytes(binaryData);
                                  stream.close();
                                  fileData = binaryData.readUTFBytes(binaryData.bytesAvailable); // I think this is where I have problem.... how do
                           //how do i converrt this bytearray/stream of data to string and send it in my post request's body - i guess if this step work rest should work..  
                                  var params: String = new String();
                                  var content:String = "—————————" + boundary + "nr";
                                  content += 'Content-Disposition: form-data; name="data";' + '{"title":"ELS test app 2","package":"com.elsapp.captivate","version":"12.3.09","create_method":"file"}' + "nr";
                                  content += "—————————" + boundary + "nr";
                                  content += 'Content-Disposition: form-data; name="file";' + fileData  + "nr";
                                  content += "—————————–" + boundary + "–nr";
                                  service.request = content;
                                  service.send();

    In the past I have used URLVariables with URLRequest and URLLoader to achieve this kind of requirement.
    Check out http://livedocs.adobe.com/flex/3/html/help.html?content=17_Networking_and_communications_3 .html which should be useful. My preference has always been to use this style instead of HTTPService objects, giving you a little more control which is what you need here.
    Let me know if you need any more assistance.

Maybe you are looking for

  • Officejet Pro 8500 Premier - only one printhead is displayed in 'Printheads Health' window

    I changed the black/yellow printhead today in my HP Officejet Pro 8500 Premier printer.  When I closed the lid, the printer did its housekeeping thing, clicking away while it aligned heads, etc, and printed out a diagnostic sheet that looked terrific

  • Finder lock ups due to samba shares being invalidated by changing network

    I often leave my macbook online for a long time unattended, for simplicity I tend to plug it into its power lead, and also connect it up to my gigabit network. I know i've set the priority in my connections to prefer the wired connection over wireles

  • Changing "file type" in Link Information Window (CS3)

    Hola, I am having a problem in Indesign (CS3), and I was wondering if anyone here might be able to help. I'm a student updating an older .INDD file for a 47 page book. The pages were all updated as .AI files, but for some reason 3 of the pages in our

  • Rev B Won't Wake Up

    I have a Rev B 17" iMac that I have never had any issues with until today. It would not wake up from sleep and when I pressed a key the screen was black and the fans went full blast. I then powered it down and restarted and everything was fine. Ran h

  • Syncing digital movie to ipod touch

    I downloaded several digital copies of DVD movies I purchased to iTunes but get an error message when I try to sync them on to my new iPod touch. Basically says I am not allowed play these on my computer. I don't know what I am doing wrong. I do have