hi dear’s

I am caught in the problem that when i use “Form ENCTYPE=”multipart/form-data” and Method=”Post” and ACTION=”FileProcess.jsp” then i am get the file on FileProcess.jsp but i can’t get the other data

like example Problem Post by that Some Person

______________________________________________________________________________________________

http://www.velocityreviews.com/forums/t137597-html-file-upload-using-enctype-multipart-form-data-in-form.html

Should we use enctype=multipart/form-data in the form, I know it is recommended
if the form has <input type=”file”>. My form has and other
html controls.

I tried the following,

form.html
=========

POST” enctype=multipart/form-data>”

 

<input type=text name=”name” size=80>”

filename” size=80>”

<input type=”submit” value=”Upload File Test”>’
“</FORM>”

test.jsp
=========
<p><%= “filename = ” + request.getParameter(“filename”) %>
<p><%= “name = ” + request.getParameter(“name”) %>

It will output
filename = null
name = null

I don’t understand why, but if i remove enctype=multipart/form-data in the form,
then I am able to get the data.
Please advise. Thanks!!

_______________________________________________________________________________________________

Now i think you Have Clear Picture in Your Mind …….

Now i am going to tell you solution which i get From My RND and Try………..

1)Test.jsp

"!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
html
 "   head
script
             var e="";
function selValue(){
                //  alert('me there');
                e = document.getElementById("name");
                //   alert('me there ='+e);
                if(e=="")
                {
                    alert('Please Select');

                }else{

                    window.location.replace("Accountdetials.jsp?value="+e);
                }//  window.location="<%= request.getContextPath() + "/Test.jsp"%>"+"?value="+e;

            }
/script
<scriplet 
String selectedindex = "";

            String AccountStatus = request.getParameter("value");
            if (AccountStatus != null) {

                System.out.println("value=" + AccountStatus);
                session.setAttribute("AccountStatus", AccountStatus);

            } else {
                session.setAttribute("AccountStatus", null);
            }
/secriplet

body
FORM ENCTYPE="multipart/form-data" ACTION="FileProcess.jsp" METHOD=POST>

center>
table border="0" bgcolor=#ccFDDEE>
tr>UPLOAD THE FILE
tr> 
INPUT NAME="name" TYPE="text"
Choose the file To Upload:
INPUT NAME="file" TYPE="file"

input type="submit" value="Send File" 
table>
center> 
FORM>
BODY>
HTML>

 In above page you see one is <input and="" other="" input="" now="" when="" we="" use ="" "form="" enctype="multipart/form-data" then="" can't="" get="" data="" on="" page="" like="" that 
 boz now you data is send in multiparts for that reason we get file data like that which i tell in the below  FileProcess.jsp  now get the file data in the below page but not get the intput Type="text" data ..... now for that i use JAVASCRIPT like that now you can see the above Javascript function selValue(); then scriptlet of jsp how i put it in the session now when 
you press the Submit button the value of input text is all ready in the session .... now on next action jsp page just 
get that value from session 
I can do this on the Select Option tag ...... 

2)FileProcess.jsp

<scriplet
int totalRows = 0;
    String saveFile = "";
    String contentType = request.getContentType();
    if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)) {
        DataInputStream in = new DataInputStream(request.getInputStream());
        System.out.println("dddda  === \n " + in.toString());
        int formDataLength = request.getContentLength();
        pi_filesize = formDataLength / 1024;        byte dataBytes[] = new byte[formDataLength];
        int byteRead = 0;
        int totalBytesRead = 0;
        while (totalBytesRead < formDataLength) {
            byteRead = in.read(dataBytes, totalBytesRead, formDataLength);
            totalBytesRead += byteRead;
        }
        String file = new String(dataBytes);
        saveFile = file.substring(file.indexOf("filename=\"") + 10);
        //System.out.println(saveFile + "\t 1" + file.toString());
        saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
        // System.out.println(saveFile + "\t 2");
        saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1, saveFile.indexOf("\""));
        // System.out.println(saveFile + "\t 3");
        int lastIndex = contentType.lastIndexOf("=");
        String boundary = contentType.substring(lastIndex + 1, contentType.length());
        int pos;
        pos = file.indexOf("filename=\"");
        pos = file.indexOf("\n", pos) + 1;
        pos = file.indexOf("\n", pos) + 1;
        pos = file.indexOf("\n", pos) + 1;
        int boundaryLocation = file.indexOf(boundary, pos) - 4;
        int startPos = ((file.substring(0, pos)).getBytes()).length;
        int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;
        // saveFile = "C:/" + saveFile;
        File f = new File(saveFile);
        FileOutputStream fileOut = new FileOutputStream(f);
        fileOut.write(dataBytes, startPos, (endPos - startPos));
        fileOut.flush();
        fileOut.close();
/scripletI hope that will help you alot ...... any issue plz ask ............

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

Now there is an other solution for you .... and i recommand you to use that ......

JSP NAME:

index.jsp

<html>
<head><title>Upload page</title></head></p> <p><body>
<form action="employee_upload_profile_image.jsp" method="post" enctype="multipart/form-data" name="form1" id="form1">
<center>
<table border="2">
<tr>
<td align="right"><b>Employee Name:</td>
<input type="text" name="emp_name">
</tr>
<tr>
<td align="right"><b>Employee Address:</td>
<input type="text" name="address1">

</tr>
<tr>
<td>
</td>
<td>
<input type="text" name="address2">
</td>
</tr>
<tr>
<td align="right"><b>Contact Number:</td>
<input type="text" name="contact_number">
</tr>
<tr>
<td align="right"><b>Employee Email ID:</td>
<input type="text" name="email_id">
</tr>

<tr>
<td align="right"><b>Employee Image </td>
<td>
<input name="file" type="file" id="file">
<td>
</tr>

<tr>
<td align="center">
<input type="submit" name="Submit" value="Submit"/>
<input type="reset" name="Reset" value="Reset"/>

</td>
</tr>
</table>
</center>
</form>
</body>
</html>

=================================

JSP NAME:

employee_upload_profile_image.jsp

<%@ page import="java.util.List" %>
<%@ page import="java.util.Iterator" %>
<%@ page import="java.io.File" %>
<%@ page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
<%@ page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
<%@ page import="org.apache.commons.fileupload.*"%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<center><h1>Your  Profile has been Uploaded</h1></center>
<%    String emp_name = "";
int count1 = 0;

boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (!isMultipart) {
} else {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List items = null;
try {
items = upload.parseRequest(request);
} catch (FileUploadException e) {
e.printStackTrace();
}
Iterator itr = items.iterator();
while (itr.hasNext()) {
FileItem item = (FileItem) itr.next();
if (item.isFormField()) {
String name = item.getFieldName();
String value = item.getString();
if (name.equals("emp_name")) {
emp_name = value;
count1 = 1;
}
} else {
try {
String itemName = item.getName();
File savedFile = new File("D:/" + itemName);
item.write(savedFile);
if (count1 == 1) {
out.println("<tr><td align='left'><b>Name:</td><td><b>" + emp_name);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
%>
</td></tr></table></center>

and two jars

commons-fileupload-1.2.2.jar

commons-io-2.4.jar

 

About these ads
Comments
  1. Very interesting article, thanks for posting this information!

  2. Reyaz says:

    Man… you saved me a lot of trouble trying to figure out how to parse the MIME request data. Thanks.

  3. Dileep N says:

    Hii
    I am facing one problem here.
    In my jsp, I mentioned as below.

    and submitting the page as follows…
    if(count == 1)
    {
    if(!dirty || confirm(“”))
    {
    document.adminProductTypeForm.action=”product_types_detail_start.do?selectedSubCategoryId=”+selectedId+”&timeWindowsEnabled=”+timeWindowsEnabled;
    document.adminProductTypeForm.submit();
    }
    }
    else
    {
    if(!dirty || confirm(“”))
    {
    document.adminProductTypeForm.action=”admin_product_type_item_level.do”;
    document.adminProductTypeForm.submit();
    }
    }

    And while submitting this page its navigate to AdminProductTypeDetailStartAction class as per the below configuration in struts-config.xml

    And in the action class,

    protected ActionForward doPerform(ActionMapping mapping, ActionForm actionForm,
    HttpServletRequest request, HttpServletResponse response) throws SystemException,
    BusinessException
    {
    AdminProductTypeDetailForm form = (AdminProductTypeDetailForm) actionForm;

    AdminProductTypeForm productTypeForm = (AdminProductTypeForm) request.getSession()
    .getAttribute(“adminProductTypeForm”);
    AdminProductType adminProductType = productTypeForm.getAdminProductType();

    form.setSelectedManagerTypeDescription(adminProductType.getManagerType().getDescription());
    form.setSelectedSubCategoryIds(productTypeForm.getSubCategoryIdsToRemove());
    productTypeForm.setSelectedSubCategory(form.getSelectedSubCategory());

    And I am not getting the values for the above 3 statements…
    I kindly request you to help me…Please do the needful

    Kind Regards
    Dileep

  4. Dileep N says:

    Sorry to bother u…
    Please see my jsp page below..
    Unfortunately I couldnt figure out the issue..I am still working to figuring it out. Meanwhile please provide me ur suggestions/thought on this.
    Thank u very mnuch for ur support

    var page = “”;

    var dirty=

    var extractEnabled=

    function handleSave()
    {
    if (!dirty || confirm(“”))
    {
    document.adminProductTypeForm.action=”admin_product_type_save.do”;
    document.adminProductTypeForm.submit();
    }
    }

    function handleExportAll()
    {
    document.adminProductTypeForm.action=”admin_product_type_export_all.do”;
    document.adminProductTypeForm.submit();
    }

    function handleDone()
    {
    if (!dirty || confirm(“”))
    {
    document.adminProductTypeForm.action=”admin_product_type_done.do”;
    document.adminProductTypeForm.submit();
    }
    }

    function handleCancel()
    {
    if(!dirty || confirm(“”))
    {
    document.location=”admin.do”;
    }
    }

    function handleManagerType(field)
    {
    if(field.value != “” && document.adminProductTypeForm.selectedFunction.value != “”)
    {
    document.adminProductTypeForm.action=”admin_product_type_manager_type_select.do”;
    document.adminProductTypeForm.submit();
    }
    }

    function handleFunctions(field)
    {
    if(field.value != “” && document.adminProductTypeForm.selectedManagerType.value != “”)
    {
    document.adminProductTypeForm.action=”admin_product_type_manager_type_select.do”;
    document.adminProductTypeForm.submit();
    }
    else if(field.value != “”)
    {
    document.adminProductTypeForm.action=”admin_product_type_functionality_select.do”;
    document.adminProductTypeForm.submit();
    }
    }

    function handleItemLevel()
    {
    //alert(“Item Level temporarily not available”);
    //return;
    var timeWindowsEnabled = document.adminProductTypeForm.timeWindowsEnabled.checked
    var subCategoryList = document.adminProductTypeForm.subCategoryIdsToRemove;
    var count = 0;
    var selectedId;
    if(subCategoryList.options.length == 0)
    {
    alert(“”);
    }
    else
    {
    for(var i=0; i 1)
    {
    break;
    }
    }
    if(count == 0)
    {
    alert(“”);
    }
    else if(count == 1)
    {
    if(!dirty || confirm(“”))
    {
    document.adminProductTypeForm.action=”product_types_detail_start.do?selectedSubCategoryId=”+selectedId+”&timeWindowsEnabled=”+timeWindowsEnabled;
    document.adminProductTypeForm.submit();
    }
    }
    else
    {
    if(!dirty || confirm(“”))
    {
    document.adminProductTypeForm.action=”admin_product_type_item_level.do”;
    document.adminProductTypeForm.submit();
    }
    }
    }
    deselectSelections(subCategoryList);
    deselectSelections(document.adminProductTypeForm.subCategoryIdsToAdd);
    }

    function handleAddAllSubCategories()
    {
    document.adminProductTypeForm.action = “admin_product_type_subcategories_select_add_all.do”;
    document.adminProductTypeForm.submit();
    }
    function handleRemoveAllSubCategories()
    {
    document.adminProductTypeForm.action = “admin_product_type_subcategories_select_remove_all.do”;
    document.adminProductTypeForm.submit();
    }
    function handleAddSubCategories()
    {
    document.adminProductTypeForm.action = “admin_product_type_subcategories_select_add.do”;
    document.adminProductTypeForm.submit();
    }
    function handleRemoveSubCategories()
    {
    document.adminProductTypeForm.action = “admin_product_type_subcategories_select_remove.do”;
    document.adminProductTypeForm.submit();
    }

    function deselectSelections(subCategoryList)
    {
    for(var i=0; i<subCategoryList.length; i++)
    {
    subCategoryList.options[i].selected=false;
    }
    }

    function setFocus()
    {
    document.adminProductTypeForm.done.focus();
    }

    function handleRollbackLastChange()
    {
    document.adminProductTypeForm.action = "admin_product_type_rollback_upload_action.do"
    document.adminProductTypeForm.submit();
    }

    function handleExtract()
    {
    if(document.adminProductTypeForm.selectedFunction.value != "")
    {
    document.adminProductTypeForm.action = "admin_product_type_extract.do";
    document.adminProductTypeForm.submit();
    }
    else
    {
    alert("”);
    }

    }

    function handleUploadFile(obj)
    {
    document.adminProductTypeForm.action = “admin_product_type_upload_file.do”;
    document.adminProductTypeForm.submit();
    }

    <rss:message key='adminproducttypes.storelevel' arg0='’/>

    <html:button property="extract" disabled="” onclick=”handleExtract()”>

    <!–:–>Upload CSV: <html:file property="uploadFile" value="Upload CSV" size="45" disabled="” onchange=”handleUploadFile(this)” accept=”text/csv”/>

    <html:select property="selectedFunction" style="width:200px" disabled="” onchange=”handleFunctions(this);”>

    <html:select property="selectedManagerType" style="width:200px" onchange="handleManagerType(this);" disabled="”>

     

  5. Dileep N says:

    Not able to copy the page content..
    Highly appreciated ur help..

  6. Dileep N says:

    Upload CSV: <html:file property="uploadFile" value="Upload CSV" size="45" disabled="” onchange=”handleUploadFile(this)” accept=”text/csv”/>

  7. Prem says:

    hi, I have a jsp page and some input text field and some file type input.I want to send the path of the input type=”file” to my servlet and retrieve there the full path.The storing and retrieving logic is working file but geting the full path is sseems to be the toughest work here.It works fine in IE but doesn’t returning proper absolute path in Firefoz or chrome.I know it can be due to security concern but give me a solution for this if possible.

  8. shriks says:

    In Servlet 3.0 it is quite easy for fileupload. The HTML page is same as give above. HttpServletRequest has methods to read the “file” thru getPart(“file”) and to save using write(“filename”). web.xml has to be tagged with tag.
    For more info http://docs.oracle.com/javaee/6/api/index.html?javax/servlet/annotation/MultipartConfig.html

  9. Fiza Ahmad says:

    The last solution is working well for me..Thanks a lot bro!!! got stuck for few days..now can release my breath…hmmm…:)

  10. loans says:

    I’m curious to find out what blog platform you have been using? I’m
    experiencing some small security problems with my latest website and I’d like to find something more secure. Do you have any recommendations?

    Discount coupons can deliver severe price savings if you use them appropriately. You just need to learn how to employ coupons to improve your savings. With all the principles over, it is possible to become nicely skilled in couponing.

  11. Somu says:

    Hi,
    I am a beginner learning jsp. I have a form in one jsp page which also has a next button onclick of which next page should be loaded. My problem is how can we save the data entered in the form on the first page and the submit action in the second page should submit all the data (both first and second page data). Please help.

  12. FAROOQ says:

    very nice .. thank u

  13. Priyank Rastogi says:

    thanx jeeshan it is really very helpfull

  14. Rajat Singhvi says:

    sir can u explain the code for send a image from one jsp page to another with the help of database….like we click on a single image among multiple in flipcart and get that image on next page with description like price etc…….highly appreciated your help…

  15. Vinod Pathak says:

    org.apache.catalina.core.StandardWrapperValve invoke
    SEVERE: Servlet.service() for servlet [jsp] in context with path [/multipart_form-data] threw exception [An exception occurred processing JSP page /employee_upload_profile_image.jsp at line 41

    38: List items = null;
    39: try
    40: {
    41: items = upload.parseRequest(request);
    42: }
    43: catch(Exception e)
    44: {

    Stacktrace:] with root cause
    java.lang.ClassNotFoundException: org.apache.commons.io.output.DeferredFileOutputStream
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1714)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1559)
    at org.apache.commons.fileupload.disk.DiskFileItemFactory.createItem(DiskFileItemFactory.java:199)
    at org.apache.commons.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:361)
    at org.apache.commons.fileupload.servlet.ServletFileUpload.parseRequest(ServletFileUpload.java:126)
    at org.apache.jsp.employee_005fupload_005fprofile_005fimage_jsp._jspService(employee_005fupload_005fprofile_005fimage_jsp.java:104)
    at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:724)

    • java.lang.ClassNotFoundException: org.apache.commons.io.output.DeferredFileOutputStream

      Solution

      By default, Struts is using Apache “commons-io.jar” for its file upload process. To fix it, you have to include this library into your project dependency library folder.
      1. Get Directly

      Get “commons-io.jar” from official website – http://commons.apache.org/io/
      2. Get From Maven

      The prefer way is get the “commons-io.jar” from Maven repository

      File : pom.xml

      commons-io
      commons-io
      1.4

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s