cocoon-users mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From "Steve Schwarz" <saschw...@hotmail.com>
Subject Re: Uploading fiiles: flow function
Date Mon, 27 Oct 2003 17:14:21 GMT
Josep,
Here is the Action I use. It is based on the example in the Cocoon 
Developer's Handbook.
Hopefully I copied and pasted it w/o error.

The sitemap would be:

in map:components section with the other actions:
      <map:action logger="sitemap.action.fileupload" name="fileupload"
      src="yourpackagenamehere.FileUploadAction" />

in your pipeline section
      <map:match pattern="do-upload">
        <map:act type="request">
          <map:parameter name="parameters" value="true" />
          <map:act type="fileupload">
            <map:parameter name="upload-dir"
            value="incoming" />
          <map:generate src="success.xml"/>
         <map:serialize type="html"/>
          </map:act>
        <map:generate src="uploadfailed.xml" />
        <map:serialize type="html" />
        </map:act>
      </map:match>

HTH
Steve

/**
* Upload a file into the directory specified in the <i>upload-dir</i> 
parameter.
* Based on code by Jeremy Aston from the Cocoon Developer's Handbook.
*/

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import org.apache.avalon.framework.parameters.Parameters;
import org.apache.avalon.framework.thread.ThreadSafe;
import org.apache.cocoon.acting.AbstractConfigurableAction;
import org.apache.cocoon.environment.Context;
import org.apache.cocoon.environment.ObjectModelHelper;
import org.apache.cocoon.environment.Redirector;
import org.apache.cocoon.environment.Request;
import org.apache.cocoon.environment.SourceResolver;
import org.apache.cocoon.servlet.multipart.Part;
import org.apache.cocoon.servlet.multipart.PartOnDisk;
import org.apache.cocoon.util.IOUtils;

public class FileUploadAction
        extends AbstractConfigurableAction
        implements ThreadSafe {
        /** Name of the parameter that holds the upload directory name to 
use **/
        private static final String UPLOAD_FOLDER_PARAMETER = "upload-dir";

        /**
         * Put an upload file into directory specified as a parameter to
         * the action called <i>upload-dir</i>
         */
        public Map act(
                Redirector redirector,
                SourceResolver resolver,
                Map objectModel,
                String source,
                Parameters parameters)
                throws Exception {
                Request request = ObjectModelHelper.getRequest(objectModel);
                Context context = ObjectModelHelper.getContext(objectModel);

                HashMap results = new HashMap();

                if (request != null) {
                        // Loop through the parameter names to find any file 
upload stuff
                        getLogger().debug("Request Parameters");
                        for (Enumeration e = request.getParameterNames();
                                e.hasMoreElements();) {
                                String param = (String)e.nextElement();

                                Object value = request.get(param);

                                getLogger().debug("["+ param + "] ["
                                                + value.getClass().getName() 
+ "] : " + value);

                                if (value instanceof Part) {
                                        // Have got a Part object (or sub 
class - hence the casting )
                                        // Now get the filename and the real 
path to form the file route.

                                        String filename = 
((Part)value).getFileName();
                                        String uploadFolder =
                                                
(String)parameters.getParameter(
                                                        
UPLOAD_FOLDER_PARAMETER);
                                        String realPath = 
context.getRealPath("/");

                                        // Do a sanity check on the upload 
folder

                                        if (uploadFolder == null || 
uploadFolder.length() == 0) {
                                                getLogger().error("Missing "
                                                                + 
UPLOAD_FOLDER_PARAMETER
                                                                + " 
parameter or no upload folder specified in the "
                                                                + 
UPLOAD_FOLDER_PARAMETER
                                                                + " 
parameter");
                                                return null;
                                        }

                                        // Concatenate the realPath folder 
to the upload folder

                                        if (realPath != null) {
                                                uploadFolder = realPath + 
uploadFolder;
                                        }

                                        getLogger().debug(
                                                "Uploading " + filename + " 
to " + uploadFolder);

                                        // Create the upload folder(s) if 
need be
                                        File folder = new 
File(uploadFolder);
                                        if (!folder.exists()) {
                                                folder.mkdirs();

                                        File destFile =
                                                new File(folder + 
File.separator + filename);

                                        // Check to see if the object is a 
PartOnDisk object as this can
                                        // simply be renamed if it is on the 
same file system
                                        if (value instanceof PartOnDisk) {
                                                getLogger().debug("Renaming 
" + filename + " to " + destFile);
                                                if 
(((PartOnDisk)value).getFile().renameTo(destFile)) {
                                                        
getLogger().debug("Successfully renamed "
                                                                        + 
filename
                                                                        + " 
to "
                                                                        + 
destFile);
                                                }
                                                else {
                                                        // Maybe it's on a 
different filesystem...
                                                        if 
(copyFile(((Part)value).getInputStream(),
                                                                new 
FileOutputStream(destFile))) {
                                                                
getLogger().debug("Successfully copied "
                                                                             
                            + filename
                                                                             
                            + " to "
                                                                             
                            + destFile);
                                                        }
                                                        else {
                                                                
getLogger().error("FAILED to rename/copy "
                                                                        + 
filename + " to "     + destFile);
                                                                return null;
                                                        }
                                                }
                                        }
                                        else {
                                                getLogger().debug("Streaming 
file to " + destFile);
                                                if 
(copyFile(((Part)value).getInputStream(),
                                                        new 
FileOutputStream(destFile))) {
                                                        
getLogger().debug("Successfully copied stream to "
                                                                             
                    + destFile);
                                                }
                                                else {
                                                        
getLogger().error("FAILED to copy stream to "
                                                                + destFile);
                                                        return null;
                                                }
                                        }

                                        request.setAttribute("upload-file", 
filename);
                                        getLogger().debug("Set upload-file 
to "
                                                        + 
request.getAttribute("upload-file"));

                                }
                                else if (value instanceof String) {
                                        getLogger().debug("Skipping 
parameter: " + (String)value);
                                }
                                else {
                                        getLogger().debug("Skipping 
something else");
                                }
                        }

                        String contentType = request.getContentType();
                        getLogger().debug("Content Type: " + contentType);

                }

                return Collections.unmodifiableMap(results);
        }

        private boolean copyFile(InputStream in, FileOutputStream out) {
                byte[] buffer = new byte[4096];
                int read;
                try {
                        read = in.read(buffer);

                        while (read > 0) {
                                out.write(buffer, 0, read);
                                read = in.read(buffer);
                        }
                        out.close();
                }
                catch (IOException ex) {
                        return false;
                }
                return true;
        }

}
>Hi again Geoff...
>
>I'm still trying to implement the code in order to upload files with 
>cocoon.
>
>I have readed wiki web a thousand times ... ;-) ..
>

_________________________________________________________________
Fretting that your Hotmail account may expire because you forgot to sign in 
enough? Get Hotmail Extra Storage today!   
http://join.msn.com/?PAGE=features/es


---------------------------------------------------------------------
To unsubscribe, e-mail: users-unsubscribe@cocoon.apache.org
For additional commands, e-mail: users-help@cocoon.apache.org


Mime
View raw message