Uploading a file in Servlets

I need help in uploading a file using servlets.help

http://search.java.sun.com/search/java/index.jsp?col=ja
aforums&qp=&qt=servlet+file+uploadThats a Master Link!!

Similar Messages

  • How to upload a file in servlet ?

    hi i am new to this concept ..............
    i need upload a file in mysql database .........
    i created a form ...
    <html>
    <form method="post" action="http://localhost:8080/examples/servlet/UploadFile" enctype="multipart/form-data">
    File
    <input type="file" name="upload"/>
    <input type="submit" value="load" />
    </form>
    </html>
    what servlet receives from request ? how it will be stored in database ...
    i need a detail explanation ...
    Thanks

    The apache jakarta commons FileUpload project has sample code for how to upload a file.
    To store the file in the database you would use a preparedStatement. You can use anyone of the following methods ; setBlob, setBinaryStream, setBytes.
    The datatype of the column storing the document depend on the databse. SQL Server used image and postgres uses bytea

  • How to get the complete path name when uploading a file from servlet

    Hi,
    I write a servlet to upload a file from html page
    <intput type=file name=fileupload>I am using
    import org.apache.commons.fileupload.to upload file. i want to get the all fields in the form and file name and content of the file also.
    It give the file name only
    String filename= fileItem.getName();
    o/p krish.jpgBut i want complete path naem like
    d:/krishna/images/funny/krish.jpgI serach the API org.apache.commons.fileupload.*
    But i did nt find the method to get it.
    plz help me , which api or method to use here..

    Krishna_Rao_chintu wrote:
    But i need path and have to do some calculations on it.No, you don't. If you have requirements which say you do then the requirements are wrong. You couldn't do anything useful with the path on the client system even if you could get it.
    is there any alternatives in java
    I need path and have to calculate MD5, Presumably you need to calculate MD5 on the contents of the file and not on the name of the file.
    and convert the file to binary format.... etc oprations on itSorry, "convert a file to binary format" is basically meaningless.
    but we can get the content of the file using
    byte [] get()/ getString() methods
    If i get content is there any performance degrades?
    ie if the content is lengthy is it take more time?Take more time than what? Degrading performance from what? It's certainly true that it would be quicker to not upload the file, but that's a pointless comparison. If you have some other process to compare with, let us know what it would be.

  • How to upload a file in servlets

    Can any one help me in uploading a file inServlets.I am new to this.If possible a source code for it.

    public void doPost( HttpServletRequest request,
    HttpServletResponse response ) throws IOException,
    ServletException
    System.out.println("request.getContentType()" + request.getContentType());
    ServletContext sc = getServletContext();
    // Here I want to put my files on server ..
    String path = sc.getRealPath( "/testfiles" );
    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();
    File file = new File(fi.getName());
    fi.write( new File(path,file.getName()));
    catch (Exception e)
    throw new ServletException( e );
    String forwardFileName = (String) request.getParameter( "h" );
    if (forwardFileName != null)
    if (forwardFileName.indexOf( ".jsp" ) == -1)
    forwardFileName = forwardFileName + ".jsp";
    response.sendRedirect(forwardFileName);
    }

  • How can we upload ftp file using servlets

    I have to write the code to upload file from an FTP location.
    How can I do it as I'm having no idea.
    Message was edited by:
    urssireesh

    The Apache Commons project has a couple of components that may help. Check out the net or vfs components:
    http://jakarta.apache.org/commons/components.html
    Also look on the SourceForge site for any Java FTP projects that you could use.

  • Uploading a file to server using servlet (Without using Jakarta Commons)

    Hi,
    I was trying to upload a file to server using servlet, but i need to do that without the help of anyother API packages like Jakarta Commons Upload. If any class for retrieval is necessary, how can i write my own code to upload from client machine?.
    From
    Velu

    <p>Why put such a restriction on the solution? Whats wrong about using that library?
    The uploading bit is easy - you put a <input type="file"> component on the form, and set it to be method="post" and enctype="multipart/form-data"
    Reading the input stream at the other end - thats harder - which is why they wrote a library for it. </p>
    why i gave the restriction is that, i have a question that <code>'can't we implement the same upload'</code>
    I was with the view that the same can be implemented by our own code right?

  • Upload File in servlet

    hi , i upload a file in jsp and in the servlet i want to read the contents of the file not store it.
    can u provide me with a simple basic code to do this.
    i dont want to use any 3rd party classes for this purpose.
    THanks

    why no 3rd party stuff? It'll make it a whole lot easier. See, if we give you any code, of course, that would be "3rd party" If you want to do it yourself, then you should go look for the RFC on file upload and maybe get a network packet sniffer app and look at what the browser sends when it submits a file upload form.

  • How to upload a file into server using j2ee jsp and servlet with bean?

    How to upload a file into server using j2ee jsp and servlet with bean? Please give me the reference or url about how to do that. If related to struts is more suitable.
    Anyone help me please!

    u don't need j2ee and struts to do file uploading. An example is as such
    in JSP. u use the <input> file tag like
    <input type="file"....>You need a bean to capture the file contents like
    class FileUploadObj {
        private FormFile srcFile;
        private byte[] fileContent;
        // all the getter and setter methods
    }Then in the servlet, you process the file for uploading
        * The following loads the uploaded binary data into a byte Array.
        FileUploadObj form = new FileUploadObj();
        byte[] byteArr = null;
        if (form.signFile != null) {
            int filesize = form.srcFile.getFileSize();
            byteArr = new byte[filesize];
            ByteArrayInputStream bytein = new ByteArrayInputStream (form.srcFile.getFileData());
            bytein.read(byteArr);
            bytein.close();
            form.setFileContent(byteArr);
        // Write file content using Writer class into the destination file in the server.
        ...

  • File Upload into CVS through Servlets/JSP

    Hi,
    I am new to servlets/jsp. I have a task which has following requirments:
    1. File(text/pic) uploading feature for client. ( i am using com.oreilly.servletpackage for this)
    2. I need to upload this file to CVS repository with all the version controls, check in, check out features. (how should i do it?)
    pls help.

    which IDE are you using ?

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

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

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

  • File upload problem in java servlets

    hello,
    I want to upload my files.i have used Multipartrequest object.In my form i had included enctype="multipart/form-data".
    I want to upload one or more files .
    So, I made a file input box and then a select option box. With the help of java script i stored the values of the file input box to the select option drop down box.In this way i stored the name and path of the file in the select option drop down box also. Now when i tried to upload all the file in the select option box it is uploading only one file which is the last one selected from the file input box.
    I hope that file name is also getting from the file input box, and that is the reason why it is uploading that file only.I write this code to execute it.
    MultipartRequest multi=new MultipartRequest(request,".",5*1024*1024);
    I want to upload all the files, so what should i do,
    Please help me to solve this problem
    puneet

    Hi,
    First go through the Multipart code and try to study what it does.it does not upload all the fields u submit in a form.it will first parse the servletInputStream which seperates the normal form fields and the "File" field.when u say ENC-TYPE="multipart/form-data" the way in which it is sent is different for normal fields and the "File" field.there'll be boundaries for each field.also for "File" field the filename will be passed in the Content-disposition info(which contains the values of form fields,their names and filename(only for File input)in specific format) .so if u want to upload more files in the same submit use two or more "File" fields.
    If any one else has a better option let me know

  • Upload multiple files WITH correct pairs of form fields into Database

    In my form page, I would like to allow 3 files upload and 3 corresponding text fields, so that the filename and text description can be saved in database table in correct pair. Like this:
    INSERT INTO table1 (filename,desc) VALUES('photo1.jpg','happy day');
    INSERT INTO table1 (filename,desc) VALUES('photo2.jpg','fire camp');
    INSERT INTO table1 (filename,desc) VALUES('photo3.jpg','christmas night');
    However, using the commons fileupload, http://commons.apache.org/fileupload/, I don't know how to reconstruct my codes so that I can acheieve this result.
    if(item.isFormField()){
    }else{
    }I seems to be restricted from this structure.
    The jsp form page
    <input type="text" name="description1" value="" />
    <input type="file" name="sourcefile" value="" />
    <input type="text" name="description2" value="" />
    <input type="file" name="sourcefile" value="" />The Servlet file
    package Upload;
    import sql.*;
    import user.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.util.Map;
    import java.util.HashMap;
    import java.util.Date;
    import java.util.List;
    import java.util.Iterator;
    import java.io.File;
    import java.io.PrintWriter;
    import java.io.IOException;
    import java.text.SimpleDateFormat;
    import org.apache.commons.fileupload.servlet.ServletFileUpload;
    import org.apache.commons.fileupload.disk.DiskFileItemFactory;
    import org.apache.commons.fileupload.*;
    public class UploadFile extends HttpServlet {
    private String fs;
    private String category = null;
    private String realpath = null;
    public String imagepath = null;
    public PrintWriter out;
    private Map<String, String> formfield = new HashMap<String, String>();
      //Initialize global variables
      public void init(ServletConfig config, ServletContext context) throws ServletException {
        super.init(config);
      //Process the HTTP Post request
      public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        Thumbnail thumb = new Thumbnail();
        fs = System.getProperty("file.separator");
        this.SetImagePath();
         boolean isMultipart = ServletFileUpload.isMultipartContent(request);
         if(!isMultipart){
          out.print("not multiple part.");
         }else{
             FileItemFactory factory = new DiskFileItemFactory();
             ServletFileUpload upload = new ServletFileUpload(factory);
             List items = null;
             try{
                items = upload.parseRequest(request);
             } catch (FileUploadException e) {
                e.printStackTrace();
             Iterator itr = items.iterator();
             while (itr.hasNext()) {
               FileItem item = (FileItem) itr.next();
               if(item.isFormField()){
                  String formvalue = new String(item.getString().getBytes("ISO-8859-1"), "utf-8");
                  formfield.put(item.getFieldName(),formvalue);
                  out.println("Normal Form Field, ParaName:" + item.getFieldName() + ", ParaValue: " + formvalue + "<br/>");
               }else{
                 String itemName = item.getName();
                 String filename = GetTodayDate() + "-" + itemName;
                 try{
                   new File(this.imagepath + formfield.get("category")).mkdirs();
                   new File(this.imagepath + formfield.get("category")+fs+"thumbnails").mkdirs();
                   //Save the file to the destination path
                   File savedFile = new File(this.imagepath + formfield.get("category") + fs + filename);
                   item.write(savedFile);
                   thumb.Process(this.imagepath + formfield.get("category") +fs+ filename,this.imagepath + formfield.get("category") +fs+ "thumbnails" +fs+ filename, 25, 100);
                   DBConnection db = new DBConnection();
                   String sql = "SELECT id from category where name = '"+formfield.get("category")+"'";
                   db.SelectQuery(sql);
                    while(db.rs.next()){
                      int cat_id = db.rs.getInt("id");
                      sql = "INSERT INTO file (cat_id,filename,description) VALUES ("+cat_id+",'"+filename+"','"+formfield.get("description")+"')";
                      out.println(sql);
                      db.RunQuery(sql);
                 } catch (Exception e){
                    e.printStackTrace();
            HttpSession session = request.getSession();
            UserData k = (UserData)session.getAttribute("userdata");
            k.setMessage("File Upload successfully");
            response.sendRedirect("./Upload.jsp");
      //Get today date, it is a test, actually the current date can be retrieved from SQL
      public String GetTodayDate(){
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        String today = format.format(new Date());
        return today;
      //Set the current RealPath which the file calls for this file
      public void SetRealPath(){
        this.realpath = getServletConfig().getServletContext().getRealPath("/");
      public void SetImagePath(){
        this.SetRealPath();
        this.imagepath = this.realpath + "images" +fs;
    }Can anyone give me some code suggestion? Thx.

    When one hits the submit button - I then get a 404 page error.What is the apaches(?) error log saying? Mostly you get very useful information when looking into the error log!
    In any case you may look at how you are Uploading Multiple Files with mod_plsql.

  • To upload a file from client machine to server machine

    Hi everybody!
    Could anyone plz help me. I am struck in a problem
    I want to transfer a file from client's machine to server but I am not able to upload
    It is tranferring the file only to the local machine
    I am using orielley package It is transferring files only to my local machine but not to the server .Can anyone correct it. It's very urgent
    how to write the relative path for server
    I am using this path and it is not uploading
    MultipartRequest multi = new MultipartRequest(request, "../<administrator>:<dev2daask>@dev2:C:/123data/", 5 * 1024 * 1024);
    Here is my code:
    <%@ page import="java.util.*" %>
    <%@ page import="javax.servlet.*" %>
    <%@ page import="javax.servlet.http.*" %>
    <%@ page import="java.io.*" %>
    <%@ page import="com.oreilly.servlet.MultipartRequest"%>
    <%
    try {
    // Blindly take it on faith this is a multipart/form-data request
    // Construct a MultipartRequest to help read the information.
    // Pass in the request, a directory to saves files to, and the
    // maximum POST size we should attempt to handle.
    // Here we (rudely) write to the server root and impose 5 Meg limit.
    MultipartRequest multi = new MultipartRequest(request, "../<administrator>:<dev2daask>@dev2:C:/123data/", 5 * 1024 * 1024);
    out.println("<HTML>");
    out.println("<HEAD><TITLE>UploadTest</TITLE></HEAD>");
    out.println("<BODY>");
    out.println("<H1>UploadTest</H1>");
    // Print the parameters we received
    out.println("<H3>Params:</H3>");
    out.println("<PRE>");
    Enumeration params = multi.getParameterNames();
    while (params.hasMoreElements()) {
    String name = (String)params.nextElement();
    String value = multi.getParameter(name);
    out.println(name + " = " + value);
    out.println("</PRE>");
    // Show which files we received
    out.println("<H3>Files:</H3>");
    out.println("<PRE>");
    Enumeration files = multi.getFileNames();
    while (files.hasMoreElements()) {
    String name = (String)files.nextElement();
    String filename = multi.getFilesystemName(name);
    String type = multi.getContentType(name);
    File f = multi.getFile(name);
    out.println("name: " + name);
    out.println("filename: " + filename);
    out.println("type: " + type);
    if (f != null) {
    out.println("length: " + f.length());
    out.println();
    out.println("</PRE>");
    catch (Exception e) {
    out.println("<PRE>");
    out.println("</PRE>");
    out.println("</BODY></HTML>");
    %>

    you have not understood my point
    how does this code will run on servlet when I want to upload a file from client's
    machine to server machine
    what I am doing is I am giving an option to the user that he/she can browse the file and then select any file and finally it's action is post in the jsp form for which I have sent the code
    All the computers are connected in LAN
    So how to upload a file from client's machine to server's machine
    Plz give me a solution

  • How to upload a file to the server using ajax and struts

    With the following code iam able to upload a file ato the server.
    But my problem is It is working fine if iam doing in my system nd when iam trying to
    access theis application from someother system in our office which are connected through lan
    iam getting an error called 500 i,e internal server error.
    Why it is so???????
    Plz help me????????
    It is required in my project.
    I want the code to access from every system.
    My exact requirement is i have to upload a file to the server and retrive its path and show it in the same page from which we
    have uploaded a file.
    Here the file has to be uploaded to the upload folder which is present in the server.Iam using Tomcat server.
    Any help highly appreciated.
    Thanks in Advance
    This is my input jsp
    filename.jsp
    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Insert title here</title>
    <script type="text/javascript">
    alertflag = true;
    var xmlHttp;
    function startRequest(file1)
         if(alertflag)
         alert("file1");
         alert(file1);
    xmlHttp=createXmlHttpRequest();
    var video=document.getElementById("filepath").value;
    xmlHttp.open("POST","FilePathAction.do",true);
    xmlHttp.onreadystatechange=handleStateChange;
    xmlHttp.setRequestHeader('Content-Type', application/x-www-form-urlencoded');
    xmlHttp.send("filepath="+file1);
    function createXmlHttpRequest()
         //For IE
    if(window.ActiveXObject)
    xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
         //otherthan IE
    else if(window.XMLHttpRequest)
    xmlHttp=new XMLHttpRequest();
    return xmlHttp;
    //Next is the function that sets up the communication with the server.
    //This function also registers the callback handler, which is handleStateChange. Next is the code for the handler.
    function handleStateChange()
    var message=" ";
    if(xmlHttp.readyState==4)
         if(alertflag)
              alert(xmlHttp.status);
    if(xmlHttp.status==200)
    if(alertflag)
                                       alert("here");
                                       document.getElementById("div1").style.visibility = "visible";     
    var results=xmlHttp.responseText;
              document.getElementById('div1').innerHTML = results;
    else
    alert("Error loading page"+xmlHttp.status+":"+xmlHttp.statusText);
    </script></head><body><form >
    <input type="file" name="filepath" id="filepath" onchange="startRequest(this.value);"/>
    </form>
    <div id="div1" style="visibility:hidden;">
    </div></body></html>
    The corresponding action class is FIlePathAction
    package actions;
    import org.apache.struts.action.Action;
    import org.apache.struts.action.ActionForm;
    import org.apache.struts.action.ActionForward;
    import org.apache.struts.action.ActionMapping;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.*;
    public class FilePathAction extends Action{
         public ActionForward execute(ActionMapping mapping, ActionForm form,
                   HttpServletRequest request, HttpServletResponse response)
                   throws IOException, ServletException
              String contextPath1 = "";
              String uploadDirName="";
              String filepath="";
                        System.out.println(contextPath1 );
                        String inputfile = request.getParameter("filepath");
                        uploadDirName = getServlet().getServletContext().getRealPath("/upload");
                        File f=new File(inputfile);
    FileInputStream fis=null;
    FileOutputStream fo=null;
    File f1=new File(uploadDirName+"/"+f.getName());
    fis=new FileInputStream(f);
         fo=new FileOutputStream(f1);
                        try
         byte buf[] = new byte[1024*8]; /* declare a 8kB buffer */
         int len = -1;
         while((len = fis.read(buf)) != -1)
         fo.write(buf, 0, len);
                        catch(Exception e)
                                  e.printStackTrace();
                        filepath=f1.getAbsolutePath();
                        request.setAttribute("filepath", filepath);
                        return mapping.findForward("filepath");
    Action-mappings in struts-config.xml
    <action path="/FilePathAction"
                   type="actions.FilePathAction">
                   <forward name="filepath" path="/dummy.jsp"></forward>
              </action>
    and the dummy.jsp code is
    <%=request.getAttribute("filepath")%>

    MESSAGE FROM THE FORUMS ADMINISTRATORS and COMMUNITY
    This thread will be deleted within 24 business hours. You have posted an off-topic question in an area clearly designated for discussions
    about Distributed Real-time Java. Community members looking to help you with your question won't be able to find it in this category.
    Please use the "Search Forums" element on the left panel to locate a forum based on your topic. A more appropriate forum for this post
    could be one of:
    Enterprise Technologies http://forums.sun.com/category.jspa?categoryID=19
    David Holmes

  • Problem acessing KM in Web dynpro for upload a file

    Hello all.
    I have a problem to put a file inside a KM repository. I create a context element like a binary - fileData - and like a String - fileName. and the both code then i will show, I give the same error!!
    please try to help me, in where is my error...
    Code 1:
      public void onActionsavePolitic(com.sap.tc.webdynpro.progmodel.api.IWDCustomEvent wdEvent )
        //@@begin onActionsavePolitic(ServerEvent)
          IPrivatePoliticCreationView.IFilenodeElement fileelement= wdContext.createFilenodeElement();
          wdContext.nodeFilenode().bind(fileelement);
          IWDAttributeInfo attInfo = wdContext.nodeFilenode().getNodeInfo().getAttribute("fileData");
        ISimpleTypeModifiable type = attInfo.getModifiableSimpleType();
          IWDModifiableBinaryType binaryType =(IWDModifiableBinaryType) wdContext.nodeFilenode().getNodeInfo().getAttribute("fileData").getModifiableSimpleType();
          IWDNodeElement element = wdContext.getParentElement();
          String filename = element.getAttributeAsText("fileName");
          if (filename.trim().equals(""))
                return;
          try {
                /*Get an object of current Portal user */
                IWDClientUser wdClientUser = WDClientUser.getCurrentUser();
                com.sap.security.api.IUser sapUser = wdClientUser.getSAPUser();
                com.sapportals.portal.security.usermanagement.IUser ep5User =
                      WPUMFactory.getUserFactory().getEP5User(sapUser);
                       ResourceContext context = new ResourceContext(ep5User);
                /*Give the path to KM in the variable path */
                 String path="/documents/News/";
                 RID rid = RID.getRID(path);
                 IResourceFactory factory =
                 ResourceFactory.getInstance();
                 ICollection folder = (ICollection) factory.getResource(rid,context);
                 //Using the upload element we can upload the files to a location in the server drive
                /*temperory location for writing */
                 String location =      "d:\";
                 String fileName = location+ fileelement.getFileName();
                 File file = new File(fileName);
                /*Create an output stream for writing to the temperory location*/
                 FileOutputStream out = new FileOutputStream(file);
                 out.write(fileelement.getFileData());
                 out.close();
                /*From the temporary location read the file using an input stream*/
                 FileInputStream fin = new FileInputStream(fileName);
                 fin.read();
                /*Using this input stream we can write to the repository
                 Content content = new Content(fileelement.getFiledata(),fileelement.get) */
                 Content content = new Content(fin,"byte", -1);
                 IResource newResource = folder.createResource(fileelement.getFileName(),null, content);
                 fin.close();
                 file.delete();
          } catch (NotSupportedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
          } catch (AccessDeniedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
          } catch (WDUMException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
          } catch (ResourceException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
          } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
          } catch (UserManagementException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
          } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
          } catch (WDRuntimeException e) {
          wdThis.wdGetAPI().getComponent().getMessageManager().reportSuccess(""+e.getMessage());
          }catch (IllegalArgumentException e) {
                wdThis.wdGetAPI().getComponent().getMessageManager().reportSuccess(""+e.getMessage());
        //@@end
    Code 2:
      public void onActionsavePolitic(com.sap.tc.webdynpro.progmodel.api.IWDCustomEvent wdEvent )
        //@@begin onActionsavePolitic(ServerEvent)
          IPrivatePoliticCreationView.IFilenodeElement fileelement= wdContext.createFilenodeElement();
          wdContext.nodeFilenode().bind(fileelement);
          IWDAttributeInfo attInfo = wdContext.nodeFilenode().getNodeInfo().getAttribute("fileData");
          ISimpleTypeModifiable type = attInfo.getModifiableSimpleType();
    IWDModifiableBinaryType binaryType =(IWDModifiableBinaryType) wdContext.nodeFilenode().getNodeInfo().getAttribute("fileData").getModifiableSimpleType();
          IWDNodeElement element = wdContext.getParentElement();
          String filename = element.getAttributeAsText("fileName");
          if (filename.trim().equals(""))
                return;
          try {
                //      Get an object of current Portal user
                IWDClientUser wdClientUser = WDClientUser.getCurrentUser();
                com.sap.security.api.IUser sapUser = wdClientUser.getSAPUser();
                com.sapportals.portal.security.usermanagement.IUser ep5User =
                                 WPUMFactory.getUserFactory().getEP5User(sapUser);
                //       create an ep5 user from the retrieved user
                ResourceContext context = new ResourceContext(ep5User);
                //      Give the path to KM in the variable path
                String repository = "//documents//News//";
                RID rid = RID.getRID(repository);
                IResourceFactory factory = ResourceFactory.getInstance();
                ICollection folder = (ICollection) factory.getResource(rid, context);
                byte[] byteArray =
                      (byte[]) wdContext.currentFilenodeElement().getFileData();
                //      From the temporary location read the file using an input stream
                ByteArrayInputStream fin = new ByteArrayInputStream(byteArray);
                //      Using this input stream we can write to the repository
                Content content =
                      new Content(fin, binaryType.getMimeType().getHtmlMime(), -1L);
                try {
                      IMutablePropertyMap propertyMap = new MutablePropertyMap();
                      IResource newResource =
                            folder.createResource(
                                 wdContext.currentFilenodeElement().getAttributeAsText(
                                 "fileData"),
                                 propertyMap,
                                 content);
                } catch (NameAlreadyExistsException re2) {
                      try {
                            fin = new ByteArrayInputStream(byteArray);
                            content =
                                 new Content(
                                       fin,
                                       binaryType.getMimeType().getHtmlMime(),
                                       -1L);
                            RID fileRid = RID.getRID(repository + filename);
                            IResource fileResource = factory.getResource(fileRid, context);
                            fileResource.updateContent(content);
                      } catch (Exception e) {
                            wdComponentAPI.getMessageManager().reportSuccess(
                                 "File doesn't exist:" + e.getMessage());
                fin.close();
          } catch (Exception e) {
                wdComponentAPI.getMessageManager().reportException(
                      "File not found." + e.getMessage(),
                      true);
          } finally {
                element.setAttributeValue(wdContext.currentFilenodeElement().getFileName(), null);
        //@@end
    and the error then I have in same codes is:
      java.lang.IllegalArgumentException:
        at com.sap.tc.webdynpro.clientserver.data.DataContainer.createLocalPath(DataContainer.java:1347)
        at com.sap.tc.webdynpro.clientserver.data.DataContainer.updateAttribute(DataContainer.java:451)
        at com.sap.tc.webdynpro.clientserver.uielements.adaptbase.AbstractAdapter.updateAttribute(AbstractAdapter.java:644)
        at com.sap.tc.webdynpro.clientserver.uielib.standard.uradapter.FileUploadAdapter.onFILEUPLOADCHANGE(FileUploadAdapter.java:298)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    com.sap.tc.webdynpro.services.exceptions.WDRuntimeException
            at com.sap.tc.webdynpro.clientimpl.html.client.HtmlClient.handleUIElementEvent(HtmlClient.java:957)
            at com.sap.tc.webdynpro.clientimpl.html.client.HtmlClient.updateEventQueue(HtmlClient.java:372)
            at com.sap.tc.webdynpro.clientserver.cal.AbstractClient.prepareTasks(AbstractClient.java:93)
            at com.sap.tc.webdynpro.clientserver.session.ApplicationSession.doProcessing(ApplicationSession.java:294)
            at com.sap.tc.webdynpro.clientserver.session.ClientSession.doApplicationProcessingStandalone(ClientSession.java:707)
            at com.sap.tc.webdynpro.clientserver.session.ClientSession.doApplicationProcessing(ClientSession.java:661)
            at com.sap.tc.webdynpro.clientserver.session.ClientSession.doProcessing(ClientSession.java:229)
            at com.sap.tc.webdynpro.clientserver.session.RequestManager.doProcessing(RequestManager.java:152)
            at com.sap.tc.webdynpro.serverimpl.defaultimpl.DispatcherServlet.doContent(DispatcherServlet.java:62)
            at com.sap.tc.webdynpro.serverimpl.defaultimpl.DispatcherServlet.doPost(DispatcherServlet.java:53)
            at javax.servlet.http.HttpServlet.service(HttpServlet.java:760)
            at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
            at com.sap.engine.services.servlets_jsp.server.HttpHandlerImpl.runServlet(HttpHandlerImpl.java:390)
            at com.sap.engine.services.servlets_jsp.server.HttpHandlerImpl.handleRequest(HttpHandlerImpl.java:264)
            at com.sap.engine.services.httpserver.server.RequestAnalizer.startServlet(RequestAnalizer.java:347)
            at com.sap.engine.services.httpserver.server.RequestAnalizer.startServlet(RequestAnalizer.java:325)
            at com.sap.engine.services.httpserver.server.RequestAnalizer.invokeWebContainer(RequestAnalizer.java:887)
            at com.sap.engine.services.httpserver.server.RequestAnalizer.handle(RequestAnalizer.java:241)
            at com.sap.engine.services.httpserver.server.Client.handle(Client.java:92)
            at com.sap.engine.services.httpserver.server.Processor.request(Processor.java:148)
            at com.sap.engine.core.service630.context.cluster.session.ApplicationSessionMessageListener.process(ApplicationSessionMessageListener.java:33)
            at com.sap.engine.core.cluster.impl6.session.MessageRunner.run(MessageRunner.java:41)
            at com.sap.engine.core.thread.impl3.ActionObject.run(ActionObject.java:37)
            at java.security.AccessController.doPrivileged(Native Method)
            at com.sap.engine.core.thread.impl3.SingleThread.execute(SingleThread.java:100)
            at com.sap.engine.core.thread.impl3.SingleThread.run(SingleThread.java:170)
    Caused by: java.lang.reflect.InvocationTargetException
            at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
            at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
            at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
            at java.lang.reflect.Method.invoke(Method.java:324)
            at com.sap.tc.webdynpro.clientimpl.html.client.HtmlClient.handleUIElementEvent(HtmlClient.java:949)
            ... 25 more
    Caused by: java.lang.IllegalArgumentException:
            at com.sap.tc.webdynpro.clientserver.data.DataContainer.createLocalPath(DataContainer.java:1347)
            at com.sap.tc.webdynpro.clientserver.data.DataContainer.updateAttribute(DataContainer.java:451)
            at com.sap.tc.webdynpro.clientserver.uielements.adaptbase.AbstractAdapter.updateAttribute(AbstractAdapter.java:644)
            at com.sap.tc.webdynpro.clientserver.uielib.standard.uradapter.FileUploadAdapter.onFILEUPLOADCHANGE(FileUploadAdapter.java:298)
            ... 30 more

    Hello
    It looks that I have a similar problem - how could you solve your problem.
    Thanks in advance
    Sascha Fuchs

Maybe you are looking for

  • Can you share iCalander/Address Book with other users and restrict them from seeing certain entries?

    I'm doing some research for my boss concerning iCloud. He would like to setup a way to syncronize iCalender and the Address Book between three users but keep his personal information private. For example, he wants to be able to update his calender fr

  • ITunes and Windows 7 (or Vista) x64

    Hey there, the current state with syncing my iPod under Windows Vista x64 and Windows 7 (RC) x64 is horrible. iTunes locks itself up for several minutes, syncing large Music libraries takes hours - and might break halfway through the progress. It's a

  • Ex rate difference account

    Hi Experts, We are trying to clear open items through Tcode F-03. At the time of saving, the system is throwing error as Ex. rate difference accounts are incomplete for account xxxxx currency XXX. But in all the transaction local currency and account

  • Need Help In Solving Positioning Problem

    Hi Guys, I have a 3 X 3 grid of JLabels of images. I constructed the grid using the grid layout. I would like to move a round object which represents a car and place that object in a particular cell. So the grid will be like a background. My question

  • Attribute onselect invalid for tag selectOneMenu according to TLD

    Hi All I am seeing the error message "Attribute onselect invalid for tag selectOneMenu according to TLD" with html_basic.tld version 1.0 even though the tag and attribute are present in the TLD. The error occurs on Windows XP in Jboss 4.0.2. I don't