Multipart data

hi my problem is as follows. my application fetches data from a remote system in the form a html file and its attachments into the system. now it needs to output this data into a browser. how do i do this without storing this information locally

yes i need my requirement is that i have to store it locally but then it cannot be accessed directly. for example if i get a html document with 3 links. then my local system will have the html document stored locally with the 3 documents (to which the links point to) also stored locally. but the system that is going to be developed over this actually reads the html file and outputs it to the browser. now if the user clicks the link it does not point to a valid path. my question is how do i solve this problem, i thought of 2 solutions. just send a multipart response the first time or have a servlet that listens to the requests and send the output to the browser.

Similar Messages

  • Multipart data posting from Mobile

    I am absolutely new to Java. Have some experience with ASP.
    My requirment is:
    1. User grabs image from mobile camera
    2. The image is either discarded or using POST, sent to a server alongwith caption.
    How difficult is this using Java technology? What are the basic requirements for this. I am interested in IMode and WAP.
    TIA,
    Regards
    Vikram

    I want to know, if there is any chance to post data from a php page using curl to a java servlet and Specify the URL of the given servlet while posting the data.
    how to get those data in that servlet?As usual, the servlet container will execute doGet() method of the Servlet class in case of HTTP Get request OR doPost() method in case of HTTP Post request. You can retrieve the submitted data using HttpServletRequest#getParameter() method.

  • ALSB 2.5 - routing request containing multipart/form-data

    Hello,
    I'm having difficulty routing a request (multipart/data-form with 2 MIME sections) in a
    business service.
    First, I set up the "attachments" variables in a stage:
    <ctx:attachments>
    <ctx:attachment>
    <ctx:Content-Disposition>form-data; name="RI"; filename="RI"</ctx:Content-Disposition>
    <ctx:Content-Type>text/plain</ctx:Content-Type>
    <ctx:Content-ID>1146702408781_1</ctx:Content-ID>
    <ctx:body>
    <RI/>
    </ctx:body>
    </ctx:attachment>
    <ctx:attachment>
    <ctx:Content-Disposition>form-data; name="CI"; filename="CI"</ctx:Content-Disposition>
    <ctx:Content-Type>text/plain</ctx:Content-Type>
    <ctx:Content-ID>1146702408781_1</ctx:Content-ID>
    <ctx:body>
    <CI/>
    </ctx:body>
    </ctx:attachment>
    </ctx:attachments>
    then do node replacements of <RI/> and <CI/> in each
    <ctx:body> section.
    Then in the routing node,
    "Set Transport Headers" for "Outbound Request"
    [x] Pass all Headers through Pipeline
    Add Header
    [Content-Type] --> [Set Header to "multipart/form-data"]
    Then I used Ethereal (network protocol analyzer) to
    observe the raw packets that business service sent
    the request to the target service. It looked like
    the POST httprequest output by ALSB does not conform to
    the other posting programs that I have wrote in Python
    and Ruby. The target webservice rejects the request
    sent by ALSB, but accepts those sent by the Python/Ruby
    programs.
    Anyone here have any experience in how to set this up?
    Thanks
    Charles

    Hello,
    Make sure you construct the attachment variable properly as specified in the documentation:
    http://e-docs.bea.com/alsb/docs26/userguide/context.html#wp1052039
    Gregory Haardt
    ALSB Prg. Manager
    [email protected]

  • Message object returns SharedByteArrayInputStream instead of Multipart.

    Dear friends,
    I am using java Mail API v 1.3.1 to access POP3 server.
    I am getting problem while I try to read an RTF message from POP3 server.
    When I try to access the data through getContent() method on javax.mail.Message Object, it sometimes gives me correct result as a Multipart data, while sometimes, it returns an object of type com.sun.mail.util.SharedByteArrayInputStream.
    Although it returns SharedByteArrayInputStream object, when I invoke getContentType() on Message Object, it returns Multipart as correct.
    I think this is some problem with the JavaMail API.
    Going specifically, I use the POP server : ksc.th.com
    Waiting for reply,
    -> Maulik Soni.

    hi,
    I have the same Problem,too. But now, i have found the reason.
    the javamail jar delivers a file named 'mailcap' in the META-INF dir of the library jar with
    the following content:
    text/plain;;          x-java-content-handler=com.sun.mail.handlers.text_plain
    text/html;;          x-java-content-handler=com.sun.mail.handlers.text_html
    text/xml;;          x-java-content-handler=com.sun.mail.handlers.text_xml
    multipart/*;;          x-java-content-handler=com.sun.mail.handlers.multipart_mixed
    message/rfc822;;     x-java-content-handler=com.sun.mail.handlers.message_rfc822
    now while creating the default instance of MailcapCommandMap (activation framework),
    this class is searching the 'mailcap' file in the META-INF dir. if 'mailcap' is not found, the
    activation framework don't map these mimetyps.
    workaround:
    make sure, that the MailcapCommandMap can find the mailcap file in META-INF or in user.home dir
    or
    map manually (javax.activation.MailcapCommandMap):
    MailcapCommandMap map = (MailcapCommandMap)MailcapCommandMap.getDefaultCommandMap();
    map.addMailcap("text/plain;;x-java-content-handler=com.sun.mail.handlers.text_plain");
    map.addMailcap("text/html;;x-java-content-handler=com.sun.mail.handlers.text_html");
    map.addMailcap("text/xml;;x-java-content-handler=com.sun.mail.handlers.text_xml");
    map.addMailcap("multipart/*;;x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
    map.addMailcap("message/rfc822;;x-java-content-handler=com.sun.mail.handlers.message_rfc822");
    simple,
    if you known it.
    thx, bye.
    franz bartlechner

  • Error deploying PAR file from Developer Studio (NW04)

    Hello,
    i've got a problem while trying to deploy a PAR file from NW Developer Studio.
    The PAR Export function says
    "Unable to connect to the Portal",
    the portal itself gives the following response:
    "ERROR: Upload failed - exception caught: com.sapportals.portal.prt.runtime.PortalRuntimeException: Invalid content type submitted - no multipart data"
    Deploying the PAR file manually using the Administration Console (system administration tab) of the portal works fine, but why doesn't the PAR Export function of NWDS?
    Thanks in advance for any help!
    Regards,
    Jörg

    Hi Jörg,
    as a general advise, use the NWDS version corresponding to the Servers version, so in this case, upgrade (or better: install new) NWDS 2.0.14. The main reason is WebDynpro compatibility, but the deploy mechanism may need this too.
    At least, give it a try and report if you have success (or not).
    Hope it helps
    Detlev

  • PAR Upload Error from NWDS

    I'm unable to export a PAR file from NWDS to the Portal. I go into the com.sap.ep.connectionManager log and find the error captured there with the URL address that NWDS was attempting to connect to and drop it in a browser. This results in the following error message:
    ERROR: Upload failed - exception caught: com.sapportals.portal.prt.runtime.PortalRuntimeException: Invalid content type submitted - no multipart data
    Has anyone encountered this and has a solution?
    Thanks in advance!

    Thanks for the response, Yoav.
    There is not a problem with uploading the par file. I can enter Java Development-Tools-PRT Admin Console and use the Archive Uploader to store the par file in the PCD.
    This appears to be a problem with NWDS communicating with the portal and the way the file is presented for upload. I am using NWDS SP11 with EP 6 SP11 and PDK 6 SP9.
    Thanks again,
    Steve

  • Trying to Imitate the html POST  method with an applet

    I am trying to imitate the POST method with an applet, so that I can eventually send sound from a microphone to a PHP script which will store it in a file on a server. I am starting out by trying to post a simple line of text by making the PHP script think that it is receiving the text within a POST-ed file. The reason I am doing things this way is in part because I am, for the time being, limited to a shared server without any support for servlets or any other server side java.
    The code I am trying is based in part on an old thread found elsewhere in this forum, concerning sending data to a PHP file by imitating the POST method:
    link:
    http://forum.java.sun.com/thread.jspa?threadID=530399&messageID=2603608
    someone named "harmmeijer" provided most of the answers on that thread. If that person is still around hope they take a look at this,also I have some questions to clarify what they said on the other thread..
    My first attempt at code is below. The applet is in a signed jar file and is trying to pass a text line to the PHP script in the same directory and on the same server that the applet came from. It is doing this by sending header information that is supposed to be identical to what an html form would send if it was uploading a .txt file with the line of text within it. The applet displays one button. When you press it, it sucessfully starts up the postsim method (defined at the end), which is supposed to send the info to the PHP script at the server.
    I have two questions:
    1) I know that the PHP script is starting up, because it prints out a few messages depending on what happens. However, the script does not recognize any file coming down the line, so it does not save anyting on the server, and prints out a message saying the no file was uploaded.
    Any idea what might be going wrong? I'm not getting any error messages from the applet. I've tried a few different variations of the 'header' information contained in the line:
    osToServer.writeBytes("--****4353\r\nContent-Disposition: form-data; name=\"testfile\"; filename=\"C:testfile.txt\"\r\nContent-Type: text/plain\r\n");
    The commented out line below it shows one variation (which was given in the thread mentioned above).
    2) You'll notice that I've commented out the two lines having to do with the input line:
    //InputStream isFromServer;
    and
    //isFromServer = uc.getInputStream();
    The reason is that the program crahes whenever I put the latter line in - to the extent that Opera closes down the JVM and then crashes when I tried to exit it.. I must be doing something horribly wrong there! I first tried using isFromServer = new DataInputStream(uc.getInputStream());
    becuase it was consistent with the output stream, but that caused the same problem.
    Here's the code:
    public class AudioUptest1 extends Applet{
    //There are a few spurious things defined in this section, having to do with the fact the microphone data is evenuatly going to be sent. haven't yet insterted code to get input from a microphone.
    AudioFormat audioFormat;
    TargetDataLine targetDataLine;
    SourceDataLine sourceDataLine;
    DataOutputStream osToServer;
    //InputStream isFromServer;
    URLConnection uc;
    final JButton captureBtn = new JButton("Capture");
    final JPanel btnPanel = new JPanel();
    public void init(){
    System.out.println("Started the applet");
    try
    URL url = new URL( "http://www.mywebsite.com/handleapplet.php" );
    uc = url.openConnection();
    //Post multipart data
    uc.setDoOutput(true);
    uc.setDoInput(true);
    uc.setUseCaches(false);
    //set request headers
    uc.setRequestProperty("Connection", "Keep-Alive");
    uc.setRequestProperty("HTTP_REFERER", "http://applet.getcodebase");
    uc.setRequestProperty("Content-Type","multipart/form-data; boundary=****4353");
    osToServer = new DataOutputStream(uc.getOutputStream());
    //isFromServer = uc.getInputStream();
    catch(IOException e)
    System.out.println ("Error etc. etc.");
    return;
    //Start of GUI stuff
    captureBtn.setEnabled(true);
    //Register listeners
    captureBtn.addActionListener(
    new ActionListener(){
    public void actionPerformed(
    ActionEvent e){
    captureBtn.setEnabled(false);
    //Postsim method will send simulated POST to PHP script on server.
    postsim();
    }//end actionPerformed
    }//end ActionListener
    );//end addActionListener()
    add(captureBtn);
    add(btnPanel);
    // getContentPane().setLayout(new FlowLayout());
    // setDefaultCloseOperation(EXIT_ON_CLOSE);
    setSize(250,70);
    setVisible(true);
    }//end of GUI stuff, constructor.
    //These buffers might be made larger.
    byte tempOutBuffer[] = new byte[100];
    byte tempInBuffer[] = new byte[100];
    private void postsim(){
    System.out.println("Got to the postsim method");
    try{
    //******The next four lines are supposed to imitate a POST upload from a form******
    osToServer.writeBytes("--****4353\r\nContent-Disposition: form-data; name=\"testfile\"; filename=\"C:testfile.txt\"\r\nContent-Type: text/plain\r\n");
    //osToServer.writeBytes("Content-Disposition: form-data; name=\"testfile\"; filename=\"C:testfile.txt\"\r\nContent-Type: text/plain\r\n");
    //This is the text that's cupposed to be written into the file.
    osToServer.writeBytes("This is a test file");
    osToServer.writeBytes("--****4353--\r\n\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
    }//end method postsim
    }//end AudioUp.java

    Hi All,
    I was trying to write a signed applet that helps the
    user of the applet to browse the local hard disk and
    select a file from the same. The JFileChooser class
    from Swing is what I used in my applet. The problem
    is with the policy file. I am not able to trace the
    exact way to write a policy file which gives a total
    access to read,write,delete,execute on all the drives
    of the local hard disk.
    I am successful in signing the applets and performing
    operations : read,write,delete & execute on a single
    file but failing to grant permission for the entire
    file.
    Any help would be highly appreciated.Which policy file are you using? there might be more than one policy file.
    also, u have to specify the alias of the signed certificate in the policy file to grant the necessary priviledges to the signed applet.

  • "File Not Found" when addCourse through iTunesU web service.

    I have problem to add Course to my institute's iTunesU site through Web Service.
    I was able to get the xml doc back through showTree operation and here is part of it:
    <Site>
    <Name>my institute's name</Name>
    <Handle>123</Handle>
    <AggregateFileSize>63057465318</AggregateFileSize>
    <Section> <Name>Your Classes</Name>
    <Handle>456</Handle>
    <AggregateFileSize>57423912007</AggregateFileSize>
    <Course>
    <Name>course 1</Name>
    <Handle>111</Handle>
    </Course>
    </Section>
    <Section>
    I was able to get the uploadURL back too. The URL to get the uploadURL request:
    https://deimos.apple.com/WebObjects/Core.woa/API/GetUploadURL/myInstitute.edu.45 6?type=XMLControlFile
    The uploadURL I got back looks like:
    https://deimos2.apple.com/WebObjects/Files.woa/Upload/myInstitute.edu.456/X_1371095208_1a.43c06fa3.467dc4f2/%5Banonymous1371095208%5D/0046e71254900a071aa9241221a469d98ff1ef6fa973544c45ef9 5260dac6c64f05b10aefc
    But when I use the uploadURL above and post the addCourse.xml:
    <ITunesUDocument>
    <AddCourse>
    <ParentHandle>456</ParentHandle>
    <Course>
    <Name>Jing Test iTunesU Web service Course</Name>
    <ShortName>Jing Test</ShortName>
    </Course>
    </AddCourse>
    </ITunesUDocument>
    The response I got
    <error>File Not Found</error> File Not Found
    I used myInstitute.edu.456 to get the uploadURL and set it to ParentHandle on addCourse.xml since 456 is the section handler in whoch I want to add the course.
    I tried to remove 456 from the myInstitute.edu to get the uploadURL and then use it to add course, got the same error.
    Is there something wrong with the URL I used to get the uploadURL?
    here is the code and the values pass to the methodI used to send addCourse request:
    url = uploadURl on above
    name="file"
    fileName="file.xml";
    data=addCourse xml on above
    contentType="text/xml"
    public String invokeAction(String url,
    String name,
    String fileName,
    String data,
    String contentType) throws MessagingException {
    // Send a request to iTunes U and record the response.
    StringBuffer response = null;
    System.out.println("xml doc: ---" + data);
    try {
    // Verify that the communication will be over SSL.
    if (!url.startsWith("https")) {
    throw new MalformedURLException("ITunesUFilePOST.invokeAction(): URL \""
    + url + "\" does not use HTTPS.");
    // Build the multipart data.
    MimeMultipart multipart = new MimeMultipart();
    MultipartFormBuilder.addMultipartFormBody(multipart,
    name,
    fileName,
    data,
    contentType);
    // Create a connection to the requested iTunes U URL.
    HttpURLConnection connection =
    (HttpURLConnection) new URL(url).openConnection();
    connection.setUseCaches(false);
    connection.setDoOutput(true);
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type",
    "multipart/form-data; boundary="
    + MultipartFormBuilder.getMultipartBoundary(multipart));
    String multipartData = MultipartFormBuilder.getMultipartData(multipart);
    // Send the multipart data to iTunes U.
    connection.connect();
    OutputStream output = connection.getOutputStream();
    output.write(multipartData.getBytes("UTF-8"));
    output.flush();
    output.close();
    // Read iTunes U's response.
    response = new StringBuffer();
    InputStream input = connection.getInputStream();
    Reader reader = new InputStreamReader(input, "UTF-8");
    reader = new BufferedReader(reader);
    char[] buffer = new char[16 * 1024];
    for (int n = 0; n >= 0;) {
    n = reader.read(buffer, 0, buffer.length);
    if (n > 0) response.append(buffer, 0, n);
    // Clean up.
    input.close();
    connection.disconnect();
    } catch (UnsupportedEncodingException e) {
    // ITunes U requires UTF-8 and ASCII encoding support.
    throw new java.lang.AssertionError("ITunesUFilePOST.invokeAction(): UTF-8 encoding not supported!");
    } catch (IOException e) {
    // Report communication problems.
    throw new java.lang.AssertionError("ITunesUFilePOST.invokeAction(): I/O Exception " + e);
    // Return the response received from iTunes U.
    System.out.println("response from ITunesUFilePOST: " + response.toString());
    return response.toString();
    }

    I'm having a similar "File Not Found" error, but it's happening for any API request other than GetUploadURL. I'm sending a POST request to the GetUploadURL, and that part is working correctly, as I get a URL such as the following:
    https://deimos2.apple.com/WebObjects/Files.woa/Upload/wvu.edu/X_1372071795_4d9433be.4c3fdd3d.4c3fdd3e/%22Chris%20Scharf%22%20%3Ccbscharf%40mail.wvu.edu%3E%20%28cbscharf%29%20%5B3258 7%5D/0046eaaaf078cf5d6b60f18926106a50a5050cf8f9c91a7608074e6d2949a8759017969ece
    Then, I've tried using curl (within 90 seconds) to submit a simple XML document containing a ShowTree request:
    <?xml version="1.0" encoding="UTF-8"?>
    <ITunesUDocument>
    <ShowTree>
    <KeyGroup>most</KeyGroup>
    </ShowTree>
    </ITunesUDocument>
    The command executed is "curl -F file=test.xml URL" (where URL is the URL retrieved from GetUploadURL. But I simply get "<error>File Not Found</error>"
    I'm correctly sending credentials, since I'm getting upload URLs. And it's not an issue with the XML document, since it's not even getting to the server.

  • Download and Upload using applet

    hi everyone,
    i tried to develop an applet that can handle upload and download file from server to client and vice versa.
    is there anyone can help me?
    Please help.
    thank you for replies.

    You need to sign your applet and the user needs to trust this signature in order for the
    applet to read from the local filesystem and or connect to a server other than the one the
    applet came from.
    http://forum.java.sun.com/thread.jsp?forum=63&thread=524815
    second post
    Here is some code that will upload (both msjvm and sun jre) but I never really finished
    it. Note that if you use the applet with msjvm the client has to adjust java security in IE
    import java.awt.*;
    import java.net.*;
    import java.io.*;
    public class srvHead extends java.applet.Applet implements Runnable{
         String c = "";
         public srvHead(){
              new Thread(this).start();
         public void init(){
    //          new Thread(this).start();
         public void run(){
              try{
    // run this as an application first, when it works than make an applet of it
                   URL u = new URL("http://localhost:101/test");
                   URLConnection c = u.openConnection();
                   // post multipart data
                   c.setDoOutput(true);
                   c.setDoInput(true);
                   c.setUseCaches(false);
                   // set some request headers
                   c.setRequestProperty("Connection", "Keep-Alive");
    // TODO: get codebase of the this (the applet) to use for referer
                   c.setRequestProperty("HTTP_REFERER", "http://applet.getcodebase");
                   c.setRequestProperty("Content-Type", "multipart/form-data; boundary=****4353");
                   DataOutputStream dstream = new DataOutputStream(c.getOutputStream());
    // write content to the server, begin with the tag that says a content element is comming
                   dstream.writeBytes("--****4353\r\n");
    // discribe the content, (in this case it's a file)
                   dstream.writeBytes("Content-Disposition: form-data; name=\"myfile\"; filename=\"C:\\myFile.wav\"\r\nContent-Type: application/octet-stream\r\n\r\n");
    // open a file
                   String title = "Frame Title";
                   Frame frame = new Frame("Select a file");
                   FileDialog fd = new FileDialog(frame);
                   frame.setSize(400, 400);
                   fd.show();
                   System.out.println(fd.getDirectory() + fd.getFile());
                   File f = new File(fd.getDirectory() + fd.getFile());
                   FileInputStream fi = new FileInputStream(f);
    // keep reading 1000 bytes from the file
                   byte[] bt = new byte[1000];
                   int cnt = fi.read(bt);
                   while(cnt==bt.length){
                        dstream.write(bt,0,cnt);
                        cnt = fi.read(bt);
    // send the last bit to the server
                   dstream.write(bt,0,cnt);
    // now close the file and let the web server know this is the end of this form part
                   dstream.writeBytes("\r\n--****4353\r\n");
    // send a form part named TargetURL with the value: /IntranetContent/TelephoneGuide/Upload/
                   dstream.writeBytes("Content-Disposition: form-data; name=\"TargetURL\"\r\n\r\n");
                   dstream.writeBytes("/IntranetContent/TelephoneGuide/Upload/");
    // let the web server know this is the end of this form part
                   dstream.writeBytes("\r\n--****4353\r\n");
    // send a form part named redirectURL with the value: http://none/none
                   dstream.writeBytes("Content-Disposition: form-data; name=\"redirectURL\"\r\n\r\n");
                   dstream.writeBytes("http://none/none");
    // this is the last information part of the multi part request, close the request
    // close the multipart form request
                   dstream.writeBytes("\r\n--****4353--\r\n\r\n");
                   dstream.flush();
                   dstream.close();
                   fi.close();
                   try{
                        DataInputStream in =
                             new DataInputStream(
                                  new BufferedInputStream(c.getInputStream()));
                        String sIn = in.readLine();
                        boolean b = true;
    // TODO: this will loop forever unless you make sure your server page
    // sends a last line like "I am done"
    // than you can do wile(sIn.compareTo("I am done")!=0){
                        while(sIn!=null){
                             if(sIn!=null){
                                  System.out.println(sIn);
                             sIn = in.readLine();
                   }catch(Exception e){
                        e.printStackTrace();
              }catch(Exception e){
                   e.printStackTrace();
         public static void main(String[] args) {
                   new srvHead();
    }

  • DataOutputStream appears to be buffering and then overflowing?? 10 Duke Pts

    Hi folks,
    Hope someone can help. I am trying to put together a file upload applet (yes I know....security this and signing that and so on...). It "works" (erm...kind of) using the JFileChooser and JProgressMonitorInputStream to carry out an HTTP post to a server side CGI script.
    I have it "working" in so far as with small files it does actually complete although usually some time after the progress bar shows it completed.
    With larger files though the progress bar still rushes through too quickly but then it crashes with an OutOfMemory exception (at around 40MB).
    It looks to me almost as if the DataOutputStream is buffering and returning (not blocking) before the data has actually been sent. I have tried including a .flush() after the write but it made no difference.
    Why does the DataOutputStream return from write before the data has actually been sent?
    If anyone can help in any way it will be massively appreciated! I have included code below its not neat since I have been bashing it around trying to make it work.
    What I am looking for is to have the progress bar show the progress as the contents of the file is uploaded to the server via the HTTP post.
    package videoupload;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.net.*;
    import java.io.*;
    public class VideoUpload extends JApplet implements ActionListener
      class HTTPPoster extends SwingWorker {
        String sBoundary="2db8c22f75474a58cd13fa2d3425017015d392ce";
        URL u;
        public URLConnection postConnect(URL urlTarget)
          URLConnection c = null;
          try {
            c = urlTarget.openConnection();
            // post multipart data
            c.setDoOutput(true);
            c.setDoInput(true);
            c.setUseCaches(false);
          } catch (Exception ex)
             ex.printStackTrace();
          return c;
        public void postHeaders(URLConnection pCon)
          // set some request headers
          pCon.setRequestProperty("Connection", "Keep-Alive");
          pCon.setRequestProperty("HTTP_REFERER", "http://www.<THEWEBSITE>.com/");
          pCon.setRequestProperty("Content-Type",
                                  "multipart/form-data; boundary="+sBoundary);
        public DataOutputStream getFormBodyOutput(URLConnection pCon)
          DataOutputStream dos = null;
          try
            dos = new DataOutputStream(pCon.getOutputStream());
            sendBoundary(dos);
          } catch (Exception ex)
            ex.printStackTrace();
          return dos;
        public void sendBoundary(DataOutputStream dos)
          try
            dos.writeBytes("--"+sBoundary+"\r\n");
          } catch (Exception ex)
            ex.printStackTrace();
        public void postFile(DataOutputStream dos, String name, File f)
          try
            dos.writeBytes(
                "Content-Disposition: form-data; name=\"" + name +
                "\"; filename=\"" + f.getName() +
                "\"\r\nContent-Type: application/octet-stream\r\n\r\n");
            System.out.println("Opening - "+f.getAbsoluteFile());
            FileInputStream fis = new FileInputStream(f.getAbsoluteFile());
            ProgressMonitorInputStream pmis = new ProgressMonitorInputStream(
                content, f.getName(), fis);
            ProgressMonitor pm = pmis.getProgressMonitor();
            pm.setMillisToDecideToPopup(500);
            byte[] bt = new byte[1024];
            int cnt = pmis.read(bt);
            while (cnt == bt.length)
              dos.write(bt, 0, cnt);
              cnt = pmis.read(bt);
            // send the last bit to the server
            dos.write(bt, 0, cnt);
            // now close the file and let the web server know this is the end of this form part
            pmis.close();
            fis.close();
            sendBoundary(dos);
          } catch (Exception ex)
            ex.printStackTrace();
        public void endPost(DataOutputStream dos)
          try
            dos.writeBytes(
                "\r\n--" + sBoundary + "--\r\n\r\n");
            dos.flush();
            dos.close();
          } catch (Exception ex)
            ex.printStackTrace();
        public void getResponse(URLConnection pCon)
          try
            DataInputStream dis =
                new DataInputStream(
                    new BufferedInputStream(pCon.getInputStream()));
            String sIn = dis.readLine();
            while (sIn != null)
              if (sIn != null)
                System.out.println(sIn);
              sIn = dis.readLine();
          } catch (Exception ex)
            ex.printStackTrace();
        public Object construct()
          try
              u = new URL("http://www.<THEWEBSITE>.com/cgi-bin/upload.cgi");
              // System.out's here for debugging only...
              System.out.println("Connect");
              URLConnection pCon = postConnect(u);
              System.out.println("Send headers");
              postHeaders(pCon);
              System.out.println("Begin body");
              DataOutputStream dos = getFormBodyOutput(pCon);
              System.out.println("Send file");
              this.postFile(dos, "file", f);
              System.out.println("End body");
              endPost(dos);
              System.out.println("Get response");
              getResponse(pCon);
              System.out.println("Done");
            catch (Exception ex)
              ex.printStackTrace();
          return null;
      Container content;
      File f;
      protected boolean isStandalone = false;
      protected BorderLayout borderLayout1 = new BorderLayout();
      String uploadPath;
      //Get a parameter value
      public String getParameter(String key, String def)
        return isStandalone ? System.getProperty(key, def) :
            (getParameter(key) != null ? getParameter(key) : def);
      //Construct the applet
      public VideoUpload()
      //Initialize the applet
      public void init()
        try
          UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        catch (Exception e)
          System.err.println("Error setting native LAF: " + e);
        content = getContentPane();
        content.setBackground(Color.white);
        content.setLayout(new FlowLayout());
        // Come back to this later
        JTextField txtFileName = new JTextField();
        txtFileName.addActionListener(this);
        content.add(txtFileName);
        JButton btnUpload = new JButton("Upload");
        btnUpload.setMnemonic('u');
        btnUpload.addActionListener(this);
        content.add(btnUpload);
        //Create a file chooser
        final JFileChooser fc = new JFileChooser();
        int returnVal = fc.showOpenDialog(content);
        f=fc.getSelectedFile();
        try
          uploadPath = this.getParameter("uploadPath", "/");
        catch (Exception e)
          e.printStackTrace();
      public void actionPerformed(ActionEvent e){
        HTTPPoster worker = new HTTPPoster();
        worker.start();
      //Start the applet
      public void start()
      //Stop the applet
      public void stop()
      //Destroy the applet
      public void destroy()
      //Get Applet information
      public String getAppletInfo()
        return "Applet Information";
      //Get parameter info
      public String[][] getParameterInfo()
        java.lang.String[][] pinfo =
            {"uploadPath", "String", ""},
        return pinfo;
      //Main method
      public static void main(String[] args)
        VideoUpload applet = new VideoUpload();
        applet.isStandalone = true;
        Frame frame;
        frame = new Frame();
        frame.setTitle("Applet Frame");
        frame.add(applet, BorderLayout.CENTER);
        applet.init();
        applet.start();
        frame.setSize(400, 320);
        Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
        frame.setLocation( (d.width - frame.getSize().width) / 2,
                          (d.height - frame.getSize().height) / 2);
        frame.setVisible(true);
    }

    Well after much ploughing through internet I have found much to my dismay that URLConnection is not as great as it may appear as it does buffer all output prior to sending.
    This is fine for everything but file transfers, especially large ones as memory can be an issue.
    Answered own question, doh!

  • Commons-fileupload-1.2.1. 4 kB limit

    Hi everybody.
    I am using apache commons-fileupload-1.2.1.jar to upload files (multipart data). I have copy/pasted the code from their example page:
    [http://commons.apache.org/fileupload/streaming.html]
    However, I have problems. When I open the inputStream to a file, and check for stream.available(), it always returns 3904 - 3916. And then I write that data down to a blob and from there save it to a file and the file is always 4 kB long.
    I have checked the limits of my Apache Tomcat. It allows files up to 20 MB.
    I have used this code to get the data:
                File tem = new File("/");
                FileItemFactory factory = new DiskFileItemFactory(10000000,tem);
                // Create a new file upload handler
                ServletFileUpload upload = new ServletFileUpload();
                // Parse the request
                // maximum size before a FileUploadException will be thrown
                upload.setSizeMax(10000000);
                upload.setFileSizeMax(10000000);
                upload = new ServletFileUpload(factory);
                // Parse the request
                FileItemIterator iter = upload.getItemIterator(request);
                while (iter.hasNext()) {
                    FileItemStream item = iter.next();
                    String name = item.getFieldName();
                    InputStream stream = item.openStream();
                    if (item.isFormField()) {
                         // source to do with form fields   
                    } else {
                        BufferedInputStream bis = new BufferedInputStream(stream, 1000000);
                        out.println("Stream has: " + stream.available());
                        // prints out 3904 - 3916, depends on the file
                        byte[] temp = new byte[stream.available()];
                        int bytesRead = stream.read(temp );
                        out.print("Number of bytes read: " +bytesRead + "<br>");
                        // prints out 3904 - 3916, depends on the file
                Any ideas what to add or where the 4 kB limit is?

    It's indeed a blocking/buffered stream. Commons FileUpload comes along with excellent documentation and examples of how to use it. Go read them. Especially the 'User Guide' and 'Frequently Asked Questions' sections at their homepage.
    If you really want to know the content length beforehand, you need HttpServletRequest#getContentLength(). Only keep in mind that the client has full control over the request header values, so your code shouldn't rely that much on this.
    That said, in the future you should be posting Servlet related questions at the Servlet forum.

  • Pb with file in jar

    I develop a small app which need to read information on text file in the Jar. The Emulation in Eclipse works well but when I use netbeans to make easily the Jar I have a problem and the program is unable to connect to the file.
    Where must I stock the file in the Jar? (In netbeans the .txt file where stock in <default package>.

              The request is in the form of multipart data and is parsed by the
              Oreilly class only. To access other information from the request
              the Oreilly class has provided you with the methods for getting
              the other data. You have to access the data from the request using
              the Oreilly class methods
              "Cameron Purdy" <[email protected]> wrote:
              >Be careful what methods you call on the request object.
              > They can prevent
              >you from later asking for that all-important input stream.
              >
              >--
              >Cameron Purdy
              >Tangosol, Inc.
              >http://www.tangosol.com
              >+1.617.623.5782
              >WebLogic Consulting Available
              >
              >
              >"Laurent Andre" <[email protected]> wrote
              >in message
              >news:3a88184c$[email protected]..
              >>
              >> Hello,
              >>
              >> we do have a problem with file upload ! We're using
              >the o'reilly class,
              >but every
              >> time we add ENCTYPE="multipart/formdata" in the html,
              >we're unable to
              >correctly get
              >> the request. ?
              >> any idea ? Is there something to configure ?
              >>
              >> thx
              >>
              >
              >
              

  • Full file Path when using FormFile in struts

    hi,
    i am uploading an excel file. All is doing fine but whatever file is selected by user by clicking the browse button, its does not retreive full path it retreives only the file name selected......
    JSP page
    <html:form action="uploadFile.do" method="POST" enctype="multipart/form-data">
         <html:file property="fileName" title="Browse" />
         <html:hidden property="methodtoinvoke" value="uploadFile" />
         <html:submit value="submit" />
    </html:form>when i retrieve this filename and convert it to String its only shows file name and not the full path, as a result it always pick this file name from the current working directory.
    how can i get the selected file path ????
    Pls help
    thanx

    What would do a server side program that processes the file upload do with the client side path of the file?
    The server side process (your Action class) would receive a stream of bytes (multipart data) that contains the file's contents as well as other info like size, content type etc.
    ram.

  • SOAP Adapter nosoap mode !

    Hi we have a Http to File scenario. PI will be getting Multipart Http post requests, xml file and pdf files through Http post request, I am using SOAP adapter in nosoap mode, how do I retain the original file name of the pdf while creating the file?

    Were you able to send Multipart data to XI from sender? In my opinon, you have to write an adapter module to handle multiple messages as attachment, and soap sender does not support module.
    Regards,
    Prateek

  • Problem when getting from truststore

    Hi,
    I have a problem that when using SSL and getting trusted cert from truststore. When using System.setProperty("javax.net.debug", "all");, although the cert is not in valid date, I can get see that the cert is added like following when using jdk1.4.2_04 or later
    init truststore
    adding as trusted cert:
    Subject: ...........
    However, the exception "javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: No trusted certificate found" exists when using jdk1.4.2_03, and I can see that after init truststore, no cert is added.
    Actually, it does not affect the application, but just want to know that whether jdk1.4.2_03 or before version does not get the expired cert? jdk1.4.2_04 or later will get it?
    Thank you.

    As long as I know you cannot retrieve the pairs key/value in the usual way from a multipart-data form.
    This post is about it:
    http://forum.java.sun.com/thread.jspa?threadID=258829&messageID=971787

Maybe you are looking for