File server servlet

Hi all,
I'm writing a servlet which has to serve images/picture's. For instance emoticons.
I found the excellent help from [BalusC : FileServlet|http://balusc.blogspot.com/2007/07/fileservlet.html] The servlet itself works fine (Thank you BalusC)
However it only servers the images from :
$CATALINA_HOME/bin
So if I ask for (for instance) http://localhost:8080/socnet/icons/cool_icon.gif it works only if $CATALINA_HOME/bin/icons/icon_cool.gif
What I want is that this picture is served from the deployed application ($CATALINA_HOME/webapps/socnet/icons/icon_cool.gif)
I can't seem to find how to accomplish this.
So if anyone has any pointers...shoot
Best Regards
maboc

Just to be sure....also the code from the servlet:
public class fileserverservlet extends HttpServlet {
    private static final int DEFAULT_BUFFER_SIZE = 10240;
    private String filepath;
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        filepath = "icons";
        String requestedFile = request.getPathInfo();
        //is er daadwerkeleijk een file gevraagd?
        if (requestedFile == null) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST);
            return;
        //File f = new File(filepath, URLDecoder.decode(requestedFile, "UTF-8"));
        File f = new File("icons/icon_cool.gif");
        if (!f.exists()) {
            System.out.println(f.getAbsoluteFile());
            System.out.println(f.getAbsolutePath());
            System.out.println(f.getCanonicalFile());
            System.out.println(f.getCanonicalPath());
            System.out.println(f.getName());
            System.out.println(f.getParent());
            System.out.println(f.getParentFile());
            System.out.println(f.getPath());
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        String contenttype = getServletContext().getMimeType(f.getName());
        if (contenttype == null) {
            contenttype = "application/octet-stream";
        response.reset();
        response.setBufferSize(DEFAULT_BUFFER_SIZE);
        response.setContentType(contenttype);
        response.setHeader("Content-Length", String.valueOf(f.length()));
        response.setHeader("Content-Disposition", "attachment; filename=\"" + f.getName() + "\"");
        BufferedInputStream input = null;
        BufferedOutputStream output = null;
        try {
            // Open streams.
            input = new BufferedInputStream(new FileInputStream(f), DEFAULT_BUFFER_SIZE);
            output = new BufferedOutputStream(response.getOutputStream(), DEFAULT_BUFFER_SIZE);
            // Write file contents to response.
            byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
            int length;
            while ((length = input.read(buffer)) > 0) {
                output.write(buffer, 0, length);
        } finally {
            // Gently close streams.
            close(output);
            close(input);
    }As you can see I do some checking with a lot of logging whether the file exists.
A bit of the log file :
/home/martijn/apache-tomcat-6.0.26/bin/icons/icon_cool.gif
/home/martijn/apache-tomcat-6.0.26/bin/icons/icon_cool.gif
/home/martijn/apache-tomcat-6.0.26/bin/icons/icon_cool.gif
/home/martijn/apache-tomcat-6.0.26/bin/icons/icon_cool.gif
icon_cool.gif
icons
icons
icons/icon_cool.gif
...I don't have a clue whether the code is wrong or some tomcat startup parameter.

Similar Messages

  • Create a new web application, how shall I update the file server.xml

    Hi,
    I will create a new web application, i.e named newApp. Then I create a file structure as follows:
    - <server-root>/newApp
    - <server-root>/newApp/WEB-INF
    - <server-root>/newApp/WEB-INF/classes
    Then I must tell the server that I have created a new web application. Then I must update my file server.xml, How shall I do this and where in the file shall I type in the new information?
    I use windows XP Pro, and Tomcat 4.1.27.
    My server.xml file looks like below:
    <!-- Example Server Configuration File -->
    <!-- Note that component elements are nested corresponding to their
    parent-child relationships with each other -->
    <!-- A "Server" is a singleton element that represents the entire JVM,
    which may contain one or more "Service" instances. The Server
    listens for a shutdown command on the indicated port.
    Note: A "Server" is not itself a "Container", so you may not
    define subcomponents such as "Valves" or "Loggers" at this level.
    -->
    <Server port="8005" shutdown="SHUTDOWN" debug="0">
    <!-- Comment these entries out to disable JMX MBeans support -->
    <!-- You may also configure custom components (e.g. Valves/Realms) by
    including your own mbean-descriptor file(s), and setting the
    "descriptors" attribute to point to a ';' seperated list of paths
    (in the ClassLoader sense) of files to add to the default list.
    e.g. descriptors="/com/myfirm/mypackage/mbean-descriptor.xml"
    -->
    <Listener className="org.apache.catalina.mbeans.ServerLifecycleListener"
    debug="0"/>
    <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener"
    debug="0"/>
    <!-- Global JNDI resources -->
    <GlobalNamingResources>
    <!-- Test entry for demonstration purposes -->
    <Environment name="simpleValue" type="java.lang.Integer" value="30"/>
    <!-- Editable user database that can also be used by
    UserDatabaseRealm to authenticate users -->
    <Resource name="UserDatabase" auth="Container"
    type="org.apache.catalina.UserDatabase"
    description="User database that can be updated and saved">
    </Resource>
    <ResourceParams name="UserDatabase">
    <parameter>
    <name>factory</name>
    <value>org.apache.catalina.users.MemoryUserDatabaseFactory</value>
    </parameter>
    <parameter>
    <name>pathname</name>
    <value>conf/tomcat-users.xml</value>
    </parameter>
    </ResourceParams>
    </GlobalNamingResources>
    <!-- A "Service" is a collection of one or more "Connectors" that share
    a single "Container" (and therefore the web applications visible
    within that Container). Normally, that Container is an "Engine",
    but this is not required.
    Note: A "Service" is not itself a "Container", so you may not
    define subcomponents such as "Valves" or "Loggers" at this level.
    -->
    <!-- Define the Tomcat Stand-Alone Service -->
    <Service name="Tomcat-Standalone">
    <!-- A "Connector" represents an endpoint by which requests are received
    and responses are returned. Each Connector passes requests on to the
    associated "Container" (normally an Engine) for processing.
    By default, a non-SSL HTTP/1.1 Connector is established on port 8080.
    You can also enable an SSL HTTP/1.1 Connector on port 8443 by
    following the instructions below and uncommenting the second Connector
    entry. SSL support requires the following steps (see the SSL Config
    HOWTO in the Tomcat 4.0 documentation bundle for more detailed
    instructions):
    * Download and install JSSE 1.0.2 or later, and put the JAR files
    into "$JAVA_HOME/jre/lib/ext".
    * Execute:
    %JAVA_HOME%\bin\keytool -genkey -alias tomcat -keyalg RSA (Windows)
    $JAVA_HOME/bin/keytool -genkey -alias tomcat -keyalg RSA (Unix)
    with a password value of "changeit" for both the certificate and
    the keystore itself.
    By default, DNS lookups are enabled when a web application calls
    request.getRemoteHost(). This can have an adverse impact on
    performance, so you can disable it by setting the
    "enableLookups" attribute to "false". When DNS lookups are disabled,
    request.getRemoteHost() will return the String version of the
    IP address of the remote client.
    -->
    <!-- Define a non-SSL Coyote HTTP/1.1 Connector on port 8080 -->
    <Connector className="org.apache.coyote.tomcat4.CoyoteConnector"
    port="8080" minProcessors="5" maxProcessors="75"
    enableLookups="true" redirectPort="8443"
    acceptCount="100" debug="0" connectionTimeout="20000"
    useURIValidationHack="false" disableUploadTimeout="true" />
    <!-- Note : To disable connection timeouts, set connectionTimeout value
    to -1 -->
    <!-- Define a SSL Coyote HTTP/1.1 Connector on port 8443 -->
    <!--
    <Connector className="org.apache.coyote.tomcat4.CoyoteConnector"
    port="8443" minProcessors="5" maxProcessors="75"
    enableLookups="true"
    acceptCount="100" debug="0" scheme="https" secure="true"
    useURIValidationHack="false" disableUploadTimeout="true">
    <Factory className="org.apache.coyote.tomcat4.CoyoteServerSocketFactory"
    clientAuth="false" protocol="TLS" />
    </Connector>
    -->
    <!-- Define a Coyote/JK2 AJP 1.3 Connector on port 8009 -->
    <Connector className="org.apache.coyote.tomcat4.CoyoteConnector"
    port="8009" minProcessors="5" maxProcessors="75"
    enableLookups="true" redirectPort="8443"
    acceptCount="10" debug="0" connectionTimeout="0"
    useURIValidationHack="false"
    protocolHandlerClassName="org.apache.jk.server.JkCoyoteHandler"/>
    <!-- Define an AJP 1.3 Connector on port 8009 -->
    <!--
    <Connector className="org.apache.ajp.tomcat4.Ajp13Connector"
    port="8009" minProcessors="5" maxProcessors="75"
    acceptCount="10" debug="0"/>
    -->
    <!-- Define a Proxied HTTP/1.1 Connector on port 8082 -->
    <!-- See proxy documentation for more information about using this. -->
    <!--
    <Connector className="org.apache.coyote.tomcat4.CoyoteConnector"
    port="8082" minProcessors="5" maxProcessors="75"
    enableLookups="true"
    acceptCount="100" debug="0" connectionTimeout="20000"
    proxyPort="80" useURIValidationHack="false"
    disableUploadTimeout="true" />
    -->
    <!-- Define a non-SSL legacy HTTP/1.1 Test Connector on port 8083 -->
    <!--
    <Connector className="org.apache.catalina.connector.http.HttpConnector"
    port="8083" minProcessors="5" maxProcessors="75"
    enableLookups="true" redirectPort="8443"
    acceptCount="10" debug="0" />
    -->
    <!-- Define a non-SSL HTTP/1.0 Test Connector on port 8084 -->
    <!--
    <Connector className="org.apache.catalina.connector.http10.HttpConnector"
    port="8084" minProcessors="5" maxProcessors="75"
    enableLookups="true" redirectPort="8443"
    acceptCount="10" debug="0" />
    -->
    <!-- An Engine represents the entry point (within Catalina) that processes
    every request. The Engine implementation for Tomcat stand alone
    analyzes the HTTP headers included with the request, and passes them
    on to the appropriate Host (virtual host). -->
    <!-- You should set jvmRoute to support load-balancing via JK/JK2 ie :
    <Engine name="Standalone" defaultHost="localhost" debug="0" jmvRoute="jvm1">
    -->
    <!-- Define the top level container in our container hierarchy -->
    <Engine name="Standalone" defaultHost="localhost" debug="0">
    <!-- The request dumper valve dumps useful debugging information about
    the request headers and cookies that were received, and the response
    headers and cookies that were sent, for all requests received by
    this instance of Tomcat. If you care only about requests to a
    particular virtual host, or a particular application, nest this
    element inside the corresponding <Host> or <Context> entry instead.
    For a similar mechanism that is portable to all Servlet 2.3
    containers, check out the "RequestDumperFilter" Filter in the
    example application (the source for this filter may be found in
    "$CATALINA_HOME/webapps/examples/WEB-INF/classes/filters").
    Request dumping is disabled by default. Uncomment the following
    element to enable it. -->
    <!--
    <Valve className="org.apache.catalina.valves.RequestDumperValve"/>
    -->
    <!-- Global logger unless overridden at lower levels -->
    <Logger className="org.apache.catalina.logger.FileLogger"
    prefix="catalina_log." suffix=".txt"
    timestamp="true"/>
    <!-- Because this Realm is here, an instance will be shared globally -->
    <!-- This Realm uses the UserDatabase configured in the global JNDI
    resources under the key "UserDatabase". Any edits
    that are performed against this UserDatabase are immediately
    available for use by the Realm. -->
    <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
    debug="0" resourceName="UserDatabase"/>
    <!-- Comment out the old realm but leave here for now in case we
    need to go back quickly -->
    <!--
    <Realm className="org.apache.catalina.realm.MemoryRealm" />
    -->
    <!-- Replace the above Realm with one of the following to get a Realm
    stored in a database and accessed via JDBC -->
    <!--
    <Realm className="org.apache.catalina.realm.JDBCRealm" debug="99"
    driverName="org.gjt.mm.mysql.Driver"
    connectionURL="jdbc:mysql://localhost/authority"
    connectionName="test" connectionPassword="test"
    userTable="users" userNameCol="user_name" userCredCol="user_pass"
    userRoleTable="user_roles" roleNameCol="role_name" />
    -->
    <!--
    <Realm className="org.apache.catalina.realm.JDBCRealm" debug="99"
    driverName="oracle.jdbc.driver.OracleDriver"
    connectionURL="jdbc:oracle:thin:@ntserver:1521:ORCL"
    connectionName="scott" connectionPassword="tiger"
    userTable="users" userNameCol="user_name" userCredCol="user_pass"
    userRoleTable="user_roles" roleNameCol="role_name" />
    -->
    <!--
    <Realm className="org.apache.catalina.realm.JDBCRealm" debug="99"
    driverName="sun.jdbc.odbc.JdbcOdbcDriver"
    connectionURL="jdbc:odbc:CATALINA"
    userTable="users" userNameCol="user_name" userCredCol="user_pass"
    userRoleTable="user_roles" roleNameCol="role_name" />
    -->
    <!-- Define the default virtual host -->
    <Host name="localhost" debug="0" appBase="webapps"
    unpackWARs="true" autoDeploy="true">
    <!-- Normally, users must authenticate themselves to each web app
    individually. Uncomment the following entry if you would like
    a user to be authenticated the first time they encounter a
    resource protected by a security constraint, and then have that
    user identity maintained across all web applications contained
    in this virtual host. -->
    <!--
    <Valve className="org.apache.catalina.authenticator.SingleSignOn"
    debug="0"/>
    -->
    <!-- Access log processes all requests for this virtual host. By
    default, log files are created in the "logs" directory relative to
    $CATALINA_HOME. If you wish, you can specify a different
    directory with the "directory" attribute. Specify either a relative
    (to $CATALINA_HOME) or absolute path to the desired directory.
    -->
    <!--
    <Valve className="org.apache.catalina.valves.AccessLogValve"
    directory="logs" prefix="localhost_access_log." suffix=".txt"
    pattern="common" resolveHosts="false"/>
    -->
    <!-- Logger shared by all Contexts related to this virtual host. By
    default (when using FileLogger), log files are created in the "logs"
    directory relative to $CATALINA_HOME. If you wish, you can specify
    a different directory with the "directory" attribute. Specify either a
    relative (to $CATALINA_HOME) or absolute path to the desired
    directory.-->
    <Logger className="org.apache.catalina.logger.FileLogger"
    directory="logs" prefix="localhost_log." suffix=".txt"
    timestamp="true"/>
    <!-- Define properties for each web application. This is only needed
    if you want to set non-default properties, or have web application
    document roots in places other than the virtual host's appBase
    directory. -->
         <DefaultContext reloadable="true"/>
    <!-- Tomcat Root Context -->
    <Context path="" docBase="ROOT" debug="0"/>
    <!-- Tomcat Examples Context -->
    <Context path="/examples" docBase="examples" debug="0"
    reloadable="true" crossContext="true">
    <Logger className="org.apache.catalina.logger.FileLogger"
    prefix="localhost_examples_log." suffix=".txt"
    timestamp="true"/>
    <Ejb name="ejb/EmplRecord" type="Entity"
    home="com.wombat.empl.EmployeeRecordHome"
    remote="com.wombat.empl.EmployeeRecord"/>
    <!-- If you wanted the examples app to be able to edit the
    user database, you would uncomment the following entry.
    Of course, you would want to enable security on the
    application as well, so this is not done by default!
    The database object could be accessed like this:
    Context initCtx = new InitialContext();
    Context envCtx = (Context) initCtx.lookup("java:comp/env");
    UserDatabase database =
    (UserDatabase) envCtx.lookup("userDatabase");
    -->
    <!--
    <ResourceLink name="userDatabase" global="UserDatabase"
    type="org.apache.catalina.UserDatabase"/>
    -->
    <!-- PersistentManager: Uncomment the section below to test Persistent
    Sessions.
    saveOnRestart: If true, all active sessions will be saved
    to the Store when Catalina is shutdown, regardless of
    other settings. All Sessions found in the Store will be
    loaded on startup. Sessions past their expiration are
    ignored in both cases.
    maxActiveSessions: If 0 or greater, having too many active
    sessions will result in some being swapped out. minIdleSwap
    limits this. -1 or 0 means unlimited sessions are allowed.
    If it is not possible to swap sessions new sessions will
    be rejected.
    This avoids thrashing when the site is highly active.
    minIdleSwap: Sessions must be idle for at least this long
    (in seconds) before they will be swapped out due to
    activity.
    0 means sessions will almost always be swapped out after
    use - this will be noticeably slow for your users.
    maxIdleSwap: Sessions will be swapped out if idle for this
    long (in seconds). If minIdleSwap is higher, then it will
    override this. This isn't exact: it is checked periodically.
    -1 means sessions won't be swapped out for this reason,
    although they may be swapped out for maxActiveSessions.
    If set to >= 0, guarantees that all sessions found in the
    Store will be loaded on startup.
    maxIdleBackup: Sessions will be backed up (saved to the Store,
    but left in active memory) if idle for this long (in seconds),
    and all sessions found in the Store will be loaded on startup.
    If set to -1 sessions will not be backed up, 0 means they
    should be backed up shortly after being used.
    To clear sessions from the Store, set maxActiveSessions, maxIdleSwap,
    and minIdleBackup all to -1, saveOnRestart to false, then restart
    Catalina.
    -->
    <!--
    <Manager className="org.apache.catalina.session.PersistentManager"
    debug="0"
    saveOnRestart="true"
    maxActiveSessions="-1"
    minIdleSwap="-1"
    maxIdleSwap="-1"
    maxIdleBackup="-1">
    <Store className="org.apache.catalina.session.FileStore"/>
    </Manager>
    -->
    <Environment name="maxExemptions" type="java.lang.Integer"
    value="15"/>
    <Parameter name="context.param.name" value="context.param.value"
    override="false"/>
    <Resource name="jdbc/EmployeeAppDb" auth="SERVLET"
    type="javax.sql.DataSource"/>
    <ResourceParams name="jdbc/EmployeeAppDb">
    <parameter><name>username</name><value>sa</value></parameter>
    <parameter><name>password</name><value></value></parameter>
    <parameter><name>driverClassName</name>
    <value>org.hsql.jdbcDriver</value></parameter>
    <parameter><name>url</name>
    <value>jdbc:HypersonicSQL:database</value></parameter>
    </ResourceParams>
    <Resource name="mail/Session" auth="Container"
    type="javax.mail.Session"/>
    <ResourceParams name="mail/Session">
    <parameter>
    <name>mail.smtp.host</name>
    <value>localhost</value>
    </parameter>
    </ResourceParams>
    <ResourceLink name="linkToGlobalResource"
    global="simpleValue"
    type="java.lang.Integer"/>
    </Context>
    </Host>
    </Engine>
    </Service>
    </Server>

    To use servlets u have indeed to update your web.xml...Well I'm not sure this is relevant to your case anyway.
    You have to add a <servlet> element to this file.
    Something like this:
    <servlet>
    <servlet-name>blabla</servlet-name>
    <servlet-class>blablapackage.Blablaclass</servlet-class>
    <init-param>...</init-param>
    </servlet>
    Now this may not solve your problem. Make sure you refer to your servlets using their full qualified names.btw, just to be sure, what is your definition of "servlet"? (i mean: any java class or only javax.servlet.Servlet)

  • Pointing KM to our file server

    Hi folks,
    We have recently setup a portal prototype and I have got KM working with the folders that exist on the portal server.  My question is can I point the KM to our file server that exists on our network?  Assuming I can do this, does the Check-in and Check-out/document locking functionality reside on the portal and could users therefore circumvent the security by going directly to the file server instead of the portal?
    Thanks for any help you can provide!
    -Patrick

    Hi Patrick,
    you can access the filesystem by creating a CM repository in FSDB mode or a Filesystem repository. Here is a link to
    some howto Guide for creating CM repositories:
    <a href="http://www.sdn.sap.com/irj/servlet/prt/portal/prtroot/com.sap.km.cm.docs/library/kmc/Creating%20a%20">http://www.sdn.sap.com/irj/servlet/prt/portal/prtroot/com.sap.km.cm.docs/library/kmc/Creating%20a%20</a>
    The locking is supported by the CM repository, but only KM internally. If the user accesses the file from the filesystem, he can change the document content even if the file is locked in KM. I would also propose to deny access on filesystem level after integrating it into KM.
    Regards
    Lars

  • 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, ...

  • Problem to include java script file in servlet

    I couldn’t use any functions included in java servlet file using servlet. I made a test in jsp and it work fine but in servlet not.
    Here my code
    out.println("<jsp:include page=\"C:/path/file.js\" flush=\"true\" />");
         or          
         out.println("<script language=\"javascript\" src=\"c:/path/file.js\">");
    Although was no error but using both didn’t let me use any function inside the java script file. As I said using the same command in JSP works fine.
    How I can include the file.js correctly ?

    [email protected] wrote:
    server machineOK, imagine that I am the server and you are the client.
    I have a file "c:/documents and settings/balusc/passwords.txt".
    So now you have the path. Can you tell me the contents of the file?

  • Getting tld file in servlet.

    hi all,
    now we cannot declare alias for tag lib tld in web.xml.so server will take tld from jar file which is there lib.
    i want access these tld file in servlet. can any body tell how to get it.
    thanks in advance...

    You could also use jsp, which provides you with JAVA functionality, however, omitting the printing. Here's an example:
    <%@ page contentType="text/html; charset=ISO-8859-5" %>
    <%
         String name = request.getParameter("name");
    %>
    <html>
    <header>
    </header>
    <body>
    <p><%=name %></p>
    </body>
    </html>

  • How to submit pdf xml data to a file server

    Hi, I am hoping someone can help me. I have created a dynamic pdf in livecycle designer ES, which appears as the requester wants it to. I now just need to work out how to collect the submitted data. Is it possible to submit the xml data to a file server? I have succeeded in emailing the data, but each response is separate xml attachment and would then need to collated, etc. It would be preferable to submit the data directly to a file server if this is possible. Even if it submitted into a database or something. From everything I have read so far, it seems that this is not possible, unless I am missing something. As a newbie to this, any assistance would be much appreciated. Thank you.

    You can submit the data as XML or URL-encoded data (HTTP POST). In either case you will need to have a server-side process to receive and parse the data stream. The server-side process may be a JSP, a servlet, PHP or any technology that can manage HTTP requests/responses.
    See About submitting data using a button at http://help.adobe.com/en_US/livecycle/9.0/designerHelp/000330.html .
    Steve

  • Testing the windows file server documents in KM

    Hi all,
       I have configured WINDOWS as file server in KM.
       After configuring i should be able to share or access the docuemnts from the WINDOWS in KM
       How should i test WINDOWS documents in KM.ie., where can i find all the documents from WINDOWS in order to access it.
    Is it in the ROOT folder of the KM Content in Content administration or somewhere else?
    thanks in advance.
    Regards
    Sireesha.

    Hi,
      I have configured WINDOWS as file server in the following way.
      1.  Created a WINDOWS  system in the system land scape.
      2.  Configured servlet Engine User .
      3.  Created a Network path
      4.  Configured a File repository in the Content Management
      5.   User mapping is  done.
      Now my doubt is where should i go and check the WINDOWS documents or files after configuring it.
    Do v need to do anything else to get the all the files which are in WINDOWS.
    Pls guide me.
    Thanks in advance.
    Regards
    Sireesha.

  • Why the serving servlet start to download on another server

    Dear All,
    i am trying to upload the file to database from a individual jsp(upload.jsp). which is calling the Servlet(FileUploadServlet) which return the attachment no which i updated with my other data to database.
    it is working fine on apache serverBut as i tried this code on Oracle App Server 10gR2 which is my actual implementaion server.it's working fine accept one thing it also give me the screen which says to save or cancel the FileUploadServletPlease suggest me why this is being happeningyou can also review the code.
    Regards,
    Manoj Rajput

    //upload.jsp
    <%@ page contentType="text/html;charset=iso-8859-1" language="java" import="java.sql.*" errorPage="" %>
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <title>Ajax File Upload</title>
    <script language="javascript">
    var max_no=0;
    var req;
    function ajaxFunction()
       var url = "../servlet/FileUploadServlet";
       if (window.XMLHttpRequest)        // Non-IE browsers
          req = new XMLHttpRequest();
          req.onReadyStateChange = processStateChange;
          try
             req.open("GET", url, true);
          catch (e)
                alert(e);
          req.send(null);
       else if (window.ActiveXObject)    // IE Browsers
          req = new ActiveXObject("Microsoft.XMLHTTP");
          if (req)
                 req.onReadyStateChange = processStateChange;
                req.open("GET", url, true);
                req.send();
    function processStateChange()
       if (req.readyState == 4)
          if (req.status == 200) // OK response
              //alert(req.responseText);
              max_no=req.responseText;
          else
                alert(req.statusText);
    function show(va)
         if(va=="unloading")
              window.opener.document.forms['regis'].elements['temp'].value=max_no;
    </script>
    </head>
    <body onLoad="show('loading');" onUnload="show('unloading');">
        <form id="myForm" enctype="multipart/form-data" method="POST" action="../servlet/FileUploadServlet" onSubmit="ajaxFunction()">
       <input type="file" name="txtFile" id="txtFile" /><br />
       <input type="submit" id="submitID" name="submit" value="Upload" />
    </form>
    <img id="Wait_Image" displayafter="1" src="images/11.gif" mce_src="images/11.gif" style="cursor:pointer;visibility:hidden; ">
    </div>
    </body>
    </html>
    //FileUploadServlet
    //both these package name are commented because jsp was not able to get them on the path so i use this directlly from root
    //package com.psclistens.ajax.fileupload;
    package wflow;
    import javax.servlet.Servlet;
    import javax.servlet.http.HttpServlet;
    import java.io.File;
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.util.Iterator;
    import java.util.List;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    import org.apache.commons.fileupload.FileItem;
    import org.apache.commons.fileupload.FileItemFactory;
    import org.apache.commons.fileupload.FileUploadException;
    import org.apache.commons.fileupload.disk.DiskFileItemFactory;
    import org.apache.commons.fileupload.servlet.ServletFileUpload;
    import java.sql.*;
    import oracle.sql.*;
    import java.io.*;
    * This is a File Upload Servlet that is used with AJAX
    * to monitor the progress of the uploaded file.
    public class FileUploadServlet      extends HttpServlet implements Servlet
         private static final long serialVersionUID = 2740693677625051632L;
         protected int max_no=0;
         protected String msg="";
         protected String  contype="";
         public FileUploadServlet()
         super();
       protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
              response.setContentType("text/plain;charset=Big5");
              response.setHeader("Pragma", "No-cache");
              response.setHeader("Cache-Control", "No-cache");     
              doPost(request,response);
             PrintWriter out = response.getWriter();
              out.println(msg);
              out.flush();
              out.close();
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
              // create file upload factory and upload servlet
              FileItemFactory factory = new DiskFileItemFactory();
              ServletFileUpload upload = new ServletFileUpload(factory);
              Connection con=null;
              oracle.sql.BLOB myBlob = null;
              PreparedStatement pstmt=null;
              Statement stmt=null;
              ResultSet rs=null;
              List uploadedItems = null;
              FileItem fileItem = null;
              try{
              Class.forName("oracle.jdbc.driver.OracleDriver");
              con=DriverManager.getConnection("jdbc:oracle:thin:@10.129.1.14:1521:igfl","intrappsx","intrappsx");
              stmt=con.createStatement();
              String query="SELECT nvl(max(sugg_no),0)+1 FROM temp_attach";
              rs=stmt.executeQuery(query);
              rs.next();
              max_no=rs.getInt(1);
              msg="";
              msg=String.valueOf(max_no);
              }catch(Exception e){}
              try
                   // iterate over all uploaded files
                   uploadedItems = upload.parseRequest(request);
                   Iterator i = uploadedItems.iterator();
                   while (i.hasNext())
                        fileItem = (FileItem) i.next();
                        if (fileItem.isFormField() == false)
                             if (fileItem.getSize() > 0)
                                  File uploadedFile = null;
                                  String myFullFileName = fileItem.getName(),myFileName = "",slashType = (myFullFileName.lastIndexOf("\\") > 0) ? "\\" : "/"; // Windows or UNIX
                                  int startIndex = myFullFileName.lastIndexOf(slashType);
                                  // Ignore the path and get the filename
                                  myFileName = myFullFileName.substring(startIndex + 1, myFullFileName.length());                              
                                  myBlob = oracle.sql.BLOB.createTemporary(con, false, oracle.sql.BLOB.DURATION_SESSION);
                                   InputStream f_in = fileItem.getInputStream();
                                  byte buffer[]=new byte[myBlob.getBufferSize()];
                                   while(f_in.read(buffer)>0)
                                       myBlob.putBytes(myBlob.length()+1,buffer);     
                                  if(myBlob!=null && !(myBlob.equals("null")) &&  !(myBlob.equals("")))
                                             String     query2 = "insert into temp_attach(SUGG_NO, ATTACHMENT, ATT_TYP, CREAT_USR_ID,file_name, CREAT_DT) values(?,?,?,?,?,sysdate)";               
                                             pstmt = con.prepareStatement(query2);               
                                              pstmt.setInt(1,max_no);               
                                               pstmt.setBlob(2, (java.sql.Blob)myBlob);
                                             //pstmt.setBinaryStream(2,f_in,(int)(new File(myFileName)).length());
                                             contype=fileItem.getContentType();
                                             if(contype.equals("application/x-zip-compressed"));
                                                  contype="application/x-zip";
                                             pstmt.setString(3,contype);
                                             pstmt.setString(4,"3133");
                                             pstmt.setString(5,myFileName);
                                                int h=pstmt.executeUpdate();
              catch (FileUploadException e)
                   e.printStackTrace();
              catch (Exception e)
                   e.printStackTrace();
    }

  • Session tracking for File Upload Servlet

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

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

  • Configure EP6SP9 KM in a file server instead of KM Database

    Hi All,
    We are at EP6SP9 in Windows 2003.
    As a part of my user requirment, I need to set up all my KM folders in a file repository and not in KM Database. The users would view this folders as KM Folders and need to utilise all the facilities offered by KM like Versioning, subscription and notification.
    I need to also integrate the central ADS Server as the user management engine (Windows Authentication) so that all the users automatically logon to the portal when they log-on to the system.TREX also has to index through this documents in the file server.
    Need some advice on the same.
    1) I have seen a document entitled "Integration of Windows File Services into SAP KM Platform using SSO and WebDAV Repository Manager". Is this the one that I have to use for setting the system up or any other suggestions. Has anyone tried connecting KM to an file server Database.
    2) Can I utilise all the KM Functionalities with the documents and folders residing in a file server.
    Would love to interact with anyone who has worked on the same.
    Regards,
    Rajan.K

    There's already lots of information on the subject right here on SDN. Here are a few pointers to get you started:
    CM repository documentation in SAP Help:
    http://help.sap.com/saphelp_nw04/helpdata/en/62/468698a8e611d5993600508b6b8b11/content.htm
    Weblog with step-by-step instructions on creating an FSDB repository:
    Creating a CM Repository Manager - FSDB
    I basically just followed the weblog and it worked. In fact, some steps in the weblog are not necessary if you intend to use the default "documents" repository. In that case, just switch to FSDB persistence mode, add your network paths and it should work after restarting the engine.
    Note that the contents of your repository will be deleted once you switch unless you backup your files to the FSDB root prior to that.
    Hope this helps.

  • How to mirror file server?

    I run a small office network with Mac OS X Server 10.4.x doing various services including AFP. My wife and I also work from home and we would like to be able to access remotely various files which are held on the server.
    We can do this over the internet, but the connections are not too quick. Ideally I would like to be able to run a mirrored copy of the file server on a little server at home, so that we can access the files locally and then have the servers keep each other up to date across the internet.
    Is this possible?
    TIA
    James

    Can anybody help me with this?
    TIA

  • Changed laptops, now iTunes can't find my music on my file server

    Ok, here's what happened when I recently switched laptops
    - I use iTunes to point to the music I store on my file server via a network share (WinXP)
    - I manually manage my iTunes folders
    - I took the \My Documents\My Music\iTunes directory from my old laptop and copied it to the same location to my new laptop
    - Installed iTunes 9 on the new laptop
    - When iTunes9 loaded on the new laptop ALMOST all music files in my library loaded with an exclamation point indicating that it couldn't locate the file (even though the file locations never changed)
    Ok... so here's the problem. I have over 20,000 songs with ratings information and if I just re-add all the files from the network share to the iTunes library again then it looks like I'd lose those ratings.
    The only way that I can see to fix things is to individually point iTunes to the network share location of the file for each file... YUCK!
    Is there a script or something I can write to tell it to find these files, or at least copy the ID3 tags to the duplicated songs that I re-added from the network share.
    Any help is GREATLY appreciated!

    Something is different in the paths to the files....hence itunes cannot find them.
    Sound like you know about the ITL file, which is why you copied it over.
    What you can do is look in its companion XML file to see the paths itunes thinks it should be using.
    If your XML is really big, open it using WordPad instead of NotePad. About the 10th line down is the itunes preference setting for the itunes folder:
    key>Music Folder</key><string>file://localhost/K:/iTunes%20Music/</string>
    On my system it's K:/iTunes Music
    The %20 just indicates a space.
    Then each song will have its own path
    <key>Location</key><string>file://localhost/K:/iTunes%20Music/Cowboy%20Junkies/The%20Trinity%20Session/07%2 0200%20More%20Miles.mp3</string>
    Now....can you see ANYTHING funny in one of those song paths?Is there an extra space, a different user name, anything different than what you could browse to in Windows Explorer?

  • File Server Role: Slow access for "opened files" and slow Explorer browsing

    Since we migrated our fileserver from Windows Server 2008 R2 to Windows Server 2012 we are facing two major problems:
    1. Opening files which are already opened by other users takes about 1 minute before the file actually opens. This is not only for Office files such as Excel and Word, but also for other (not office) files. Again, this problem only rises when the file(s)
    is/are already opened by another user. There seems to be a sort of "Lock" check time which is about 45 to 60 seconds.
    2. The other problem is browsing via Explorer through the network drive (all clients are Windows 7 clients). Half of the time there is some kind of "hick up" with displaying the results of the folder. I cannot figure out a patern, but if there
    is no "hick up" then browsing is very fast (also in the busiest times of the working day)... If there is a "hick up" the result can take about 50 seconds to display the content of a folder.
    I suspect the SMB implementation / settings of Windows Server 2012 which are causing the problems...
    Things I tried:
    1. Changed the Oplocks wait time to 10 seconds (which is the minimum). The result is that openening files does indeed go some faster (still taking about 45 seconds).
    2. Disabled SMB2: the result is that browsing is fast... Opening files does go faster. BUT: we are then facing other problems like some files are not able to open... This setting was, after getting a lot of complaints from the users, changed back to enabled
    SMB2.
    3. Within the NIC card properties I disabled "QoS packet Scheduler", "Link-Layer Topology Discovery Mapper I/O Driver", "Link-Layer Topology Discovery Responder" and IPv6 (as we only use IPv4).
    All above with not the promising results.
    The server is a dedicated (virtual machine on vSphere 5.1) fileserver.
    Please Advice since this is not workable, and we have postponed the migration of the fileserver for our aother location.

    Hi Dave,
    I suggest you disable all third party applications like Anti-Virus application to test if it could reduce the waiting time when accessing a file.
    Here are some related threads below that could be useful to you:
    DFS Slowness when Opening Microsoft Documents and Excel Spreadsheets
    http://social.technet.microsoft.com/Forums/windowsserver/en-US/61ec9a99-0027-44cb-815c-0da9276c1c96/dfs-slowness-when-opening-microsoft-documents-and-excel-spreadsheets?forum=winservergen
    Opening files over network takes long time
    http://social.technet.microsoft.com/Forums/windows/en-US/c8ddb65f-8a17-4cee-afd4-dfc09e99d562/opening-files-over-network-takes-long-time?forum=w7itpronetworking
    opening folder or file takes over a minute on Windows 2008R2 File server
    http://social.technet.microsoft.com/Forums/windowsserver/en-US/b9aa98c4-3ef7-4e6d-810d-6099e72b33f6/opening-folder-or-file-takes-over-a-minute-on-windows-2008r2-file-server?forum=winserverfiles
    Best Regards,
    Amy Wang

  • File server-Help!

    Hello Everyone,
    My program not working when sceduled to run in background, but works fine when run in foreground. Think i need to change some funcution modules as the ones i used are, think, referencing for foreground processing. Can anyone point to some function modules which does the job for me.
    I am picking up the files from file server.
    REPORT  zco11n
            NO STANDARD PAGE HEADING
            LINE-SIZE 255.
    INCLUDE zdeclerations.          " Data Declarations part
    *---------------Get actual filepath from logical filepath---------------------*
    CALL FUNCTION 'FILE_GET_NAME'
      EXPORTING
    *   CLIENT                        = SY-MANDT
        logical_filename              = 'ZBARCODE_APPLICATION'    "logical path
    IMPORTING
       file_name                     = pa_file                     "actual path
    EXCEPTIONS
       file_not_found                = 1
       OTHERS                        = 2
    IF sy-subrc <> 0.
      MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno
              WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
    ENDIF.
    *---------------Get all the required files from the directory-------------------*
    CALL FUNCTION 'TMP_GUI_DIRECTORY_LIST_FILES'
      EXPORTING
        directory  = pa_file                         "Directory path
        filter     = '*.CSV'
      TABLES
        file_table = lt_file                        "Files in the direcory
        dir_table  = lt_dir
      EXCEPTIONS
        cntl_error = 1
        OTHERS     = 2.
    IF sy-subrc <> 0.
      MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno
              WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
    ENDIF.
    *-------Get the directory and file name as single path & move to internal table----*
    LOOP AT lt_file INTO lw_file.
      CONCATENATE pa_file  lw_file-pathname INTO lstring.
      MOVE lstring TO lw_filename-pathname.
      MOVE lw_file-pathname TO lw_filename-filename.
      APPEND  lw_filename TO lt_filename.
      CLEAR lw_filename.
      CLEAR lw_file.
    ENDLOOP.
    START-OF-SELECTION.
      LOOP AT lt_filename  INTO lw_filename.
        file_name = lw_filename-pathname.
    *-------Read the contents of the file to an internal table--------------------------*
        CALL FUNCTION 'DX_FILE_READ'
          EXPORTING
            filename          = file_name
            pc                = 'X'
          TABLES
            data_tab          = lt_temp                            "File contents
          EXCEPTIONS
            no_file_on_server = 1
            no_data_on_server = 2
            gui_upload_failed = 3
            no_authority      = 4
            OTHERS            = 5.
        IF sy-subrc <> 0.
          MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno
                  WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
        ELSE.
    *-------------Split and move the contents as required for BDC---------------*
          LOOP AT lt_temp INTO lw_temp.
            SPLIT lw_temp AT ',' INTO lw_afrud-aufnr lw_afrud-lmnga lw_afrud-budat.
            APPEND lw_afrud TO lt_afrud.
          ENDLOOP.
    ************----------Start Of BDC-----------------------***************
          LOOP AT lt_afrud INTO lw_afrud.
            PERFORM bdc_dynpro      USING 'SAPLCORU_S' '0100'.
            PERFORM bdc_field       USING 'BDC_OKCODE'
                                          '/00'.
            PERFORM bdc_field       USING 'AFRUD-AUFNR'
                                           lw_afrud-aufnr.
            PERFORM bdc_field       USING 'AFRUD-LMNGA'
                                          '1'.
            PERFORM bdc_field       USING 'AFRUD-ISDZ'
                                          '00:00:00'.
            PERFORM bdc_field       USING 'AFRUD-IEDZ'
                                          '00:00:00'.
            PERFORM bdc_field       USING 'AFRUD-PEDZ'
                                          '00:00:00'.
            PERFORM bdc_field       USING 'BDC_CURSOR'
                                          'AFRUD-BUDAT'.
            PERFORM bdc_field       USING 'AFRUD-BUDAT'
                                          lw_afrud-budat.
            PERFORM bdc_dynpro      USING 'SAPLCORU_S' '0100'.
            PERFORM bdc_field       USING 'BDC_OKCODE'
                                          '=BU'.
            CALL TRANSACTION 'CO11N' USING lt_bdcdata MODE 'N'
            UPDATE 'S' MESSAGES INTO lt_bdcmsgcoll.          "#EC CI_CALLTA
          ENDLOOP.
    *******-----------End of BDC-------------------------------------*******
          CLEAR lw_afrud.
          REFRESH lt_afrud.
    ************************File Manipulations*********************
          lv_file_name = lw_filename-filename.                     "Assign the filename to a local variable
          CONCATENATE '\CAUVERYSAPBARCODESUCCESS'
                          lv_file_name INTO lstring_success.       "Place holder for BDC Success Files
          CONCATENATE '\CAUVERYSAPBARCODEERROR'
                          lv_file_name INTO lstring_error.         "Place holder for BDC Error Files
          file_name_source = file_name.                            "Source file path
          file_name_success_dest = lstring_success.                "Success file path
          file_name_error_dest = lstring_error.                    "Error file path
    *For the files with no data in them, move them to desired(error) folder.
          if lt_bdcmsgcoll[] is initial.
            CALL METHOD cl_gui_frontend_services=>file_copy
              EXPORTING
                SOURCE               = file_name_source
                destination          = file_name_error_dest.
            endif.
          LOOP AT lt_bdcmsgcoll INTO lw_bdcmsgcoll.
            IF lw_bdcmsgcoll-msgtyp EQ 'S' AND
                lw_bdcmsgcoll-msgnr EQ '110'.
    *----------Move the succes files to designated folder---------------*.
              CALL METHOD cl_gui_frontend_services=>file_copy
                EXPORTING
                  SOURCE               = file_name_source
                  DESTINATION          = file_name_success_dest
                  overwrite            = 'X'
                EXCEPTIONS
                  cntl_error           = 1
                  error_no_gui         = 2
                  wrong_parameter      = 3
                  disk_full            = 4
                  access_denied        = 5
                  file_not_found       = 6
                  destination_exists   = 7
                  unknown_error        = 8
                  path_not_found       = 9
                  disk_write_protect   = 10
                  drive_not_ready      = 11
                  not_supported_by_gui = 12
                  OTHERS               = 13.
              IF sy-subrc <> 0.
                MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno
                           WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
              ENDIF.
            ELSE.
    *--------Move the error files to designated folder-----------------*.
              IF  lw_bdcmsgcoll-msgtyp EQ 'E' OR
                  lt_bdcmsgcoll[] IS INITIAL.
                CALL METHOD cl_gui_frontend_services=>file_copy
                  EXPORTING
                    SOURCE               = file_name_source
                    DESTINATION          = file_name_error_dest
                    overwrite            = 'X'
                  EXCEPTIONS
                    cntl_error           = 1
                    error_no_gui         = 2
                    wrong_parameter      = 3
                    disk_full            = 4
                    access_denied        = 5
                    file_not_found       = 6
                    destination_exists   = 7
                    unknown_error        = 8
                    path_not_found       = 9
                    disk_write_protect   = 10
                    drive_not_ready      = 11
                    not_supported_by_gui = 12
                    OTHERS               = 13.
                IF sy-subrc <> 0.
                  MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno
                             WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
                ENDIF.
              ENDIF.
            ENDIF.
          ENDLOOP.
    *----------------Delete file from the directory---------------------------*
          CALL METHOD cl_gui_frontend_services=>file_delete
            EXPORTING
              filename             = file_name_source
            CHANGING
              rc                   = lv_rc
            EXCEPTIONS
              file_delete_failed   = 1
              cntl_error           = 2
              error_no_gui         = 3
              file_not_found       = 4
              access_denied        = 5
              unknown_error        = 6
              not_supported_by_gui = 7
              wrong_parameter      = 8
              OTHERS               = 9.
          IF sy-subrc <> 0.
            MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno
                       WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
          ENDIF.
        ENDIF.
        REFRESH lt_bdcmsgcoll.
        REFRESH lt_bdcdata.
      ENDLOOP.
    *&      Form  bdc_dynpro
    *       text
    *      -->PROGRAM    text
    *      -->DYNPRO     text
    FORM bdc_dynpro USING program  dynpro.                      "#EC *
      CLEAR lw_bdcdata.
      lw_bdcdata-program  = program.
      lw_bdcdata-dynpro   = dynpro.
      lw_bdcdata-dynbegin = 'X'.
      APPEND lw_bdcdata TO lt_bdcdata.
    ENDFORM.                    "BDC_DYNPRO
    *&      Form  bdc_field
    *       text
    *      -->FNAM       text
    *      -->FVAL       text
    FORM bdc_field USING fnam fval.                             "#EC *
      IF fval <> space.
        CLEAR lw_bdcdata.
        lw_bdcdata-fnam = fnam.
        lw_bdcdata-fval = fval.
        APPEND lw_bdcdata TO lt_bdcdata.
      ENDIF.
    ENDFORM.                    "bdc_field
    *&  Include           ZDECLERATIONS
    *-----------------------------Types decleration--------------------------*
    TYPES: BEGIN OF tw_afrud,
            aufnr        TYPE  aufnr,
            lmnga(13)    TYPE  c,
            budat        TYPE buchdatum,
            END OF tw_afrud,
            tt_afrud     TYPE STANDARD TABLE OF tw_afrud.
    TYPES: BEGIN OF tw_temp,
            rec(7000)    TYPE c,
            END OF tw_temp,
            tt_temp     TYPE STANDARD TABLE OF tw_temp.
    TYPES: BEGIN OF tw_errorlog,
            aufnr        TYPE aufnr,
            message      TYPE string,
           END OF tw_errorlog,
           tt_errorlog   TYPE STANDARD TABLE OF tw_errorlog.
    TYPES: BEGIN OF tw_file,
           pathname      TYPE sdok_filnm,
            END OF tw_file,
            tt_file      TYPE STANDARD TABLE OF tw_file.
    TYPES: BEGIN OF tw_dir,
           pathname1     TYPE sdok_filnm,
            END OF tw_dir,
            tt_dir       TYPE STANDARD TABLE OF tw_dir.
    TYPES: BEGIN OF tw_filename,
           filename      TYPE rlgrap-filename,
           pathname      TYPE localfile,
          END OF tw_filename,
          tt_filename    TYPE STANDARD TABLE OF tw_filename.
    *-------------Variable decleration---------------------------------------*
    DATA: pa_file                TYPE rlgrap-filename.
    DATA: lstring                TYPE string,
          lstring_success        TYPE string,
          lstring_error          TYPE string,
          file_name              TYPE dxfile-filename,
          lv_rc                  TYPE i,
          file_name_source       TYPE string,
          file_name_error_dest   TYPE string,
          file_name_success_dest TYPE string,
          lv_file_name           TYPE rlgrap-filename.
    *---------------Internal tables & Work area's ------------------------------*
    DATA : lw_afrud      TYPE  tw_afrud,
           lt_afrud      TYPE  tt_afrud,
           lw_temp       TYPE  tw_temp,
           lt_temp       TYPE  tt_temp,
           lw_file       TYPE  tw_file,
           lt_file       TYPE  tt_file,
           lw_dir        TYPE  tw_dir,       "#EC *
           lt_dir        TYPE  tt_dir,
           lw_filename   TYPE tw_filename,
           lt_filename   TYPE tt_filename,
           lw_bdcdata    TYPE bdcdata,
           lt_bdcdata    TYPE STANDARD TABLE OF bdcdata,
           lw_bdcmsgcoll TYPE bdcmsgcoll,
           lt_bdcmsgcoll TYPE STANDARD TABLE OF bdcmsgcoll.
    Regards

    The methods of the class
    cl_gui_frontend_services
    cannot be used in background since they refer to the presentation server. You have to upload the files to the application server to run the program in the background. You can use transaction CG3Z or the function module
    ARCHIVFILE_CLIENT_TO_SERVER
    to upload the files.
    Manoj

Maybe you are looking for

  • Passing data from one bsp application to another

    Hi, I have few queries that most of you would have done in ur projects: 1. I want to pass data from one bsp application to another: eg based upon selected row of table view which populates material no and descriprion to another application which open

  • Safari keeps crashing on startup - help please!

    Safari is continuously crashing on startup; I have no web on my iPhone 4! I have tried the basics, restarting, two-finger 'hard restart', clearing all of the Safari settings caches, clearing out some space. I have not tried restoring/resyncing (R/R).

  • PDF form responses coming back uneditable

    I have created a lengthy form in InDesign (v.9.2) for a client, which I have exported to PDF then extended in Acrobat Pro (11.0.06) under File > Save as Other > Reader Extended PDF > Enable More Tools. This makes the form savable (if that's a real wo

  • In iPhoto on MacBook getting black exclamation point instead of photo

    getting a black exclamation point in iPhoto instead of the photo.  Tried holding down option & command while getting on to iPhoto.  it's not working, thank you.

  • Help with fixing geotags

    I am in the process of having a service scan my old photos for importing into iPhoto 9. All the photos so far (about 2000) have no places as would be expected from a scanned photo. But some (about 300) have several different places in China. China is