0

I want to make a download link.

Here is my HTML:

<a href="javascript:void(0)"><img src="../images/icons/word.png" alt="Word"></a>
<a href="javascript:void(0)"><img src="../images/icons/excel.png" alt="Excel"></a>
<a href="/download/test.ppt"><img src="../images/icons/ppt.png" alt="PPT"></a>
<a href="/download/test.pdf"><img src="../images/icons/pdf.png" alt="PDF"></a>

When I click <a> tag, I want to perform an http request, and the <a> tag really does that. But it also jumps to the new page. I do not want that to happen.

I searched and found some solutions such as setting <a> tag's href="#something", or use ajax. However, those solutions are not what I want.

I am wondering there is a better solution for doing this? PS: I really do not want to use ajax to realize these in here.

Sumner Evans
  • 8,951
  • 5
  • 30
  • 47
BenFei
  • 3
  • 2
  • No, that make no sense. Anchor tags are used to navigate, you can't just send a request without going anyware using standard behavior. Supressing default behavior (navigation) + ajax is the best you can do. – Claudio Redi Feb 22 '15 at 03:39
  • possible duplicate of [How can I create download link in html?](http://stackoverflow.com/questions/2793751/how-can-i-create-download-link-in-html) – Eric J. Feb 22 '15 at 03:57
  • just turn the _href_ into _data-href_, and in the JS code, use _a.dataset.href_ instead of _a.href_ . – dandavis Feb 22 '15 at 03:59
  • you can also use onclick='return false' , but it's better to cancel the event and preventDefault in your code that binds to the ajax. – dandavis Feb 22 '15 at 04:01
  • So what *should* happen? What should happen to the HTTP response? – Jukka K. Korpela Feb 22 '15 at 07:27
  • @JukkaK.Korpela , you can find my codes in second answers.I hope that is useful for you. – BenFei Feb 22 '15 at 08:03
  • I wasn’t asking for code. I was asking for a clarification of the question. Currently it falls into the “unclear what you are asking” question. If you need to present code to clarify what is being asked, please do so by editing the question. – Jukka K. Korpela Feb 22 '15 at 10:46

2 Answers2

0

You can set the target to a new tab. In chrome this tab closes automatically.

<a href="/download/test.ppt" target="_blank"><img src="../images/icons/ppt.png" alt="PPT"></a>
Clemens Frahnow
  • 307
  • 1
  • 5
0

HTML codes are:

<a href="../downloads/test.docx" target="_blank"><img src="../images/icons/ppt.png" alt="PPT"></a>

I use nodejs for server,and nodejs codes are:

fs.stat(filepath, function(err, stats) {
    if (err)
        throw err;

    var stream = fs.createReadStream(filepath);
    response.setHeader('Content-Type', mime.lookup(filepath));
    response.setHeader('Content-Disposition', 'attachment;    filename=test.docx');
    response.writeHead(200);
    stream.pipe(response);
});
BenFei
  • 3
  • 2