How can i upload file using ajax post request and jsp

Hi
this is my code files
addPhoto.jsp
<html>
<head>
<title>Add Photo</title>
<script>
var optionNo = 0;
var i=1;
var val=0;
var file = 0;
var exten = new Array(".jpg",".jpeg",".gif");
function addValues()
     for(var i=0;i<5;i++)
          optionNo += 1;
          oNewOption = new Option();
          oNewOption.text = optionNo;
          oNewOption.value = optionNo;
          addSelect.add(oNewOption);
function addBoxes()
     var str = "";
     var j=0;
     val = document.getElementById('addSelect').value;
     for(j=1; j<= val; j++)
          str = str + '<font size=3>file:' + j + '</font>';
          str = str + '<input type="file" id=filepath'+ j +' name=file'+ j + ' onchange="uploadFile(hidden'+ j + '.value)"><div id="result'+ j +'"></div>
          str = str + '<input type="hidden" name="hidden' + j + '" value=' + j +'>';
     document.getElementById('addPhoto').innerHTML = str;
function uploadFile(value)
var str = "filepath" + value;
file = value;
var param = document.getElementById(str).value;
var parameter = "filepath=" + param;
alert(parameter.length);
if(checkValidity(param))
var url = "uploadFile.jsp";
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
req.open("POST", url, true);
req.setRequestHeader("Content-type", "multipart/form-data");
//req.setRequestHeader("Content-length", parameter.length);
req.setRequestHeader("Connection", "close");
req.onreadystatechange = callback;
req.send(null);
     else
          document.getElementById("result" + file).innerHTML = "upload .jpeg,.jpg,.gif Files Only";
function callback() {
if (req.readyState == 4) {
updatepage(req.responseText);
function updatepage(str){
     document.getElementById("result" + file).innerHTML = str;
function checkValidity(str)
     var i=0;
     var j=0;
     var str1 = str.substring(str.lastIndexOf("."),str.length);
     alert(str1);
     for(i=0;i<exten.length;i++)
     if(str1.search(exten) != -1)
          j++;
          break;
     if(j>0)
          return true;
     else
          return false;
</script>
</head>
<body onload="addValues()">
<h5>Add Photo(s)</h5>
<select id="addSelect" name="addSelect" onchange="addBoxes()">
<option id="select" selected>Select</option>
</select>
<div id="addPhoto"></div>
</body>
</html>
uploadFile.jsp
<%@page import="java.io.*"%>
<%
/*try
String contentType = request.getContentType();
     System.out.println(request.getMethod());
     System.out.println("Content type is :: " +contentType); 
     if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0))
          DataInputStream in = new DataInputStream(request.getInputStream());
          DataInputStream in1 = in;
          int formDataLength = request.getContentLength();
System.out.println(formDataLength);
          byte dataBytes[] = new byte[formDataLength];
          int byteRead = 0;
          int totalBytesRead = 0;
          while (totalBytesRead < formDataLength)
               byteRead = in1.read(dataBytes, totalBytesRead, formDataLength);
               totalBytesRead += byteRead;
          out.println("<br>totalBytesRead : " + totalBytesRead + " : formDataLength = " + formDataLength);
     } catch(Exception e) {
          e.printStackTrace();
     try
     String filePath = request.getParameter("filepath");
     System.out.println(filePath);
     File f= new File(filePath);
     String path = f.getName();
     String contentType = request.getContentType();
     System.out.println(contentType);
     //InputStream in = new FileInputStream(filePath);
     DataInputStream in = new DataInputStream(request.getInputStream());
     int formDataLength = request.getContentLength();
     System.out.println(formDataLength);
byte[] buf = new byte[1024];
OutputStream out1 = new FileOutputStream("c:/docs/" + path);
int len;
while ((len = in.read(buf)) > 0) {
out1.write(buf, 0, len);
in.close();
out1.close();
     out.write("File Uploaded SucssesFully");
catch(Exception e)
     e.printStackTrace();
     out.write("error while Writing File");
%>
the above code in request.getContentType() i am getting 0. I am not passing the content length. for the same application with out using Ajax i am
getting the size of file... it is very very urgent for me.. pls help me out on this...
Any one having the code on this pls mail me the code...
my mail id ... [email protected]
Regards
Ashok Kumar

Sure, you can upload a file, using a form input element of type file. You pick this up with a servlet, though you need a special request wrapper to sort out the multi-part request you get back that way (there's a suitable package on jakarta.apache.org/commons)
The servlet decrypts the file and can pass the results to a JSP for display.
Don't try to do the complicated stuff in a JSP, it all gets incredibly messy, and that's not what JSPs are for.

Similar Messages

  • How can i upload files in servlets and also using jsp

    means that uploading files(.doc) or any files by using servlets and jsps

    yawmark wrote:
    saichand wrote:
    means that uploading files(.doc) or any files by using servlets and jsps
    [http://www.google.com/search?q=How+can+i+upload+files+in+servlets+and+also+using+jsp]
    ~Good topic titles are indeed brilliant search keywords. It's sad to see that it won't even come in the mind of the topicstarters to Google it before posting the topic.

  • How can i upload files from one ip address to another  ip address machine ?

    how can i upload files from one ip address to another ip address machine ?

    i need to copy files from one client m/c to server m/c like sftp
    please suggest solution on this

  • In KE13N How can I Upload files

    In KE13N How can I Upload files ? , Other than file should be in which format?

    Hi
    You need to first save file description from the planning layout.
    You need to go to transaction KEPM open the planning method. It will open in excel format provided you layout is excel integrated . In the menu there will be a option to format setting do this, save the excel sheet in the desktop.
    Once you do format settings and there will be a menu appearing as save file description click on this. After this you can update the excel file downloaded to your desktop and upload through transaction KE13N.
    Anand

  • I have a G4 Quicksilver that no longer works, but the hd may still be good. How can I get files off the G4 hd and onto my new iMac?

    I have a G4 Quicksilver 2001 that no longer works, but the hd may still be good. How can I get files off the G4 hd and onto my new late 2013 iMac?

    Also, how do I boot the G4 into FireWire Target Disk mode?
    First, the G4 must be able to start to use FWTDM. If it can start, hold the t key at boot until you get a "screensaver pattern" that looks like this:
    If the G4 is attached via a FireWire cable to a newer Mac with a FireWire port, the G4's hard drive will appear on the other Mac's desktop just as if it were any external drive. A USB cable won't work for FWTDM.
    Just wondering if the drive in my G4, which I believe may be an ATA drive will also work in an enclosure for a SATA drive?
    No. ATA (actually "PATA" or "IDE") and SATA are different interfaces. PATA external enclosures are now very hard to find. You best and least expensive option is the adaptor that BDAqua linked. One of its connectors is for PATA drives.

  • How can we upload file into to OCS Content repository when we are in Apex

    We have installed the Oracle Application Express 2.2.1 into the OCS 10.1.2 database.
    The Apex authentication is set to operate with OCS SSO.
    We have made a form. There is a browse button on the form. We would like if the uploaded file appeared in the OCS content database repository as
    opposed to Apex document repository.
    To put it into another word, how can we upload the file into to OCS Content repository when we are in Apex.
    Generally speaking, how can we reach content from Apex?
    We have found many java based examples to use content sdk, but how can we use them with Apex? We believe that
    content hasn't got plsql interface.
    i would highly appreciate it if you sent me a full example program.

    Hi Ram,
    Thanks for the reply
    We have a requirement to device a solution to upload the policy documents related to iProcurement
    I am planning to create an OA page to upload the content and planning to use the AOL function security to restrict the users those who can access this page .
    Is there any better way to implement the security?
    Is this approach feasible or is there any better way to approach this requirement?
    Thanks

  • How can I upload file in JSP portlet?

    Hello,
    How can I upload a local file in JSP portlet? What do I have to use and where can I found infromation about that?
    Does someone has experiance in uploading file?
    Thank you!
    Kristjan

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

  • How can i Upload Files from my Flex 2.0 Application?

    How can i do a Upload File funtionality with Flex 2.0? Do i
    have to make the component? How is the code in Flex/ Action Script
    to make this possible?. I'm new in this Flex world and it seems to
    me very interesting to make RIA's Applications; in fact i'm making
    a little Employees Application for my company and i'm trying this
    technology and of course i need the functionality that i asking
    for.
    Regards.
    Andres.

    I haven't tried this, but I believe what you could do is
    append
    requestHeaders to the urlrequest object that you pass into
    the file.upload()
    method. The requestHeaders is an array of name/value pairs
    that would be
    included with your post. At least in theory, I believe that
    shoudl work.
    Good luck.
    Phil
    "tantalo" <[email protected]> wrote in
    message
    news:e3q3mt$138$[email protected]..
    > Hi. Phil, how i commented in the forum the examples
    works ok, with a
    > little
    > changes to make a file Upload. Now i have another doubt,
    i need to make a
    > submit of a form with another fields and the file
    selected.
    >
    > I made a HHTP Service for that purpose with the tags
    Requests like:
    >
    > <mx:HTTPService id="empleadoRequest"
    > url="
    http://andresbarrios:8080/directorio/empleados/insertarEmpleado.jsp"
    > useProxy="false" method="POST">
    > <mx:request xmlns="">
    >
    <empresa>{empresa.selectedItem.data}</empresa>
    >
    <ubicacion>{ubicacion.selectedItem.data}</ubicacion>
    >
    <departamento>{departamento.selectedItem.data}</departamento>
    > <cedula>{cedula.text}</cedula>
    > <nombre>{nombre.text}</nombre>
    > <apellido>{apellido.text}</apellido>
    > <!--Falta Fecha de Nacimiento -->
    > <sexo>{sexo.selectedItem.data}</sexo>
    >
    <estado_civil>{estado_civil.selectedItem.data}</estado_civil>
    >
    <telefono_celular>{telefono_celular.text}</telefono_celular>
    > <extension>{extension.text}</extension>
    >
    <correo_electronico>{correo_electronico.text}</correo_electronico>
    > </mx:request>
    > </mx:HTTPService>
    > I have the global variable called "file" that contains
    the file selected.
    > I
    > want to send this file variable in the HHTPservice call
    EmpleadoRequest,
    > can i
    > do that with a Request tag like another field? or the
    only way is trougth:
    > file.upload(upload.cfm) ?;
    >
    > I want only make a one call to the server to submit the
    fields of the form
    > and
    > to upload the file at th e same time can you help me How
    can i do that?
    >
    > Thanks.
    >
    > Regards.
    >
    > Andres.
    >
    >
    >

  • HT201250 How can I restore files using Time Machine to a new external drive?

    I need to restore all the files on a failed hard drive—upwards of a terabyte of data. How can I instruct Time Machine to copy the files to a new external hard drive? Thanks!

    Hold down the option key and select
              Browse Other Backup Disks...
    from the Time Machine menu in the menu bar. The menu icon looks like a clock running backwards. If you don't have that menu, open the Time Machine preference pane and check the box marked
              Show Time Machine in menu bar

  • How can I add file attachment to my form and get the attachment by email?

    I'm using this code and it works fine, but I don't get the attachment file in the email. How can I add this to my code?
    HTML
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Untitled Document</title>
    <script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script>
    <script src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js" type="text/javascript"></script>
    <script type="text/javascript">// <![CDATA[
                  $(document).ready(function() {
                    $("#form1").validate({
                      rules: {
                        first: "required",// simple rule, converted to {required:true}
                        email: {// compound rule
                        required: true,
                        email: true
                      last: {
                        last: true
                      comment: {
                        required: true
                      messages: {
                        comment: "Please enter a comment."
    // ]]></script>
    <script type="text/javascript">// <![CDATA[
    function validate ()
              if (document.form1.first.value == "")
              alert("Please enter your First Name");
              document.form1.first.focus();
              document.form1.first.style.border="1px solid red";
              return false;
              else if (document.form1.last.value == "")
              alert("Please enter your Last Name");
              document.form1.last.focus();
              document.form1.last.style.border="1px solid red";
              return false;
              else if (document.form1.emailaddress.value == "")
              alert("Please enter your Email Address");
              document.form1.emailaddress.focus();
              document.form1.emailaddress.style.border="1px solid red";
              return false;
    function has_focus() {
        if(document.form1.first.value == "")
                                  document.form1.first.focus();
                                  document.form1.style.first.border="1px solid green";
    function set_focus(x)
              document.getElementById(x).style.border="1px solid #80CA75";
    function clear_focus(x)
              document.getElementById(x).style.border="1px solid #DBDFE6";
    // ]]></script>
    </head>
    <body>
    <p><span style="color: #666666; text-align: center; font-size: 13px;">Please complete this form if you have any technical issue.</span></p>
    <form id="form1" action="http://www.southsun.com/php/tech_issue.php" enctype="multipart/form-data" method="post">
    <table style="width: 850px; font-size: 15px; padding-left: 20px; text-align: center;" border="0">
    <tbody>
    <tr>
    <td style="text-align: left; padding-bottom: 20px;" colspan="2">
    <h2><span style="color: #666666;">Please complete this form if you have any technical issue.</span></h2>
    </td>
    </tr>
    <tr style="padding-top: 40px;">
    <td style="text-align: left;"><span style="color: #abaf6f;"><strong>First Name</strong>:*</span><input id="first1" name="first" type="text" />  <br /><br /> <span style="color: #abaf6f;"><strong>Last Name</strong>:*</span><input id="last1" name="last" type="text" /><br /><br /> <span style="color: #abaf6f; padding-right: 33px;"><strong>Email</strong>:</span><span style="color: #abaf6f;">*</span><input id="email1" name="email" type="text" /><br /><br /> <span style="color: #abaf6f;"><strong>Shipping Method:</strong><br /></span> <input name="shippingmethod" type="radio" value="prioritymail" /> Priority Mail                                                                 <input name="shippingmethod" type="radio" value="store" /> In Store Pick up <br /> <input name="shippingmethod" type="radio" value="ground" />  Ground                                                                       <input name="shippingmethod" type="radio" value="3day" /> 3 Day Select<br /><br /> <span style="color: #abaf6f;"><strong>Payment Method:</strong><br /></span> <input name="paymentmethod" type="radio" value="paypal" /> Paypal Method                                                       <input name="paymentmethod" type="radio" value="creditcard" /> Credit Card<br /> <strong><br /> <span style="color: #abaf6f;">If getting an error message, please explain the error:</span></strong><span style="color: #abaf6f;"> <br /></span> <textarea id="errormessage" cols="20" rows="2" name="errormessage"></textarea><br /><br /></td>
    <td style="border-left: 1px solid grey; padding-left: 40px; text-align: left;"><span style="color: #abaf6f;"><strong>If using Paypal, Were you redirected successfully?</strong><br /></span> <input name="paypalredirect" type="radio" value="yes" /> Yes                                                                 <input name="paypalredirect" type="radio" value="no" /> No<br /><br /> <span style="color: #abaf6f;"><strong>If using Credit Card, Did you get an error?</strong><br /></span> <input name="carderror" type="radio" value="yes" /> Yes                                                                  <input name="carderror" type="radio" value="no" /> No<br /><br /> <span style="color: #abaf6f;"><strong>What happened after clicking place order? </strong><br /></span> <textarea id="placeorder1" cols="20" rows="2" name="placeorder"></textarea><br /><br /> <span style="color: #abaf6f;"><strong>Comments</strong>: <br /></span> <textarea id="comments1" cols="20" rows="2" name="strcomments"></textarea><br /><br /> <span style="color: #abaf6f;"><strong>Attach PrintScreen</strong>: <br /></span> <input name="strresume" type="file" />
    <div style="height: 50px;"> </div>
    </td>
    </tr>
    <tr>
    <td style="padding-top: 20px;" colspan="2">( * ) indicates required fields</td>
    </tr>
    <tr>
    <td style="text-align: center; padding-top: 20px;" colspan="2"><input class="button" name="submit" type="submit" value="Submit" />                        <input class="button" name="reset" type="reset" value="Reset" /></td>
    </tr>
    </tbody>
    </table>
    </form>
    </body></html>
    PHP
    <?php
    echo $savestring;
    //--------------------------paramaters--------------------------
    // Subject of email sent to you.
    $subject = 'prueba con uploads';
    // Your email address. This is where the form information will be sent.
    $emailadd = '[email protected]';
    // Where to redirect after form is processed.
    $url = 'http://www.pch-graphicdesign.com';
    // Makes all fields required. If set to '1' no field can not be empty. If set to '0' any or all fields can be empty.
    $req = '0';
    $target_path = "http://www.pch-graphicdesign.com/php/uploads/";
    $target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
    $text = "Results from form:\n\n";
    $space = ' ';
    $line = '
    foreach ($_POST as $key => $value)
    if ($req == '1')
    if ($value == '')
    {echo "$key is empty";die;}
    $j = strlen($key);
    if ($j >= 20)
    {echo "Name of form element $key cannot be longer than 20 characters";die;}
    $j = 20 - $j;
    for ($i = 1; $i <= $j; $i++)
    {$space .= ' ';}
    $value = str_replace('\n', "$line", $value);
    $conc = "{$key}:$space{$value}$line";
    $text .= $conc;
    $space = ' ';
    mail($emailadd, $subject, $text, 'From: '.$emailadd.'');
    echo '<META HTTP-EQUIV=Refresh CONTENT="0; URL='.$url.'">';
    ?>

    Sending a file as an attachment to an email involves setting the correct MIME type and headers. There's a brief tutorial here: http://webcheatsheet.com/php/send_email_text_html_attachment.php.
    Also, you need to use the same name as in your form. In the script you have shown here, the name of the file field is strresume, but your processing script uses this: $_FILES['uploadedfile']['name']. It should be this: $_FILES['strresume']['name']

  • How can I convert files in Aperture to jpegs and keep the file large

    I want to upload files into istock photo and they must be as big as possible but in jpg format. I end up exporting tiny little things going from 8mb to 300kb. How can I do it? I even tried going into CS3 but that only allowed me to convert to tif. I would appreciate any help - especially if it is simple!

    Go to File >> Export >> Export Version(s)
    In the resulting dialog box you'll find a drop down called Export Preset with a list of presets. One of them is JPEG Original Size. That should do it for you.
    Also you can choose Edit at the bottom of the preset list and modify an existing preset or create a new custom preset.
    BTW: the reason you couldn't do it in Photoshop is that you need to convert it from 16bit to 8bit before you can save a JPEG. That command in Photoshop is under Image>>Mode.
    DLS

  • How can build help file for right to left and non english language

    hi erverybody, i have a big problem ,please help me
    i creat a c# appliction with vs.net2005 and i want to write
    help file for it .i need a software to creat help file for non
    english language(such as persian or arabic) and right to left
    support . i tried many helpware chm builder tools but each of them
    made a problem .i dont know what to do .what is the best solution
    for creating help files for right to left and non english languages
    how can i build my help file with f1 helping ability .thank u
    so much
    Text

    Hi Mr_Sia and welcome to the RH community.
    You could try looking at the HAT Matrix. This is a comparison
    of all the help tools around. Click
    here to go to it.
    RoboHelp itself, whilst it does support over 35 different languages
    does not support Persian or Arabic.

  • Can't upload files using webDAV

    hi guys. i have a bit of a frustrating problem. im trying to upload zip file (~50MB) to a file hosting site (in.solit.us specifically) and i'm using webDAV to do so. i have no problem connecting to and mounting the server, but whenever i try and add anything to the dav disk it give me the error:
    "you cannot copy some of the items to the destination because their names are too long or contain invalid characters for the destination."
    i freaking hate this error message, whenever i get it it is so unwarranted. my zip file is titled "one.zip"... so no the name isn't too long or any such thing. the compressed files inside this zip file are also of similar length and composition. when i try and upload anything, even a smaller (regularly named) doc file, finder gives me the same error. what's more, when i try and create a new folder within the dav drive the "new folder" icon pops up for a few seconds then immediately disappears. which is kind of funny because when i then try and create another new folder it names it "new folder 2" -- which then subsequently disappeared as well. last time something like this happened to me it was a problem with the disk automatically ejecting itself after a couple of seconds. this does not seem to be the case here, console reads:
    "Feb 11 18:55:45 localhost webdavd[1641]: /Volumes/dav mounted"
    and then, when i manually eject it:
    "Feb 11 19:15:17 localhost webdavd[1641]: /Volumes/dav unmounted"
    console does not lie.
    any help would be much appreciated

    Hi Bilinbaja,
    I am not sure if you are using FTP to upload the files, however this error can sometimes refer to a hardware issue. Please try to toggle the hardware acceleration by right clicking on a item using the flash plug in and selecting settings.
    Please let us know if this improves the performance as well as if this also happens on other computers, or if it still happens after you delete cache and cookies. Each browser has its own cache, Firefox's cache may also be longer. [[How to clear the Firefox cache]]
    Did this help? We look forward to your reply.

  • How can I move files using the title bar

    I am using Mountain Lion, latest release (10.8.4) and am wondering if there is some secret options which would allow me to move files by clicking on the title bar (of e.g. preview) and moving it to a directory.
    Unfortunately, I can only either create a link or copy the file. Moving seems to be deactivated, though I have learned from other forums posts that this was working under Tiger.
    Any advise would be greatly appreciated.
    Thanks,
    equi

    Depends on the application. iCloud-aware applications (Preview, Pages, etc) have the behavior you describe, and you can't move a file by dragging the thumbnail icon, but there is a small popup triangle to the right of the filename which contains the option "Move To" - you can then select your destination. It's not as seamless and dragging and dropping, though, I agree.
    Non-iCloud-aware apps, like Office 2011, still allow drag-to-move from the titlebar icon.
    Matt

  • How can I trasfer file using java program (from NT to Unix)

    Hi all,
    I want to transfer a text file from Windows NT to Unix machine inside the Java program.
    How should i do it.
    Thanks in advance.
    Regards
    Rajeev

    you have several options:
    - make your system administrator software install software on Unix and NT so that you can see a directory on the Unix machine from your NT machine, and just copy the file there
    - use FTP to put the file on the Unix machine
    Jesper

Maybe you are looking for

  • How can I control automatic print head cleaning every time my Officejet Pro 8500A Premium starts up?

    In general we really like our new Officejet, but we're very frustrated by the automated start up procedure.  Every time we turn it on it does a self check and then cleans the print heads.  It's bothersome for two reasons: 1) We want to print quickly,

  • Mail issues on macbook pro

    I recently got a macbook pro and was setting up my mail and when I set up my accounts I do not have access to the mail folders and mail will not delete.  I have an iPad and iPhone and my hotmail accounts when I delete on one device its gone on the ot

  • Query in selecting row wise information

    Hello All, Could you please help me in getting the row wise information for the Financial Reporting Studion Report? I have a report where the row information will be Revenue and Expenses. but the revenue and expenses should only carry for specific co

  • Creating a New Virtual CU in iw32

    Hello, When I try to create a new Virtual CU (VCU) in IW32 the characteristic fields are already populated with the characteristics of the previously created VCU. But when I save the VCU the characteristics aren't saved with it so when I went back in

  • Enum key word is available before JDK 1.5 or not

    i have a jar file which is having a package name with enum. now i am using JDK 1.5. so i am getting errors saying that enum is a keyword. i want to know, from which version onwards they have included.