Servlet file uploading code need.

Hello
Can somebody give me a sourcecode of working servlet program that do file uploading on the server?
thnks

He's not angry at you, he's just angry at the self-serving tone of your post.
Why don't you give me a $100 USD... while at it? Oh, no? But WHY? Why oh why? I'm such a good person of liberal character - could you give me a 100 dollars RIGHT NOW? Oh, you wouldn't - I see...
Almost the same w/that "give me source code" :)....

Similar Messages

  • 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

  • File Upload - code improvement help

    I have asked similar kind of question before, but it was termed as meaningless. I hope this time it will have some meaning(I am now following the instructions :)).
    I got this code from online, the address is mentioned in the comments. With little changes it is serving the purpose well. However, the upload time is a bit high and I was wondering is there a way to improve that.
    <!-- upload.jsp -->
    <!-- http://forums.codecharge.com/posts.php?post_id=44078 -->
    <html>
        <head>
        <title>Upload Page</title>
        <jsp:useBean class = "formjavabean.application" id = "applicationId" scope = "session" />
        </head>
        <body>
        <%@ page import="java.io.*" %>
        <%
        String userEmail = applicationId.getUserEmail()  ;
        File user = new File("C:\\JBoss\\jboss-4.0.5.GA\\bin\\Fastran\\" + userEmail ) ;
        user.mkdir() ;
        String contentType = request.getContentType();
        System.out.println("Content type is :: " +contentType);
        if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0))
            DataInputStream in = new DataInputStream(request.getInputStream());
            int formDataLength = request.getContentLength();
            byte dataBytes[] = new byte[formDataLength];
            int byteRead = 0;
            int totalBytesRead = 0;
            while (totalBytesRead < formDataLength)
                byteRead = in.read(dataBytes, totalBytesRead, formDataLength);
                totalBytesRead += byteRead;
            String file = new String(dataBytes);
            String saveFile = file.substring(file.indexOf("filename=\"") + 10);
            saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
            saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1,saveFile.indexOf("\""));
            int lastIndex = contentType.lastIndexOf("=");
            String boundary = contentType.substring(lastIndex + 1,contentType.length());
            int pos;
            pos = file.indexOf("filename=\"");
            pos = file.indexOf("\n", pos) + 1;
            pos = file.indexOf("\n", pos) + 1;
            pos = file.indexOf("\n", pos) + 1;
            int boundaryLocation = file.indexOf(boundary, pos) - 4;
            int startPos = ((file.substring(0, pos)).getBytes()).length;
            int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;
            FileOutputStream fileOut = new FileOutputStream("c:\\JBoss\\jboss-4.0.5.GA\\bin\\Fastran\\" + userEmail + "\\" + saveFile);
            fileOut.write(dataBytes, startPos, (endPos - startPos));
            fileOut.flush();
            fileOut.close();
        %>
        <img src="logo.jpeg" width="101" height="75" align = "Right">
        <img src="h_corporate_center.jpg" width="622" height="102">
        <br><br><br><br>
        <b>
        <%
        out.println("File uploaded as "+" \"" +saveFile+" \"");
        %>
        <br><br>
        <b>Please make sure all required files are uploaded:<br>
        <font color = "Red">ftn03, ftn07, and ftn09<font>
        <br><br><br><br>
        <input type=button onClick="location.href='fastran.jsp'" value='Proceed'>
        </body>
    </html>

    the input files are a bunch of text files, with a lot of numbers generated through some other software. There can be some big files (perhaps close to a GB), and the upload time for such a file is painfully long - something like 6 min, over LAN. I have tried to upload it on my own computer(with application server running on it) and for a 50 MB file, it is taking about 3 min.
    There are many third part options are available but that requires some librarires, and this code doesn't. So my preference is for this one.
    Also, I couldn't figure out exactly, but some articles were suggesting to use String buffers instead of just Strings. In my case, Strings are used.
    Secondly, I understand using of input and output buffer stream, but can it be the cause of long upload time? I mean converting a file to some machine independent code and then re-converting it back. If yes, can there be a way of skipping that all together ?
    I am a bit hesitant of asking questions, my previous experience here was not a very pleasant one. Some genius, bullied me around :)
    I will appreciate any help, thanks :)
    Message was edited by:
    NasirMunir

  • J2me multipart file upload-  Help Needed

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

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

  • Servlet file uploading

    hi
    from HTML page
    <form id="form" action="bookimage?a=add" method="get">
    <input type="text" name="txtBookTitleId" id="txtBookTitleId" />
    <input type="file" name="txtImg" id="txtImg"/>
    </fom>
    servlet
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    try {
    Long bookTitleId=new Long(request.getParameter("txtBookTitleId"));
    String imglocation=request.getParameter("txtImg");
    File file=new File(imglocation);
    FileInputStream fs = new FileInputStream(file);
    int len=fs.available();
    byte[] img = new byte[len];
    fs.read(img, 0,len);
    }catch(Exception e){
    e.printStackTrace();
    above is code which i use in my application
    but it not working
    i am not getting FileInputStream fs it gives error.
    if form method used post then gives null request parameter(bookTitleId , imglocation)
    please suggest solution proper and dynamic for image up loading form client to server .
    it works when i give static file path
    postgersql is database and application is Ejb application.

    To be able to send a file from the client to the server you need at least the POST method and the multipart/form-data enctype. Also see the HTML forms specification: [http://www.w3.org/TR/html401/interact/forms.html].
    In the server side, in case of a multipart/form-data request you need to extract all request parameters (including the complete file) back from the request body yourself. Those aren't available by getParameter() and so on. There's a very robust, commonly used and thoroughly tested API available for this: the Apache Commons FileUpload: [http://commons.apache.org/fileupload]. Read especially the 'User Guide' and 'Frequently Asked Questions' sections.

  • What's the error of this file-upload code?

    hi,
    I have written following code for file selection:
    <form action="display.jsp" method="POST" enctype="multipart/form-data">
    <input type="file" name="File1">
    <input type="submit" name = "button" value="Submit">
    </form>And my project another file display.jsp which code is:
    <%@ page import="org.apache.commons.fileupload.*"%>
    <%@page import="java.io.*" %>
    <%@page import="java.util.*" %>
    <%
         out.println("Content Type: "+request.getContentType());
         boolean isMultipart=FileUpload.isMultipartContent(request);
         DiskFileUpload upload=new DiskFileUpload();
         List items=upload.parseRequest(request);
         Iterator iter=items.iterator();
         while(iter.hasNext()){
              FileItem item=(FileItem)iter.next();
              if(item.isFormField()){
                   out.println("SIZE: "+item.getSize());
                File fNew= new File(application.getRealPath("/"), item.getName());
                 out.println(fNew.getAbsolutePath());
                item.write(fNew);
              else
         out.println("Field ="+item.getFieldName());
    %>After that, i put on common-fileupload-1.1..jar on the project's /WebConcontent/WEB-INF/lib/ directory. And i have also add the common--fileupload-1.1.1. jar in the project build path. Further that i have got following error:
    Error is:
    exception
    org.apache.jasper.JasperException: org/apache/commons/io/output/DeferredFileOutputStream
         org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:510)
         org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:375)
         org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:314)
         org.apache.jasper.servlet.JspServlet.service(JspServlet.java:264)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
    root cause
    javax.servlet.ServletException: org/apache/commons/io/output/DeferredFileOutputStream
         org.apache.jasper.runtime.PageContextImpl.doHandlePageException(PageContextImpl.java:858)
         org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:791)
         org.apache.jsp.display_jsp._jspService(display_jsp.java:78)
         org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:97)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
         org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:332)
         org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:314)
         org.apache.jasper.servlet.JspServlet.service(JspServlet.java:264)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
    root cause
    java.lang.NoClassDefFoundError: org/apache/commons/io/output/DeferredFileOutputStream
         org.apache.commons.fileupload.DefaultFileItemFactory.createItem(DefaultFileItemFactory.java:102)
         org.apache.commons.fileupload.FileUploadBase.createItem(FileUploadBase.java:500)
         org.apache.commons.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:367)
         org.apache.commons.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:268)
         org.apache.jsp.display_jsp._jspService(display_jsp.java:53)
         org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:97)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
         org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:332)
         org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:314)
         org.apache.jasper.servlet.JspServlet.service(JspServlet.java:264)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:802)Why i have got this error? IS there anybody can help me? What will be the solution?Please Help me?
    With regards
    Bina

    java.lang.NoClassDefFoundError: org/apache/commons/io/output/DeferredFileOutputStream
    Means you are missing a class file from the class path. Most likely cause is a missing jar file. The Apache Commons utilities often have dependancies on other Commons projects. This looks like it is looking for the Apache Commons IO jar file. Download the jar file and add it to the WEB-INF/lib directory.

  • Image file upload code

    Hi,
    I'm trying to track down where, i.e. by which code, image files are saved into the wiki.
    I've traced the route to the wiki.js file which creates the dialogue that posts the form to the server but I've run into a wall.
    I can't establish the name of the 'action' for the form.
    Nor can I infer which python code is receiving it.
    Can anyone help?
    p.s. The reason for all this is that I want uploaded files to be namable, either manually or driven by a field in the form.
    I guess this may involve rewriting some Python and I know that this is frowned upon but the look-out is mine!
    p.p.s. It would also be nice to know where dialogManager() is defined, that's got me beaten at the moment.

    John Anderson1 wrote:
    Remember that, when changing the code, you should override the code using your own theme; don't change it directly. Changing the uncompressed JavaScript won't work anyway; the server sends out code-compressed scripts whenever possible. Changing source code maintained by automatic software updates is the first of many steps down the path toward a bricked server.
    Yes, I'm starting to get a hang of this (I think) I do intend to override the js, it's just I need to know how it's doing it in order to overrride it!
    The form's "action" is "images"
    I'd sort of deduced this but I can't find the code on the server that implements it. I did a quick search and couldn't find "images' in Python and deduced I was being a bit simplistic.
    and dialogManager is defined in widgets.js:
    var ModalDialogManager = Class.createWithSharedInstance('dialogManager');
    Ah, thanks, I'll follow it up.
    You do know that you can just name the file in the Finder before uploading it, right?
    Not really. Under certain circumstances I want teamsserver to save the image file, in the page's image folder, with a particular name, i.e. NOT 123456.gif but pageImage.gif. I recognise that one has the potential problem of duplicate filenames but I'm happy to overwrite existing files AND I'm quite happy for teamsserver to give the file a unique name (presumably for internal database purposes) and make a duplicate of the numbered filename. i.e. save 123456.gif as per normal and then, if some condition is met (e.g. the alt name == pageimage) save a copy as pageImage.gif
    (If you're interested, I've managed to get search to take an additional parameter xslFile=1...5 which selects alternate search.xsl files that return different search layouts. One of which substitutes page specific images instead of the generic 'snowflake' image in search listings. Currently I have to give each page a tag that specifies what the pageImage uid is, but this is wasteful as every tag in every page is therefore different. What I'm trying to do now is make the pageImage filename consistent so that I have a single tag that indicates every page that has an associated image. (The custom search.xsl files recognise if a page HAS a custom image and uses the snowflake if it doesn't)
    Basically it allows me to generate slightly more attractive listings - nothing big but nice for my 'list of published books' page. Vanity, vanity)
    Thanks for hte help. I'll follow it up tomorrow.

  • File upload - I need help

    [Sorry 'bout my bad English]
    I'm trying to upload a file in a JSP. This page do a post to another JSP. In this page I have the code (there is more):
    1)PrintWriter pw = new PrintWriter(
    2) new BufferedWriter(new FileWriter( file)));
    3) ServletInputStream in = request.getInputStream();
    4) int i = in.read(); // here I got the error
    5) while ( i != -1 ) {
    6) pw.print((char) i);
    7) i = in.read();
    8) }
    I got an error that the file was not open, so I run the page in the debug mode, and I notice that the lenght of 'in', just after line 3, is 0.
    Please help
    thank you.

    read this. its 4 pages. tells ya everything you need to know.
    http://www.onjava.com/pub/a/onjava/2001/04/05/upload.html?page=1
    -S-

  • File Upload Help Needed - Very Urgent

    Dear All
    I am making a application in Webdynpro for uploading an excel file to the server. Can someone give me a demo application so that I can run it and see whether my server is configured or not. Also I have made the application right now and have coded the need full. But when I select a file and say submit it shows me a page not found error. Currently I am working round the clock on my project and am stuck up here. Its very urgent can any body help please with an example or a demo application.
    Regards Gaurav

    Hi,
      Check whether in server, MultipartBodyParameterName property is set to "com.sap.servlet.multipart.body" . You can check this by going to Visual Admin -> Cluster tab -> Services -> web container -> Properties sheet.
    Do assign points if i answered your question.
    Regards
    Vasu

  • (JSP/SERVLET) File upload Character problem form enctype="multipart.....

    Hi,
    When i upload a file from <form> ( jsp page ) and send it to my object class(struts,servlet) , the filename �����.doc are replaced by ?????.doc. in the database.
    I make few test by adding UTF-8 charset and content type to the jsp but still doesn't work...
    Ex :
    String encod = request.getCharacterEncoding();
    if (encod == null || !encod.equals("UTF-8"))
    try
    request.setCharacterEncoding("UTF-8");
    catch (UnsupportedEncodingException e)
    System.err.println("HttpMultipartRequest - : " + e);
    It's not a charset problem in the database because i try to do with an input type="text" and its working. It's just not working with the input type="file".
    And i also add directly ��� character into the database and its working.
    it's will be a pleasure if someone could response to me .
    thanks
    Jonathan

    warnerja,
    Not sure why you always play the part of the
    cross-post police... Seems like waste of effort to
    me.To each his own. I'm not sure why you feel the need
    to question my motives. Also not sure why you have
    posted requests to Sun regarding forum features...
    "Seems like a waste of effort to me.". But I wasn't
    going to call you on it.touch�
    :-)

  • File upload after deployment

    hi everbody,
    i had deployed the file upload code in unix server and the page is successfully opening after attaching functions and menus. Now the page has only messagefileupload type item for file upload. so please please can anybody tell how to upload the file to a specific directory. my code i have used is in application module is like this but after selecting a file and click submit the file is not being uploaded.
    String path= "/u03/prodcomn/temp/"+fileName;
    if(testprofile != null){     
    System.out.println("path.."+path);
    FileOutputStream fileOutput = new FileOutputStream(path);
    fileOutput.write(blobIn.toByteArray());
    fileOutput.close();
    }

    the above code is perfectly correct and it is working , the silly thing that i didnt notice is in winscp i didnt refresh and see after file upload in the page.
    i had wasted whole one day for this.
    thanks
    prabhakaranp

  • File upload JSP

    Yet again the issue of file upload...?:|
    I am trying to use a file upload as part of my screenflow.
    I besically have 2 jsp files. jsp file upload code and the supporting HTML.
    I created 2 "interactive component calls", connected with a transition and in the 1st one I call one JSP and in the 2nd one the other JSP.
    My action on my HTML is action="fileupload.jsp" (my upload code file) I try changing it to action="&lt;f:postResults /&gt;" but that didnt work
    Then I changed my action to "&lt;f:postResults fowardUrl="fileupload.jsp"/&gt; I got an error on that too.
    Anyone can help with that issue? I am besically tring to do a simple file upload from my sub-process.
    Thank You
    Lilach

    Hi,
    There was a sample application regarding File Upload in Fuego 5.5. My mail id is [email protected] If you want then drop me a mail and I can send across the export of the same to you.

  • HELP! File Upload Servlet and Internet Explorer

    Hello people. I hope this is an easy problem to solve...
    I have a servlet upload program that works using Mozilla browser (www.mozilla.org), but for some reason it doesn't work using Microsoft IE. The servlet is also using the servlet upload API from Apache (commons).
    I'm using IE version 6.0.2800.1106 in a Win98SE host computer. I get a cannot find path specified error message (see below). At work, I also get the same error message using IE, but don't know what version. The OS is XP. Unfortunately, at work, I can't install Mozilla browser (or any software-company policy) to see if Mozilla works there too. I would've like to have tested to see if the upload program worked on Mozilla on a truly remote computer.
    So I figured, it must be a IE configuration issue, but darn it!! I began by resetting IE to default settings, but still have the problem, I played around with several different combinations of settings in "Tools"-->"Internet Options...", and I still get the error message. Someone PLEASE HELP ME!!!
    Dunno, if it will help, I've also pasted the upload servlet source code below and the html file that's calling the upload servlet, but you still need the Apache commons file upload API.
    Trust me on this one folks, for some reason it works for Mozilla, but not for IE. With IE, I can at least access web server, and therefore, the html file that calls the upload servlet , so I don't think it's a Tomcat configuration issue (version 5.0). I actually got the code for the file upload servlet from a book relatively new in the market (printed in 2003), and it didn't mention any limitations as far as what browser to use or any browser configuration requirements. I have e-mailed the authors, but they probably get a ton of e-mails...
    Anyone suggestions?
    Meanwhile, I will try to install other free browsers and see if the file upload program works for them too.
    ERROR MESSAGE:
    "HTTP Status 500 -
    type Exception report
    message
    description The server encountered an internal error () that prevented it from fulfilling this request.
    exception
    javax.servlet.ServletException: C:\TOMCAT\webapps\MyWebApps\files\C:\WINDOWS\Desktop\myfile.zip (The system cannot find the path specified)
         com.jspbook.FileUploadCommons.doPost(FileUploadCommons.java:43)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:763)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:856)
    root cause
    java.io.FileNotFoundException: C:\TOMCAT\webapps\MyWebApp\files\C:\WINDOWS\Desktop\myfile.zip (The system cannot find the path specified)
         java.io.FileOutputStream.open(Native Method)
         java.io.FileOutputStream.(FileOutputStream.java:176)
         java.io.FileOutputStream.(FileOutputStream.java:131)
         org.apache.commons.fileupload.DefaultFileItem.write(DefaultFileItem.java:392)
         com.jspbook.FileUploadCommons.doPost(FileUploadCommons.java:36)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:763)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:856)
    note The full stack trace of the root cause is available in the Tomcat logs.
    Apache Tomcat 5.0.16"
    FILE UPLOAD SERVLET source code:
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import org.apache.commons.fileupload.*;
    import java.util.*;
    public class FileUploadCommons extends HttpServlet {
    public void doPost(HttpServletRequest request,
    HttpServletResponse response)
    throws IOException, ServletException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.println("<html>");
    out.print("File upload success. <a href=\"/MyWebApp/files/");
    out.print("\">Click here to browse through all uploaded ");
    out.println("files.</a><br>");
    ServletContext sc = getServletContext();
    String path = sc.getRealPath("/files");
    org.apache.commons.fileupload.DiskFileUpload fu = new
    org.apache.commons.fileupload.DiskFileUpload();
    fu.setSizeMax(-1);
    fu.setRepositoryPath(path);
    try {
    List l = fu.parseRequest(request);
    Iterator i = l.iterator();
    while (i.hasNext()) {
    FileItem fi = (FileItem)i.next();
    fi.write(new File(path, fi.getName()));
    catch (Exception e) {
    throw new ServletException(e);
    out.println("</html>");
    public void doGet(HttpServletRequest request,
    HttpServletResponse response)
    throws IOException, ServletException {
    doPost(request, response);
    HTML PAGE that calls the upload servlet:
    <html>
    <head>
    <title>Example HTML Form</title>
    </head>
    <body>
    <p>Select a file to upload or browse
    currently uploaded files.</p>
    <form action="http://##.##.##.####/MyWebApp/FileUploadCommons"
    method="post" enctype="multipart/form-data">
    File: <input type="file" name="file"><br>
    <input value="Upload File" type="submit">
    </form>
    </body>
    </html>
    Thanks in advance for any assistance.
    -Dan

    I'm guessing what is happening is that Mozilla tells the servlet "here comes the file myfile.zip". The servlet builds a file name for it:
        String path = sc.getRealPath("/files");
        // path is now C:\TOMCAT\webapps\MyWebApps\files\
        fi.write(new File(path, fi.getName()));
        // append myfile.zip to "path", making it C:\TOMCAT\webapps\MyWebApps\files\myfile.zipIE, however, tells "here comes the file C:\WINDOWS\Desktop\myfile.zip". Now imagine what the path+filename ends up being...
    So what you want to do is something along the lines of (assuming Windoze):
    public static String basename(String filename)
        int slash = filename.lastIndexOf("\\");
        if (slash != -1)
            filename = filename.substring(slash + 1);
        // I think Windows doesn't like /'s either
        int slash = filename.lastIndexOf("/");
        if (slash != -1)
            filename = filename.substring(slash + 1);
        // In case the name is C:foo.txt
        int slash = filename.lastIndexOf(":");
        if (slash != -1)
            filename = filename.substring(slash + 1);
        return filename;
        fi.write(new File(path, basename(fi.getName()));
        ....You can make the file name check more bomb proof if security is an issue. Long file names trying to overflow something in the OS, NUL characters, Unicode, forbidden names in Windos (con, nul, ...), missing file name, ...

  • File upload using Servlets and Weblogic

    Hi,
    I need to write a servlet that can upload a .doc file to a folder on the server. Can someone please let me know abot the code i need to write, as i am a novice in servlets.
    Thanks in advance
    buddy0303

    Another, simpler (we think), such package is Jenkov HTTP Multipart File Upload. It's a servlet filter which can work in front of both servlets and JSP's. The servlet filter parses the uploaded file and stores it temporarily on the servers disk. When the servlet or JSP executes afterwards, it can obtain all the information about the file, from the request attributes. There is a decent manual for HTTP Multipart File Upload on the website.
    Just search for "Jenkov HTTP Multipart" on Google and you'll find it. HTTP Multipart is free, open source, Apache Licsense.

  • Java.io.IOException in servlet-based file upload

    Hi,
              I'm running into some problems with Weblogic Server 5.1 on Unix (Solaris), while
              trying to do a servlet-based file upload. I'm trying to upload a file to the
              server file system through a file upload servlet running inside Weblogic Server
              5.1, and I get an exception when I try to create a file on the Unix server
              filesystem:
              java.io.IOException: Not owner
              at java.io.UnixFileSystem.createFileExclusively(Native Method)
              at java.io.File.createNewFile(File.java:692)
              at com.cysive.filemanagement.UploadFile.save(UploadFile.java:84)
              I tried changing the upload location to various places, like directly in the
              docroot (myserver/public_html), in my home directory, etc. I am not sure which
              owner Weblogic is looking for, because the process is owned by whoever starts
              the WL server. And the strange thing is, I am able to create new directories on
              the file system, just not files.
              When I run the exact code on WinNT, everything works fine... I am able to create
              files and directories and the upload goes through smoothly.
              I'm thinking there is something I need to be setting in the weblogic.properties
              file on Unix by way of permissions/privileges that is not required on WinNT, but
              was not able to find anything in the documentation.
              Could anyone help, please?
              Thanks.
              Hrishi
              

    Check what user/group you are running your weblogic server.(check out the user who starts as well as UID/user/group in weblogic.properties file if you have set them).
    check out whether that user/group has necessary permission on unix m/c
    Hrishi Dixit <[email protected]> wrote:
    >
    Hi,
    I'm running into some problems with Weblogic Server on Unix, while trying to do
    a servlet-based file upload. I'm trying to upload a file to the server file
    system through a file upload servlet running inside Weblogic Server 5.1, and I
    get an exception when I try to create a file on the Unix server filesystem:
    java.io.IOException: Not owner
         at java.io.UnixFileSystem.createFileExclusively(Native Method)
         at java.io.File.createNewFile(File.java:692)
         at com.cysive.filemanagement.UploadFile.save(UploadFile.java:84)
    I tried changing the upload location to various places, like directly in the
    docroot (myserver/public_html), in my home directory, etc. I am not sure which
    owner Weblogic is looking for, because the process is owned by whoever starts
    the WL server. And the strange thing is, I am able to create new directories on
    the file system, just not files.
    When I run the exact code on WinNT, everything works fine... I am able to create
    files and directories and the upload goes through smoothly.
    I'm thinking there is something I need to be setting in the weblogic.properties
    file on Unix by way of permissions/privileges that is not required on WinNT, but
    was not able to find anything in the documentation.
    Could anyone help, please?
    Thanks.
    Hrishi

Maybe you are looking for

  • Having Trouble setting up 9i on WinXP Pro

    Hi I've downloaded Oracle9i Database Release 2 Enterprise/Standard/Personal Edition for Windows NT/2000/XP. I unzip the 3 files into their appropriate folders, disk1, disk2, etc. Then when I clicked setup.exe or autorun.exe, nothing happens. I've tri

  • HT1338 my iphone and ipad are no longer syncing to my macbook air

    I dont know why I can no longer sync my iphone and ipad to my macbook air. It is a recent change - sometime during January. Any ideas?

  • Handling uncaught runtime exceptions

    Hi, We are building a ADF applicaton using eclipselink as the backend. When an uncaught runtime exception (like null pointer or optimistic lock exception) occurs in the application, we are seeing the exception stack trace as an alert. Is there a way

  • Photos are not sharp

    i have my new ipod repaired due to backlight issue, but the new one i got doesn't show sharp photos... and i tried getting into the settings to refine but it has no opption of refining! what should i do?

  • Use an expression to trigger a sound file?

    I have a comp with many layers. At the beginning of each layer, I want to play an AIFF file (the same one for every layer). Rather than adding the AIFF asset to the project over and over, is there a way to add the sound file to the comp once, and the