/    Sign up×
Community /Pin to ProfileBookmark

HELP: button to download an image??

[B]simply, i made a images explorer for my site,
i want to allow users to download any image by clicking on the download button.[/B]

[SIZE=”3″]anyone can help me ?[/SIZE]– sry 4 my beginner question and 4 my bad eng. –
HERE IS THE CODE:
first: HTML codes

[code=html]<input id=”btnPrev” disabled onclick=”prev()” type=”button” value=” prev ” name=”btnPrev”>
<input id=”btnDl” disabled onclick=”” type=”button” value=”DownLoad” name=”btnDl”>
<input id=”btnNext” disabled onclick=”next()” type=”button” value=” next ” name=”btnNext”>[/code]

Second: JS functions

[CODE]var no_of_imgs = 24;
var imgs = new Array(no_of_imgs);
var imgWidth = 265;
var imgHeight = 150;
var currentImg=0;
for(i=0;i<=no_of_imgs;i++){
imgs[i] = new Image()
imgs[i].src = “wallpapers/”+i+”.jpg”
}

function doImg(){imgsDiv.innerHTML=”<img height=” +imgHeight+ ” width=” + imgWidth + ” src=” + imgs[currentImg].src + “>”}

function next(){
btnPrev.disabled=false
if (currentImg == no_of_imgs){ btnNext.disabled=true }
else { currentImg++ ; doImg() }
}

function prev(){
btnNext.disabled=false
if (currentImg==0){ btnPrev.disabled=true }
else { currentImg– ; doImg() }
UpDate()
}

function Pageloaded(){
doImg()
btnNext.disabled =false
}[/CODE]

the HTML page in the attachments as a text file ?

Please i want help to make a function for my download button ?
and i hope from our expert coders if there is any comments on my (beginner) coding, so i edit it and practice my self.

THANKS FOR ALL

[upl-file uuid=800e7875-d48a-4f84-9bcd-826d73eecbef size=3kB]wallpapers.txt[/upl-file]

to post a comment
JavaScript

12 Comments(s)

Copy linkTweet thisAlerts:
@FangFeb 11.2007 — &lt;a href="anImage.gif"&gt;download anImage.gif&lt;/a&gt;

Any function using [I]document.write[/I] after page load will create a new document!
Copy linkTweet thisAlerts:
@alaa_sdkauthorFeb 11.2007 — i tried what u typed
<a href="anImage.gif">download anImage.gif</a>[/QUOTE]

and it opened the "anImae.gif" in a new page, but i want to open the download dialogbox of windows like downloading any file (.exe) or what ever..
-----------


i got ur point in
Any function using document.write after page load will create a new document![/QUOTE]
but i am dont use document.write after the page loads,

and if i used it where ??

any way thanks for ur help, but it doesnt work!!

-sry 4 my bad english-
Copy linkTweet thisAlerts:
@FangFeb 11.2007 — zip the image&lt;a href="anImage.zip"&gt;download anImage.gif&lt;/a&gt;

Use innerHTML , not [I]document.write[/I]
Copy linkTweet thisAlerts:
@alaa_sdkauthorFeb 11.2007 — thanks, but i want to make the users to download the image it-self without ZIP.

i saw that in some sites like the sites of MSN display images, google it.

and i want the code in javascript (without document.write and innerHTML), not HTML.

anyway thanks for ur help ?
Copy linkTweet thisAlerts:
@UltimaterFeb 11.2007 — Look into PHP.

For example:
[code=php]
<?php
header("Content-Type:image/png");
header("Content-Disposition:attachment;filename=ultimater.png");
//Use inline instead of attachment if you don't want it to force a download.
echo file_get_contents("https://webdeveloper.com/forum/image.php?u=30185&dateline=1128637189");
?>
[/code]


Although the above is just an example, you could design your PHP file in such a way that it would be able to accept a parameter associated with the file to download. e.g. downloadimage.php?file=ulti.png

In such a case, you could use a non-JavaScript dependant solution like:

frame:
<i>
</i>&lt;iframe src="about:blank" name="hiddenframe" style="border:0; width:0; height:0; position:absolute;"&gt;&lt;/iframe&gt;

Then:
<i>
</i>&lt;form target="hiddenframe" action="downloadimage.php?file=ulti.png" method="get"&gt;
&lt;input type="submit" value="Download"&gt;
&lt;/form&gt;

or
<i>
</i>&lt;a target="hiddenframe" href="downloadimage.php?file=ulti.png"&gt;Download&lt;/a&gt;


If you'd rather mess with htaccess and/or httpd.conf, be my guest.

assuming the image is located at: mysite.com/download/ulti.png

httpd.conf I believe would look something like this: (although I haven't tested it nor am I an httpd.conf guru)
<i>
</i>&lt;IfModule mod_headers.c&gt;
&lt;Directory /var/www/download&gt;
Order allow,deny
Allow from all
&lt;FilesMatch ".(gif|jpe?g|png)$"&gt;
Header append Content-Disposition "attachment;"
&lt;/FilesMatch&gt;
&lt;/Directory&gt;
&lt;/IfModule&gt;

or you could use htaccess in the "download" directory like this:
<i>
</i>&lt;Files ~ ".(gif|jpe?g|png)$"&gt;
Header append Content-Disposition "attachment;"
&lt;/FilesMatch&gt;

Then accessing the image from mysite.com/download/ulti.png should force the user's browser to download the file. Do note that there are browsers out there that ignore the Content-Disposition header however they can always save the image manually so no biggie.
Copy linkTweet thisAlerts:
@alaa_sdkauthorFeb 12.2007 — thanks for your time that u spent to type ur post.. :eek:

but i am relly sorry bec. i have no idea about the php scripts.

i am using only DHTML [html,css,javascript] - all my usage is a client-side scripts.

any way thanks for ur time ? i think that will help many people in their server-side scripts ?

i think that there is no solution for my problem in the DHTML.

any one can help me ???
Copy linkTweet thisAlerts:
@UltimaterFeb 12.2007 — I think this is IE only but at least it degrades gracefully.
<i>
</i>&lt;script type="text/javascript"&gt;
function saveMe(myFile){
try{
myTempWindow = window.open(myFile,"tmpwindow");
myTempWindow.document.execCommand("SaveAs",null,myFile);
myTempWindow.close();
return false;
}catch(E){
return true
}
}
&lt;/script&gt;
&lt;a href="[color=blue]ulti.png[/color]" target="_new" onclick="return saveMe(this.getAttribute('href'))"&gt;Download Me&lt;/a&gt;

Sadly the above SaveAs approach requires JavaScript to run on a new window or frame (if revised) -- hence the same domain&server security restriction on your images... Maybe in the future I'll think of a way to serve other browsers without relying on the server.

Sadly the closest I seem to be able to get in Firefox is:
<i>
</i>&lt;iframe src="data:application/x-octet-stream;base64,R0lGODdhMAAwAPAAAAAAAP///ywAAAAAMAAw
AAAC8IyPqcvt3wCcDkiLc7C0qwyGHhSWpjQu5yqmCYsapyuvUUlvONmOZtfzgFz
ByTB10QgxOR0TqBQejhRNzOfkVJ+5YiUqrXF5Y5lKh/DeuNcP5yLWGsEbtLiOSp
a/TPg7JpJHxyendzWTBfX0cxOnKPjgBzi4diinWGdkF8kjdfnycQZXZeYGejmJl
ZeGl9i2icVqaNVailT6F5iJ90m6mvuTS4OK05M0vDk0Q4XUtwvKOzrcd3iq9uis
F81M1OIcR7lEewwcLp7tuNNkM3uNna3F2JQFo97Vriy/Xl4/f1cf5VWzXyym7PH
hhx4dbgYKAAA7"&gt;

However without a Content-Disposition, the file wants to save as vl7novz4...
Copy linkTweet thisAlerts:
@alaa_sdkauthorFeb 12.2007 — thanks alot, It works great ???
Copy linkTweet thisAlerts:
@alaa_sdkauthorFeb 12.2007 — i just want to ask you about somethings in your code post:

first:

[code=php]execCommand("SaveAs",null,myFile);[/code]
what the second and third parameter means

second:
[code=php]catch(E){
return true
}[/code]

what is E, is it means the error variable, and if it means that y you use return true not return false

third
[code=php]return false;[/code]
y u are using this after opening, execcommand, closing

fourth:

i want to learn about the try statment

fifth:

what about popup blocking in the user's browsers, it will block the opened window????

sixth:

i cant understant what you typed about the firefox code, it is so complicated

and what is "Content-Disposition"


thanks ?
Copy linkTweet thisAlerts:
@UltimaterFeb 12.2007 — You can also use [url=http://msdn.microsoft.com/workshop/author/dhtml/reference/constants/saveas.asp]document.execCommand("SaveAs")[/url]

the 2nd and 3rd arguments are optional however in my code I provided them.

The 2nd argument is a boolean one that makes no difference in the case of SaveAs however with different commands makes a difference

e.g.

document.execCommand("CreateLink",true,"http://google.com")

will prompt the users for the URL to enter

document.execCommand("CreateLink",false,"http://google.com")

document.execCommand("CreateLink",null,"http://google.com")

won't prompt the user and instead rely upon the 3rd argument

Regarding the try-catch block, E is an error object that is created and exists only within the catch block however it is required by JavaScript even though I am not using it. I tend to think of the catch-block as a function that requires one argument and the variable is local to the function just like the variable is local to the catch-block. Regarding the boolean value the function returns to the onclick event handler of the Anchor element, give this a run:
<i>
</i>&lt;a href="http://www.google.com" target="_new" onclick="return false"&gt;Disabled Link&lt;/a&gt;
&lt;br&gt;
&lt;a href="http://www.google.com" target="_new" onclick="return true"&gt;Enabled Link&lt;/a&gt;

The try block cannot occur alone although it can occur as a useless try-finally block or a useful try-catch block or a try-catch-finally block. Without a catch block, the errors will not be blocked. The finally block is rather useless and is rather powerless. By catching an error, it is not passed to the browser's onerror event. Also the catch block is only evaluated if the try block would normally fire the onerror event however if you give the try-block a syntax error, JavaScript will not even attempt to run the contents of the containing SCRIPT element at all.

Popup blockers allows windows to be opened if the users manually opens it however auto-opening windows e.g. onload will be blocked. If the user clicks a link and it opens in a new window, a popup blocker will not block it.

Regarding the Firefox code:
<i>
</i>&lt;iframe src="data:application/x-octet-stream;base64,R0lGODdhMAAwAPAAAAAAAP///ywAAAAAMAAw
AAAC8IyPqcvt3wCcDkiLc7C0qwyGHhSWpjQu5yqmCYsapyuvUUlvONmOZtfzgFz
ByTB10QgxOR0TqBQejhRNzOfkVJ+5YiUqrXF5Y5lKh/DeuNcP5yLWGsEbtLiOSp
a/TPg7JpJHxyendzWTBfX0cxOnKPjgBzi4diinWGdkF8kjdfnycQZXZeYGejmJl
ZeGl9i2icVqaNVailT6F5iJ90m6mvuTS4OK05M0vDk0Q4XUtwvKOzrcd3iq9uis
F81M1OIcR7lEewwcLp7tuNNkM3uNna3F2JQFo97Vriy/Xl4/f1cf5VWzXyym7PH
hhx4dbgYKAAA7"&gt;

one could just type into their address bar in Firefox:
<i>
</i>data:text/html;utf-8,&lt;strong&gt;This is HTML&lt;/string&gt;

And you could also place binary data:
<i>
</i>data:image/gif;base64,R0lGODdhMAAwAPAAAAAAAP///ywAAAAAMAAwAAAC8IyPqcvt3wCcDkiLc7C0qwyGHhSWpjQu5yqmCYsapyuvUUlvONmOZtfzgFzByTB10QgxOR0TqBQejhRNzOfkVJ+5YiUqrXF5Y5lKh/DeuNcP5yLWGsEbtLiOSpa/TPg7JpJHxyendzWTBfX0cxOnKPjgBzi4diinWGdkF8kjdfnycQZXZeYGejmJlZeGl9i2icVqaNVailT6F5iJ90m6mvuTS4OK05M0vDk0Q4XUtwvKOzrcd3iq9uisF81M1OIcR7lEewwcLp7tuNNkM3uNna3F2JQFo97Vriy/Xl4/f1cf5VWzXyym7PHhhx4dbgYKAAA7

application/x-octet-stream just hints to the browser to download rather than run it.

base64 is a charset consisting of 64 characters:

0 through 9, a through z, A through Z, the + character and the / character

base64 is a commonly used charset to represent binary data.
Copy linkTweet thisAlerts:
@alaa_sdkauthorFeb 13.2007 — Regarding the try-catch block
E is an error object that is created and exists only within the catch block however it is required by JavaScript even though I am not using it[/QUOTE]
you mean typing it between the prackets (E) -or- you mean declare it in the backgroud only by javascript, and i want to ask if i can use the E variable as in VisualBasic.NET by appearing the error to the users for example

alert(E.value) or whatever.

the second thing is i want to know why you typed return true not return false in the catch block..
--


JavaScript will not even attempt to run the contents of the containing SCRIPT element at all.[/QUOTE]

you mean that javascript will not run all the contains bec. <script> and </script> or what ??
----------


Regarding the Firefox code::

you said that users of firefox can type
[code=php]data:text/html;utf-8,<strong>This is HTML</string>[/code]
can the users of IE type that too ??? and why ??

the second thing is about the binary data, i just know the binary data as 0,1 as i see in the computer or what ever but what is the relation between it and between you typed:
[CODE]data:image/gif;base64,R0lGODdhMAAwAPAAAAAAAP///ywAAAAAMAAwAAAC8IyPqcvt3wCcDkiLc7C0qwyGHhSWpjQu5yqmCYsapyuvUUlvONmOZtfzgFzByTB10QgxOR0TqBQejhRNzOfkVJ+5YiUqrXF5Y5lKh/DeuNcP5yLWGsEbtLiOSpa/TPg7JpJHxyendzWTBfX0cxOnKPjgBzi4diinWGdkF8kjdfnycQZXZeYGejmJlZeGl9i2icVqaNVailT6F5iJ90m6mvuTS4OK05M0vDk0Q4XUtwvKOzrcd3iq9uisF81M1OIcR7lEewwcLp7tuNNkM3uNna3F2JQFo97Vriy/Xl4/f1cf5VWzXyym7PHhhx4dbgYKAAA7[/CODE][/QUOTE]
and how to convert my drawed images to code like that and where to use it ?? -- i want to learn about that [binary,bases,convert,etc] where can i find that (URL) --

i know that i asks many questions but i am relly sorry, i have other questions but i will not ask it bec. it will take a ""hard work"" from you.

[FONT="Comic Sans MS"][B]the only thing i want to tell you is that you are so HELPFUL ? THANKS ALOT[/B][/FONT]
Copy linkTweet thisAlerts:
@UltimaterFeb 16.2007 — 
you mean typing it between the prackets (E) -or- you mean declare it in the backgroud only by javascript,
[/quote]

Not sure I understand your question. Also brackets is spelled with a "b" not a "p" and the variable "E" is wrapped around parentheses () not brackets [].

It doesn't matter if the variable "E" is defined prior to the catch block since the catch block overrides it with an error object and the variable will be local to the catch block. Give this a run and you'll understand want I mean:
<i>
</i>&lt;script type="text/javascript"&gt;
var E="global value";
alert("The value of the variable "E" is:n"+E)
try{
someFunctionThatDoesntExist();
}catch(E){
alert("The value of the variable "E" is:n"+E)
}
alert("The value of the variable "E" is:n"+E)
&lt;/script&gt;


and i want to ask if i can use the E variable as in VisualBasic.NET by appearing the error to the users for example

alert(E.value) or whatever.
[/quote]

Give this a run:
<i>
</i>&lt;script type="text/javascript"&gt;
try{
someFunctionThatDoesntExist();
}catch(E){
var t=new Array();
for(var j in E)t.push("E."+j+":n"+E[j]);
alert(propertiesOfE=t.join("nnn"))
}
&lt;/script&gt;

Firefox and IE will give you two uniquely different alerts.

Browsers are prone to giving different errors and the errors they raise are bound to be different. Some browsers raise exceptions where required by standards while others do not. The Error object is so unreliable that even the error type encountered is different from browser to browser.
<i>
</i>&lt;script type="text/javascript"&gt;
try {
someFunctionThatDoesntExist();
} catch (e) {
alert(
"TypeError: "+(e instanceof TypeError)+"n"+ //IE
"RangeError: "+(e instanceof RangeError)+"n"+
"EvalError: "+(e instanceof EvalError)+"n"+
"ReferenceError: "+(e instanceof ReferenceError)+"n"+ //Firefox
"SyntaxError: "+(e instanceof SyntaxError)+"n"+
"URIError: "+(e instanceof URIError)+"n"+
"Error: "+(e instanceof Error)+"n" // IE,Firefox
);
}
&lt;/script&gt;



the second thing is i want to know why you typed return true not return false in the catch block..
[/quote]

I've given this code before and it should answer your question.
<i>
</i>&lt;a href="http://www.google.com" target="_new" onclick="return false"&gt;Disabled Link&lt;/a&gt;
&lt;br&gt;
&lt;a href="http://www.google.com" target="_new" onclick="return true"&gt;Enabled Link&lt;/a&gt;

By clicking an anchor element (<a>) it tells the browse to navigate away to the given HREF. Upon click of an anchor element, the browse awaits a return value. If none is given it has a default of true meaning that the click event was successful and the anchor element was clicked so the browser should navigate away to the given HREF. However by returning false, the browser closes its eye to the clicked anchor element and doesn't load the HREF. In my code, the anchor element has a target of "_new" so if the anchor element is clicked (even with JavaScript disabled) then the link will be loaded in a new window. However JavaScript is [i]also[/i] creating a new window via window.open. Basically IE is served with execCommand while other browsers fail to let JavaScript handle their request and I wanted them to fall back to opening the image in a new window in order to assist users that are trying to save the image manually.

Hence I return true to the anchor element's onclick event handler for non-IE browsers and JavaScript disabled users in order for the href to be loaded in a new target while returning false to IE so they doesn't get an unnecessary window having already successfully executed execCommand and saved the image.

you mean that javascript will not run all the contains bec. <script> and </script> or what ??
[/quote]

Correct. Each SCRIPT element is evaluated separately. If there is a syntax error in one of the SCRIPT tags, even if found within a try-catch block, JavaScript complains and stops in its tracks and jumps to evaluate the next SCRIPT tag.

i know that i asks many questions but i am relly sorry, i have other questions but i will not ask it bec. it will take a ""hard work"" from you.[/QUOTE]
What can I say? Whoever loves knowledge also loves discipline. The one that listens to reproof gains both understanding and slowness to anger while the heart of the prudent acquires knowledge but stupid is the one that hates reproof. Hard work? psst, in my book, hard work is defined as keeping my coffee mug full. Many Questions? Oh please. I enjoy the sensation of getting hit by loads of hard questions and answering them with little effort while others fear me. Is that all you got? ?

I'll postpone my reply regarding the data protocol and base64 in order to give you time to catch up.
×

Success!

Help @alaa_sdk spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.16,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...