Archive for the ‘Tips & Tricks’ Category

Get image data from client side using javascript

Well, I had a requirement to show a preview of image, whenever client selects an image inside a form. First I thought it was just a easy task… But it really took about one hour of me to figure the way out…

As it was an input element with type=file, I simply tried to get the value and push it to an image element’s source attribute attaching ‘file://’ at the beginning. But life’s not that easy! The value only returns the file name not the full path. How can I get the full path??!! I can see the path on the input box, but I can’t get it!!!

Next approach, go to our best friend, Google! Well, I guess she wasn’t very pleased with me and didn’t help me very much…

Now what?! Well, let’s try the DOM inspector of Firefox. There I found three functions for the file input element.

  • getAsBinary()
  • getAsDataURL()
  • getAsText()

They are all self explanatory… My head was already stuck at that moment. So I didn’t see the ‘Data URL’ function first. Tried to parse binary for a while. But couldn’t find a way to push the binary data of an image inside the image tag. Then I noticed the next function. Well, it worked like a charm. I just pushed the function’s return value to the image tag’s source attribute. Done.

So, to get the file path, the call should be like:

file_input_element_id.files[0].getAsDataURL()

That’s all… :-)

N.B. For IE, it works OK with adding the ‘file://’ before the value of input element. You just need to have proper permission level.

Advanced object selection using Mootools

Mootools’ “Selectors” utility has some really strong feature. It really saves a lot of time and sweat. Using this property, one can select a tag (any one can!), tag with specific name, id or any other attribute (huh!) and most amazingly part of a property value matching to some string…

Say you want to select all the div tags which has ID starting with ‘my’. How can you do that? Read the rest of this entry »

File upload/download on MySQL database

Well… It is already a well discussed topic. But when I was first trying to find out how to do this, I really got stuck. Actully it took me a lot of time to find out the key code segment for the purpose.

So, here is what I’ve learned:

The table:

Suppose the structure of the MySQL table (say ‘file_table‘) is like this:

It has three fileds:

  • id : the primary key, integer type with auto increment feature.
  • content: the content of file, blob type.
  • type: varchar type, the type of the file (e.g. doc, pdf etc.).

Upload:

I think you can create a HTML form with a input with file type. Its pretty simple. Just use this code to make a input field be able to upload file:

<input id="file_upload" name="file_upload" type="file" />

Now the backend coding. I’m using PHP for this. Read the rest of this entry »

Search
Categories