[Zope] RE: Q: How to check if Image exists (inside REQUEST object)?

Samu Mielonen ex@uiah.fi
Mon, 25 Oct 1999 12:59:10 +0300


My question:
> > You wouldn't know how to test if a REQUEST.image1 exists or not before
> > actually using manage_addImage or manage_upload on that image?

Alexander Staubo [mailto:alex@mop.no] :
> Test on the content type of the file object, or check whether the file
> object's file attribute contains a non-zero file (eg., call seek(0, 2)
> and then check if tell() returns > 0).

> The following code illustrates the latter:
> 
>   <dtml-if "REQUEST.has_key('MyFile')">
>     <dtml-if "(MyFile.file.seek(0, 2) or MyFile.file.tell()) > 0">
>       <!-- file is valid -->
>     </dtml-if>
>   </dtml-if>

Excellent! Thanks! It works. I don't yet understand how, but it works. 
For others who may have a problem with saving non-existent images
from form uploads the answer is to use the above code modified
to your specific circumstances (see below).

In my example, I am using <input type=file name=image1> in my
submit form. In case the user doesn't choose an image to be
uploaded, we need to do the following check in the dtml-method
that handles the submit form:

  <dtml-if "REQUEST.has_key('image1')"> 

	<dtml-if "(REQUEST.image1.seek(0, 2) or REQUEST.image1.tell()) > 0">

		<dtml-with "_[i1name]">

			<dtml-call "manage_upload(image1, REQUEST.image1)">

		</dtml-with>

	</dtml-if>

  </dtml-if>  

Comments:

1st line checks if the REQUEST object (ie submitted form contents) has
an attribute image1 (so we dont get errors afterwards, if we don't
for some reason have that attribute in the object).

2nd line checks something :) 

3rd line goes into the context of a specific image

4th line replaces the image (in context) with the image from the
submit form (referenced in this case with attribute image1).

Thanks again,
	Samu Mielonen

PS I'm still a bit puzzled at how difficult this is. Shouldn't there
be an easier way? I guess I could write a dtml-method to do this, but
I think this could be an out of a box functionality. I mean
<dtml-if image1> should just work in my naive opinion :)