cocoon-users mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Andrew Savory <and...@luminas.co.uk>
Subject Re: Upgrading the "Upload File" sample to handle binary formats
Date Wed, 15 Sep 2004 06:43:42 GMT
Hi,

On 2 Sep 2004, at 07:24, Derek Hohls wrote:

> In the "Upload File" sample, only text is handled
> and the code looks like:
>
> function handleUpload(form) {
>   var buf = new java.lang.StringBuffer();
>   var uploadWidget = form.lookupWidget("upload");
>   if (uploadWidget.getValue() != null) {
>     var stream = uploadWidget.getValue().getInputStream();
>     var reader = new java.io.BufferedReader(new
> java.io.InputStreamReader(stream));
>     var line;
>     while ((line=reader.readLine())!=null)
>       buf.append(line).append("\n");
>     reader.close();
>   }
>   return buf.toString();
> }
>
> It seems it should be possible to upgrade this to
> write out binary...???  Specifically, I want users to
> be able to upload standard image files - JPEG, GIF
> and PNG (and maybe BMP).

Here's one way to handle this:

// save the uploaded Image, retrieved from CForms
// form is the cforms form object
// id is the name or unique id of the object to save
// repository is a directory on the server
function saveUploadCForms(form, id, repository) {
	try {
		var uploadWidget = form.lookupWidget("upload");
		if (uploadWidget.getValue() != null) {
			var dest = resolve(repository + id + image_suffix);
			var inputStream = uploadWidget.getValue().getInputStream();
			var outputStream = dest.getOutputStream();
			SourceUtil.copy(inputStream,outputStream);
			cocoon.log.info("saved image: " + repository + id + image_suffix);
		}
	} catch (e) {
		cocoon.log.error(e);
		return false;
	}
	return true;
}

/**
  * Utility function - resolve a URI to a Source
  *
  */
function resolve(uri) {
    try {
       var resolver = cocoon.getComponent(SourceResolver.ROLE);
       return resolver.resolveURI(uri);
     } catch (error) {
       cocoon.log.error("Unable to resolve source", error);
       throw (error);
     } finally {
       cocoon.releaseComponent(resolver);
    }
}


> The ideal solution would
> only allow these files types, but this is less critical than
> simply being able to get binary uploaded in the first
> place.

The biggest problem I've found doing this sort of thing is that the 
browsers all have different ideas of how to set the mime-types of the 
uploaded files, so you end up parsing the suffix to determine the type 
of file.

> Any help appreciated... if the solution works, maybe
> I can post it to the Wiki for future reference.

It'll probably be faster than waiting for me to update the 
documentation and CForms samples ;-)


Andrew.

--
Andrew Savory, Managing Director, Luminas Limited
Tel: +44 (0)870 741 6658  Fax: +44 (0)700 598 1135
Web: http://www.luminas.co.uk/
Orixo alliance: http://www.orixo.com/

Mime
View raw message