Emulating HTTP POST for file upload with J2ME

I have search through a lot of site and couldn't find the actual code. I try to emulate below html with J2ME.
<form method="POST" enctype="multipart/form-data" action="Insert.asp">
<td>File :</td><td>
<input type="file" name="file" size="40"></td></tr>
<td> </td><td>
<input type="submit" value="Submit"></td></tr>
</form>
here is my code :
HttpConnection c = null;
InputStream is = null;
OutputStream os = null;
byte[] filecontent = file byte content ...
try {
c = (HttpConnection)Connector.open("http://xx.com/insert.asp");
c.setRequestMethod(HttpConnection.POST);
c.setRequestProperty("Content-Length", String.valueOf(cmg.length + 15));
c.setRequestProperty("Content-type","multipart/form-data");
os = c.openOutputStream();
os.write("file=c:\\abc.png".getBytes());
os.write(filecontent);
os.flush();
I can emulate form with text field and it work, but when it come to file upload, above code not working, I don't know what to put for the outputstream, filename ? content ? or both ? since the html only has one field that is the "file" field. The file is actually store in rms with filename abc.png, and I just put in the c:\ for the server as a dump path.

File upload is more complicated then that... you need multi-part MIME formatting.... But I have just the code...
http://forum.java.sun.com/thread.jspa?forumID=256&threadID=451245

Similar Messages

  • File Uploading with two command button

    Hi all,
    After a long I return back.
    I am having a JSP page with some mandatory fields and one attach document field.
    I am using JSF framework so for file upload i used the tag <t:inputfileupload>, for compulsion fields I used the attribute required = true.
    My problem is,
    If i attach the file and click attach button before filling mandatory fields the action method is not called. Only after filling the mandatory fields the action method is called. What may be the reason for this?
    Is there any example for file uploading with in form and it has two separate command buttons?

    DHURAI wrote:
    Hi all,
    After a long I return back.
    I am having a JSP page with some mandatory fields and one attach document field.
    I am using JSF framework so for file upload i used the tag <t:inputfileupload>, for compulsion fields I used the attribute required = true.
    My problem is,
    If i attach the file and click attach button before filling mandatory fields the action method is not called. Only after filling the mandatory fields the action method is called. What may be the reason for this?My guess: you get validation errors, but you don't have a <h:messages/> in your JSF page so you don't see the error yourself. If you check your log files it will most likely be mentioned there.

  • One  last try... emulating HTTP POST with applet

    I am trying emulate the HTTP POST method for file uploading using an applet. More specifically, I am trying to upload raw data to a PHP script by making the PHP script think it is receiving a file when in reality all it is receiving is a series of headers, some other necessary info, the data, and a closer. The PHP is then supposed to save the data into a file.
    I have looked at eight or ten threads, explanations, and sample code in this and other forums that deal with this exact same thing, some even specific to PHP, read various documents on and explanations of HTTP headers and so forth, corrected every code error and possible code error I could find, and tried a gazillion variations, but still can't get the PHP script to think that it is receiving a file.
    As far as I can tell, communication with the server is being established, the server is receiving info and sending responses back, the PHP script is defrinitely being activated to do its thing, but the PHP is not recognizing anything that looks like a file or even a file name to it.
    The following information may be relevant:
    The PHP works perfectly with real files uploaded from real HTML pages.
    The server uses Apache.
    The server has no Java support (shouldn't matter, but otherwise I would be using servlets at that end instead of PHP).
    the applet is in a signed jar, and is trying to store information in the same directory that it came from.
    I am using the Firefox browser (shouldn't matter?) .
    I am hoping that someone knowegeable about this can look at the code below and point our any errors. I've also included the response I get from the server, and the PHP code. If there are no obvious errors, can you think of anything else tthat might be going wrong besides the code itsef?
    Please don't suggest I try alternate means of doing this or grab some working code from somewhere. I may very well wind up doing that, but I'm a stubborn bastard and want to find out what the #^%R$($ is going wrong here!!!
    Here is the latest incarnation of the applet code: All it does is immediately try to send some text to the PHP script in such a way that the script thinks it is uploading text within a file. it also displays the responses it gets from the server, including what the PHP script sends back.
    import java.applet.Applet;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.net.*;
    public class test1 extends Applet{
    DataOutputStream osToServer;
    DataInputStream isFromServer;
    HttpURLConnection uc;
    String content = "This is a test upload";
    public void init(){
    try
    URL url = new URL( "http://www.mywebpage.com/handleapplet.php" );
    uc = (HttpURLConnection)url.openConnection();
    uc.setRequestMethod("POST");
    uc.setDoOutput(true);
    uc.setDoInput(true);
    uc.setUseCaches(false);
    uc.setAllowUserInteraction(false);
    uc.setRequestProperty("Connection", "Keep-Alive");
    //uc.setRequestProperty("HTTP_REFERER", "http://applet.getcodebase");
    uc.setRequestProperty("Content-Type","multipart/form-data; boundary=7d1234cf4353");
    uc.setRequestProperty( "Content-length", ( Integer.toString( content.length() ) ) );
    osToServer = new DataOutputStream(uc.getOutputStream());
    isFromServer = new DataInputStream(uc.getInputStream());
    catch(IOException e)
    System.out.println ("Error etc. etc.");
    return;
    try{
    osToServer.writeBytes("------------------------7d1234cf4353\r\nContent-Disposition: form-data; name=\"testfile\"; filename=\"C:testfile.txt\"\r\nContent-Type: text/plain\r\n\r\n");
    osToServer.writeBytes(content);
    osToServer.writeBytes("\r\n------------------------7d1234cf4353--\r\n");
    osToServer.flush();
    osToServer.close();
    catch (Exception e) {
    System.out.println(e);
    System.out.println("did not sucessfully connect or write to server");
    System.exit(0);
    }//end catch
    try{
    String fieldName="",fieldValue="";
    for ( int i=0; i<15; i++ )
    fieldName = uc.getHeaderFieldKey(i);
    System.out.print (" " + fieldName +": ");
    fieldValue = uc.getHeaderField(fieldName);
    System.out.println (fieldValue);
    }catch(Exception e){
    System.out.println ("Didn't get any headers");
         try{        
    String sIn = isFromServer.readLine();
                        for ( int j=0; j<20; j++ )
                             if(sIn!=null)
    System.out.println(sIn);
                             sIn = isFromServer.readLine();
    isFromServer.close();
    }catch(Exception e){
              e.printStackTrace();
    }//end AudioUp.java
    Here's the response I get back from the server:
    null: HTTP/1.1 200 OK
    Date: Sun, 03 Apr 2005 18:40:04 GMT
    Server: Apache
    Connection: close
    Transfer-Encoding: chunked
    Content-Type: text/html
    null: HTTP/1.1 200 OK
    null: HTTP/1.1 200 OK
    null: HTTP/1.1 200 OK
    null: HTTP/1.1 200 OK
    null: HTTP/1.1 200 OK
    null: HTTP/1.1 200 OK
    null: HTTP/1.1 200 OK
    null: HTTP/1.1 200 OK
    null: HTTP/1.1 200 OK
    <html>
    <head>
    <title>Handling uploaded files from an applet, etc.</title>
    </head>
    <body>
    No file was uploaded.
    </body>
    </html>
    The <html> and the "No file uploaded" message is simply what the PHP script sends back when it does not detect any uploaded file.
    Here is the PHP code on the server:
    <html>
    <head>
    <title>Handling uploaded files from an applet, etc.</title>
    </head>
    <body>
    <?php
    if ($testfile)
    print "The temporary name of the test file is: $testfile<br />";
    $uplfile=$testfile_name;
    $uplfile=trim($uplfile);
    print "The filename is: $uplfile<br />";
    if ($uplfile)
    copy ($testfile, "$testfile_name");
    unlink ($testfile);
    }else{
    print "No file was uploaded.";
    ?>
    </body>
    </html>

    xyz's sample code didn't work - PHP doesn't like the getallheaders line at all. I'm going back to the manual now.
    I had another thought. When I first started using PHP, I had problems with ordinary text field uploads from web pages because somewhere in the process, extra blank lines or spurious carriage returns were being inserted into the strings. For example, if I had a place where people could enter their name, password, and brief message, and tried to store the incoming strings in an array, I'd wind up with some thing like:
    name
    password
    brief message
    instead of:
    name
    password
    brief message
    Which played havoc when trying to read out information by counting lines.
    Anyway, the problem was solved by using the trim($string) function on all incoming strings, which I now do as a matter of course. I never could figure out why it was happening though.
    Do you think something like that could be happening here?? I mean, if spurious blank lines or carriage returns were being inserted where they shouldn't be, could that be screwing things up in this way? HTTP seems to insist on having new lines and blank lines inserted in just the right places.

  • URGENT! File Upload Utility or a Custom UI for File Upload is needed!

    Hi all,
    I'm trying to find or develop a file upload utility or custom user interface rather than editing and adding file type item to a page. There is a free portlet for file upload in Knowledge Exchange resources, but it is for 3.0.9 release. I'm using portal 9.0.2.
    I could not any sample about the new release. Also API such as wwsbr_api that is used to add item to content areas is out dated.
    I create a page with a region for "items". When "edit" page and try to add an "file" type item the generated url is sth like this;
    "http://host:7779/pls/portal/PORTAL.wwv_additem.selectitemtype****"
    After selecting item type as a simple file autogenerated url is sth. like ;
    "http://host:7779/pls/portal/PORTAL.wwv_add_wizard.edititem"
    I made search about these API but could not find anything (in PDK PL/SQL API help, too).
    I need this very urgent for a proof of consept study for a customer.
    Thanks in advance,
    Kind Regards,
    Yeliz Ucer
    Oracle Sales Consultant

    Answered your post on the General forum.
    Regards,
    Jerry
    PortalPM

  • Multiple File Upload With Metadata Using REST

    hi all
    I want to upload multiple files with metadata to document library using REST API. I am using this msdn article
    http://msdn.microsoft.com/en-us/library/office/dn769086(v=office.15).aspx for uploading file. I am able to upload single file to document library but it is not working for multiple file. when I select multiple file it is uploading last selected file. can
    anyone help with this. I am using office 365 environment.
    Thanks in advance

    Hi,
    According to your post, my understanding is that you wanted to use the REST to upload multiple files.
    Per my knowledge, the REST API is not supported for uploading multiple files via a single call.
    You can write your own loop to upload multiple files via an individual call.
    http://sharepoint.stackexchange.com/questions/108525/multiple-file-upload-with-metadata-using-rest/108532#108532
    More reference:
    http://sharepointfieldnotes.blogspot.com/2014/04/uploading-documents-and-setting.html
    http://www.shillier.com/archive/2013/03/26/uploading-files-in-sharepoint-2013-using-csom-and-rest.aspx
    Thanks & Regards,
    Jason
    Jason Guo
    TechNet Community Support

  • File upload with 'asp vb' backend

    Hello,
    I am trying to get file uploading with flex (flash buider) working. There are plenty of examples with a php backend, but i need the script for a 'asp vb' backend.
    I' ve tried lots of different approaches but can't get it right. Someone out there with a solution?
    Thanx!!

    Believe it or not I have to do this also.
    I have legacy ASP code that uses ASPUpload that I'd like to get working with my Flash CS5 and FlashBuilder Burrito front-ends.
    it's just multipart encoded.
    So, if you first test it with ASPUpload and a simple form, trying just FILE1 first, and it works with ASP backend then tackle the FlashBuilder side with some debugging.
    ASPUpload is still an extremely embedded component on tens of thousands if not more sites, and it was just updated, but I think the previous version just before this update, the one that's out there in code on so many sites, that is what Flash needs to work with.
    ASPUpload is doing its part, as it follows all the multipart encoded RFC rules and has worked for years.
    I'd love to join you in finding out what's going on here.
    This is a long-standing issue.
    I've done PHP also.  But again, enhancing an interface with FlashBuilder4 or Burrito, to integrate with working legacy code makes it hard when something is not working on the Flash side (it appears anyway) as ASPUpload form posts are extremely easy.

  • Can anyone recommend a free file uploader with progress bar?

    Can anyone recommend a free file uploader with progress bar?
    I have searched google but with no luck.
    Ideally it would be a DW extension but that might be wishing
    for too much.
    I would like a large file limit for video and multiple file
    extensions allowed.
    Thanks in advance

    Heya,
    Check out this due Waleed he has some nice tuts and here's
    a
    link
    to file upload with progress bar tutorial he has. Granted it
    looks like it's just an animated gif letting users know their file
    is uploading; if you want realtime upload information displayed for
    the user you're gonna have to look at something like Flash with the
    power of actionscript to achieve that result.
    Hope that helps!

  • BI IP --- Planning function for File Upload

    Hai All,
    In BI IP , When I am trying to load the data (text file) by using Planning function for File Upload. I am getting an error message When I am clicking on Update .
    Error Message : Inconsistent input parameter (parameter: <unknown>, value <unknown>).
    In Text file I am using Tab Separation for each value
    Anyone help me out.
    Thanks,
    Bhima

    Hi Bhima
    Try one of these; it should work:
    1. If you are on SP 14 you would need to upgrade to SP 15. It would work fine
    2. If not, then -
         a] apply note 1070655 - Termination msg CL_RSPLFR_CONTROLLER =>GET_READ_WRITE_PROVIDS
         b] Apply Correction Instruction 566059 [i.e: in Object - CL_RSPLFR_CONTROLLER GET_READ_WRITE_PROVIDS,
    delete the block: l_r_alvl = cl_rspls_alvl=>factory( i_aggrlevel = p_infoprov ).
    and insert block - l_r_alvl = cl_rspls_alvl=>factory( i_aggrlevel = i_infoprov ).
    Goodluck
    Srikanth

  • ALBPM 6.0 : The maximum size for file uploads has been exceeded.

    Hi,
    I use AquaLogic BPM Entreprise server to deploy my Process. When I try to publish a process on my server I get the following error:
    An unexpected error ocurred.
    The error's technical description is:
    "javax.servlet.jsp.JspException: null"
    Possible causes are:
    The maximum size for file uploads has been exceeded.
    If you are trying to publish an exported project you should publish it using the remote project option.
    If you are trying to upload the participant's photo you should choose a smaller one.
    An internal error has ocurred, please contact support attaching this page's source code.
    Has someone resolve it?
    Thank's.

    Hi,
    Sure you've figured this out by now, but when you get the "Maximum size for file uploads" error during publish consider:
    1. if your export project file is over 10mb, use "Remote Project" (instead of "Exported Project") as the publication source. That way when you select the remote project, you will point to ".fpr" directory of the project you are trying to publish.
    Most times your project is not on a network drive that the server has access to. If this is the case, upload the .exp file to the machine where the Process Administrator is running, then expand it in any directory (just unzip the file). Then, from the Process Administrator, use the option to publish a Remote Project by entering the path to the .fpr directory you just created when unzipping the project.
    2. Check to see if you have cataloged any jars and marked them as non-versionable. Most of the times the project size is big just because of the external jar files. So as a best practice, when you do a project export select the option "include only-versionable jars", that will get reduce the project size considerably (usually to Kb's). Of course you have to manually copy the Jar files to your Ext folder.
    hth,
    Dan

  • Why does the file Name for file attached with Annotations "Attach File" (paperclip) become Unknown when Comments are Published?

    Our company recently purchased Adobe Acrobat Pro XI for the purpose of using it for shared electronic reviews.  We are using Send for Shared Review created in Adobe Acrobat Pro XI, and all the Comment tools work as expectedexcept the paperclip in Annotations.
    When a Word or Excel or Image(png,jpeg) file is attached using the Annotations paperclip, the initiator can initially see and open it. But after Publish Comments is selected and the review file is closed, the file "Name" changes to "Unknown" (although the Description has the correct file name and extension).  The Modified information is Unknown, as is the Size and Compressed Size.
    When the review file is then re-opened, even the initiator cannot open the file, although:
    The file location is marked with the paperclip within the document.
    The file name is shown in the Comments List with the initiator's name.
    In the Attachments list (the paperclip beneath the Thumbnails and Bookmarks) the Name appears as Unknown, Description shows the file name, Modified is Unknown, Size is Unknown, and Compressed Size is Unknown.
    The file Name cannot be edited, although the file Description can be.
    We have followed the procedure described in the tutorials but cannot figure out how to troubleshoot this situation.  Since this feature was the reason for the purchase of Adobe Acrobat Pro IX, we would any help. Please don't leave out any basics since we are all new users.
    We have several people with Adobe Acrobat Pro XI and the rest have Adobe Reader XI and it is a Windows platform.  Can someone please give us some advice how to get this feature to work as described?

    FYI Rave,
    There are some other forum entries with this exact same issue...:
    Cannot Open Attachments in PDF
    Why does the file Name for file attached with Annotations "Attach File" (paperclip) become Unknown when Comments are Published?
    Can someone help us get the COMMENTS ATTACHMENT TOOL to work as described in Acrobat Pro XI?

  • Http post from an application with file attachment

    Hi ! I didn't know where else to post this message...
    I'm trying to make a HTTP POST from an application and upload a file with it. I have no problems with the posting, just that I haven't got any ideas how to get the file uploaded as well. I've been reading loads of examples regarding the topic, and searching older posts the forum here, without any help.
    Here's the method i'm using:
                   // open connections
                  URL url = new URL ("TheURL");
                   URLConnection urlConn = url.openConnection();
                              // We do input & output, without caching
                   urlConn.setDoInput (true);
                   urlConn.setDoOutput (true);
                   urlConn.setUseCaches (false);
                              // multipart/form-data because we want to upload a file
                     urlConn.setRequestProperty ("Content-Type", "multipart/form-data");
                  // Open output stream
                     DataOutputStream printout = new DataOutputStream (urlConn.getOutputStream ());
                  // Set the actual content
                     String content = "upfile=" + System.getProperty("user.dir") + "\\file.ext&";
                       content += "other_key-value_pairs";
                  // write the data to stream, and flush it.
                     printout.writeBytes (URLEncoder.encode(content));
                   printout.flush ();
                   printout.close ();
                   // Get the response.
                     DataInputStream input = new DataInputStream (urlConn.getInputStream());
                   FileOutputStream fos=new FileOutputStream("postto.txt");
                   String str;
                     BufferedReader bufr = new BufferedReader(new InputStreamReader(input));
                  // Write response to outputfile
                     while (null != ((str = bufr.readLine()))) {
                         if (str.length() >0) {
                         fos.write(str.getBytes());
                         fos.write(new String("\n").getBytes());
                   input.close ();Now, the response here I get from the url i'm posting to is "Failure, no data-file". I've tried many diff methods of writing the file to the stream, but always get the same result.
    I need to file attached like it would be when using a HTML form's <input type="file">.
    Please help ! This is getting really urgent !

    String content = "upfile=" + System.getProperty("user.dir") + "\\file.ext&";
    content += "other_key-value_pairs";
    printout.writeBytes (URLEncoder.encode(content));
    printout.flush ();
    printout.close ();Actually, what this does is create a request like:
    GET /path/to/file/script.language?upfile=/home/user/file.ext&other=params HTTP/1.1
    Content-Type: multipart/form-data
    -- And other HTTP params --
    The file is not actually appended to the request.
    I really don't know how Java handles the file upload, but you could do it by hand, like so:
    public static void doFileUpload(String url, String filename, Hashtable params) throws IOException {
        // Construct the request
        String boundary = "----------------------mUlTiPaRtBoUnDaRy";
        String request_head = "POST " + url + " HTTP/1.0\r\n" +
                                         "Content-type: multipart/form-data; boundary=" + boundary + "\r\n";
        String request_body = boundary + "\r\n\r\nContent-disposition: form-data; name=\"upload\"" +
                                         "\r\n\r\n";
        BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(filename)));
        int b = -1;
        while((b = in.read()) != -1) {
             request_body += (char)b;
        in.close();
        Enumeration keys = params.keys();
        while(keys.hasMoreElements()) {
            String key = keys.nextElement();
            requst_body += "\r\n" + boundary + "\r\n\r\nContent-type: form-data; name=\"key\"\r\n" +
                                    (String)params.get(key);
        request_body += "\r\n" + boundary + "--\r\n";
        int length = request_head.length() + request_body.length() + "Content-length: \r\n";
        String req_length = "Content-length: " + (length + new String("" + length).length()) + "\r\n";
        Socket socket = new Socket(url,80);
        PrintStream stream = socket.getOutputStream();
        stream.print(request_head + req_length + req_body);
        // And now an option to read the response, I will omit that...   
    }Note: I have not tested this code, just wrote it up out of memory. If it does not work, it will propably need some small fixes.
    Tuomas Rinta

  • File upload with DAD not working

    Hi all,
    I have an application which uses the file upload function, similar to the sample http://otn.oracle.com/products/database/htmldb/howtos/howto_file_upload.html
    During the development I was not using a DAD and it was working perfectly. Now I have changed the application to use a DAD and now the file upload fails with a HTTP 404 - File not found error
    [DAD_din]
    connect_string = deccasm01os.na.decoma.com:1521:DIN
    ;password =
    ;username =
    ;default_page =
    document_table = wwv_flow_file_objects$
    document_path = docs
    document_proc = wwv_flow_file_mgr.process_download
    ;upload_as_long_raw =
    ;upload_as_blob =
    ;name_prefix =
    ;always_describe =
    ;after_proc =
    ;before_proc =
    reuse = Yes
    ;connmax =
    ;pathalias =
    ;pathaliasproc =
    enablesso = No
    ;sncookiename =
    stateful = STATELESS_RESET
    ;custom_auth =
    response_array_size = 128
    ;exclusion_list =
    ;cgi_env_list =
    bind_bucket_widths = 32,128,1450,2048,4000
    bind_bucket_lengths = 4,20,100,400
    ;error_style =
    ;nls_lang =
    BTW, it is on HTMLDB v1.6 on 9iDB (9.2.0.4)
    thx

    Rob,
    The File Browse item type does not require upload table WWV_FLOW_FILE_OBJECTS$. The POST for the File Browse item type is intercepted by modplsql and is inserted into the Document Table as defined by the Database Access Descriptor.
    You could ultimately create your own DAD with your own Document Table. The Document Table would have to contain the minimum definition as described at:
    http://download-west.oracle.com/docs/cd/B14099_03/web.1012/b14010/concept.htm#i1005880
    This way, users of the application using the Basic Database Authenticated DAD would be uploading directly into your table and not the HTML DB one. A word of caution, though, is that you would never want to use this DAD with HTML DB development itself...you would need to use the DAD that specifies upload into WWV_FLOW_FILE_OBJECTS$ for HTML DB development.
    I hope this helps.
    Joel

  • Session tracking for File Upload Servlet

    Hey Friends,
    I am developing a File Upload servlet and I need your help in certain matters .I have taken the servlet code from java-edge.com and am modifying it to give custom behaviour.I have a main page for upload (form upload)(lets call it form 1).If the file to be uploaded already exists on the server then a page is generated by the server saying that file already exists.(form 2)Now it is here(in form 2) that I want to provide an extra button which when submitted would recall the same servlet /or maybe another one and would provide the user for overriding the existing file.
    Now as per the code I would set the Override flag to be false in the second form and false in the main form .
    Given the case that it is a form based uploading servlet how do I maintain the user session when going to the next form or how do i pass the variables of the first form into second form .
    I am also facing another problem that is how do i manage multiple file uploads at a time .This basic system allows only one file per upload .
    P.S If someone could also throw some light on how to use the com.oreilly servlet (the latest version) it would be lovely but for now I want to focus on developing the current one

    Hi Jocelyn,
    I want to apologize firstly for the delay in my response.
    I was seriously bogged down due to certain circumstances and so couldnt reply.Thanks a million for your prompt reply.I'll post the Html content here and you will find the servlet code as is at the following U.R.L
    http://www.java-edge.com/Viewcode.asp?Value=serv012
    Form1:
    <HTML>
    <HEAD>
    <TITLE> Upload </TITLE>
    </HEAD>
    <BODY >
    <h2>Upload Your File!</h2>
    <form ENCTYPE="multipart/form-data" action="http://localhost:8080/servlet/Upload" method=post>
    click <b> browse </b>to select the file <br>
    <b> File:</b>
    <input type="FILE" name="Filename" value="" MAXLENGTH=255 size=50><br>
    Click here to upload!<input type=submit value=Upload>
    <input type=hidden name=Directory value="G:/Workspace/Upload/">
    <input type=hidden name=SuccessPage value="G:/Workspace/successpage.html">
    <input type=hidden name="OverWrite" value="false">
    <input type=hidden name="OverWritePage" value="">
    </form>
    </BODY>
    </HTML>
    Form 2
    <HTML>
    <HEAD>
    <TITLE> Upload </TITLE>
    </HEAD>
    <BODY >
    <h2>Upload Your File!</h2>
    <form ENCTYPE="multipart/form-data" action="http://localhost:8080/servlet/Upload" method=post>
    click <b> browse </b>to select the file <br>
    <b> File:</b>
    <input type="FILE" name="Filename" value="" MAXLENGTH=255 size=50><br>
    Click here to upload!<input type=submit value=Upload>
    <input type=hidden name=Directory value="G:/Workspace/Upload/">
    <input type=hidden name=SuccessPage value="G:/Workspace/successpage.html">
    <input type=hidden name="OverWrite" value="true">
    <input type=hidden name="OverWritePage" value="G:/Workspace/overwritepage.html">
    </form>
    </BODY>
    </HTML>
    Now in Form 2 I would add another button which when clicked would prompt the user if he wishes to overwrite the page.
    I am also posting the servlet code although I am sure u would prefer reading the one on the site
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.*;
    public class Upload extends HttpServlet
    static final int Max = 102400;// max. size of the file can be 100K
    String path;// stores path
    String msg;// store message of success
    //init method is called when servlet is first loaded
    public void init(ServletConfig config)throws ServletException
    super.init(config);
    if(path == null)
    path = "G:/Workspace/Upload/";
    if(msg == null)
    msg = "File successfully uploaded. Check out!";
    public void doPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException
    ServletOutputStream sos = null;
    DataInputStream dis = null;
    FileOutputStream fos = null;
    try
    resp.setContentType("text/plain");// return type of response is being set as plain
    sos = resp.getOutputStream();// gets handle to the output stream
    catch(IOException e)
    System.out.println(e);
    return;
    try
    String contentType = req.getContentType();// gets client's content type that should be multipart/form-data
    if(contentType!=null && contentType.indexOf("multipart/form-data")!= -1)
         // gets handle to the input stream to get the file to be uploaded from client
         dis = new DataInputStream(req.getInputStream());
         // gets length of the content data
         int Length = req.getContentLength();
         if(Length>Max)// length of the content data is compared with max size set
         sos.println("sorry! file too large");
         sos.flush();
         return;
         //to store the contents of file in byte array
         byte arr[] = new byte[Length];
         int dataRead = 0;
         int totalData = 0;
         while(totalData <Length)
         dataRead = dis.read(arr,totalData,Length);
         totalData += dataRead;
         String data = new String(arr);//byte array converted to String
         arr = null;
         // gets boundary value
         int lastIndex = contentType.lastIndexOf("=");
         String boundary = contentType.substring(lastIndex+1,contentType.length());
         String dir = "";
         if(data.indexOf("name=Directory")>0)// the type ""Directory"" is searched in the web page
         dir = data.substring(data.indexOf("name=Directory"));
         //gets directory
         // the directory higher in the directory tree cannot be selected
         if(dir.indexOf("..")>0)
         sos.println("Error- the directory higher in the directory tree cannot be selected");
         return;
         String successPage="";
         if(data.indexOf("name=\"SuccessPage\"")>0)// the type ""SuccessPage"" is searched in the web page
         successPage =data.substring(data.indexOf("name=\"SuccessPage\""));
         // gets successpage
         String overWrite="";
         if(data.indexOf("name=\"OverWrite\"")>0)// the type ""Overwrite"" is searched in the web page
         overWrite =data.substring(data.indexOf("name=\"OverWrite\""));
         overWrite = overWrite.substring(overWrite.indexOf("\n")+1);
         overWrite = overWrite.substring(overWrite.indexOf("\n")+1);
         overWrite = overWrite.substring(0,overWrite.indexOf("\n")-1);//gets overwrite flag
         else
         //overWrite = "false";
         String overWritePage ="";
         if(data.indexOf("name=\"OverWritePage\"")>0)// the type ""OverwritePage"" is searched in the web page
         // ensures same file is not uploaded twice
         overWritePage =data.substring(data.indexOf("name=\"OverWritePage\""));
         overWritePage = overWritePage.substring(overWritePage.indexOf("\n")+1);
         overWritePage = overWritePage.substring(overWritePage.indexOf("\n")+1);
         overWritePage = overWritePage.substring(0,overWritePage.indexOf("\n")-1);// // gets overwritepage
         //gets upload file name
         String file =data.substring(data.indexOf("filename=\"")+10);
         file = file.substring(0,file.indexOf("\n"));
         file = file.substring(file.lastIndexOf("\\")+1,file.indexOf("\""));
         int position;//upload file's position
         position =data.indexOf("filename=\"");//find position of upload file section of request
         position =data.indexOf("\n",position)+1;//find position of content-disposition line
         position =data.indexOf("\n",position)+1;//find position of content-type line
         position =data.indexOf("\n",position)+1;//find position of blank line
         int location =data.indexOf(boundary,position)-4;//find position of next boundary marker
         data =data.substring(position,location);// uploaded file lies between position and location
         String fileName = new String(path + dir + file);// the complete path of uploadad file
         File check = new File(fileName);
    /*************************CASE OVERRIDE ************************************/
         //String overwrite=req.getParameter("OverWrite");
         if(check.exists())// checks for existence of file
              if(overWrite.equals("false"))
                        if(overWritePage.equals(""))
                        sos.println("Sorry ,file already exists");
                        //return;
                        else
                        //overWritePage="G:/Workspace/overwritepage.html";
                        fos = new FileOutputStream(fileName);
                        fos.write(data.getBytes(),0,data.length());
                        //resp.sendRedirect(overWritePage);
                        sos.println("File Overridden");
              //return;
         File checkDir = new File(path + dir);
         if(!checkDir.exists())//checks for existence of directory
         checkDir.mkdirs();
    fos = new FileOutputStream(fileName);
    fos.write(data.getBytes(),0,data.length());
    sos.println("File successfully uploaded");
    if(check.exists())
              if(overWrite.equals("true"))
                   fos = new FileOutputStream(fileName);
                   fos.write(data.getBytes(),0,data.length());
                   if(successPage.equals(""))
                   sos.println(msg);
                   sos.println("File successfully uploaded");// if success HTML page URL not received
                   else
                   successPage="G:/Workspace/successpage.html";
                   resp.sendRedirect(successPage);
         else// incase request is not multipart
         sos.println("Not multipart");
    }//END OF TRY BLOCK
    catch(Exception e)
              try
              System.out.println(e);
              sos.println("unexpected error");
              catch(Exception f)
              System.out.println(f);
    finally
              try
              fos.close();// file output stream closed
              catch(Exception f)
              System.out.println(f);
              try
              dis.close();// input stream to client closed
              catch(Exception f)
              System.out.println(f);
              try
              sos.close();// output stream to client closed
              catch(Exception f)
              System.out.println(f);
    }//END OF DOPOST METHOD
    } //END OF CLASS
    Jocelyn the above code may have tid bit errors which u could understand.But I hope u get the overall idea of whats going on

  • File upload with non-ascii name

    I'm designing a system that includes file-uploads. My problem is that any non-ascii chars in the filename are encoded strangely when saved. &auml; is encoded to a&#778; etc.
    I use Tomcat with the -Dfile.encoding="UTF-8" in the Catalina file. I get the same result despite method; my own implementation, apache commons or Javazoom's uploadBean. All the JSP charset parameters are set.
    Any ideas?

    Hi amitads,
    I'm sure u've used Java enough. Also, u must have learned about the \ (backslash) escape character ?
    So, if u want to include a string like a single quote, u can write \' and for a double quote u can write \".
    Try this ... I'm sure it will help.
    Keep me posted.
    Cheers !!
    Sherbir.

  • Javascript multiple file upload with progressbar does not work in firefox, please help

    I want to upload files using this javascript snipped as well as processing non file fields on the same form. This works beautiful in IE11, Chrome and Opera, but not in firefox (version 34).
    I fired the non file handler with the action attribute on the <form> like this:
    <form id="upload_form" enctype="multipart/form-data" method="POST" action="nonFile.php">
    and the javascript with:
    <input name="submit" type="submit" style="background: green" value="Submit" onclick="return uploadFiles()"/>
    When I change type="button" the file uploads work in FF but the I have no control over the non file fileds.
    Can someone gives me an indication of what is wrong?
    oXHR.upload.addEventListener("progress", function(e){
    var percent=(e.loaded/e.total) * 100;
    _(idProg).value = Math.round(percent);
    _(idstat).innerHTML = filename.name + " "+Math.round(percent)+"% --- Please Wait";
    }, false);
    // Upload finish, show the size of the file in Bytes, KBytes or MBytes
    oXHR.onreadystatechange = function(){
    if (oXHR.readyState == 4 && oXHR.status == 200){
    var iBytesTransfered = bytesToSize(filesize);
    _(idstat).innerHTML = filename.name + " Size: " + iBytesTransfered + " "+100+"%";
    _(idProg).value = 100;
    // Upload failed
    oXHR.addEventListener("error", function(e){
    _(idstat).innerHTML = "Upload Failed";
    }, false);
    // Upload aborted
    oXHR.addEventListener("abort", function(e){
    _(idstat).innerHTML = "Upload Aborted";
    }, false)

    <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0, 0,0" width="600" height="360">
    <param name=movie value="example.swf">
       <param name="allowScriptAccess" value="always" />
    <param name="quality" value="high">
    <param name="allowScript" value="opaque">
    <param name="wmode" value="opaque">
    <embed src="example.swf" quality="high" allowScriptAccess="always" pluginspage="http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=Shockwave Flash" type="application/x-shockwave-flash" width="600" height="360"></embed></object>

Maybe you are looking for