Rectangle 27 561

Bluish is completely right about this, you can't do it through Ajax because JavaScript cannot save files directly to a user's computer (out of security concerns). Unfortunately pointing the main window's URL at your file download means you have little control over what the user experience is when a file download occurs.

I created jQuery File Download which allows for an "Ajax like" experience with file downloads complete with OnSuccess and OnFailure callbacks to provide for a better user experience. Take a look at my blog post on the common problem that the plugin solves and some ways to use it and also a demo of jQuery File Download in action. Here is the source

Here is a simple use case demo using the plugin source with promises. The demo page includes many other, 'better UX' examples as well.

$.fileDownload('some/file.pdf')
    .done(function () { alert('File download a success!'); })
    .fail(function () { alert('File download failed!'); });

Depending on what browsers you need to support you may be able to use https://github.com/eligrey/FileSaver.js/ which allows more explicit control than the IFRAME method jQuery File Download uses.

I love what you built but I suspect that to get more StackOverFlow credit your answer here should contain a bit more detail. Specifically on how you solved the problem.

it would be nice if you would mention exactly how this "plugin" gets around the limitation, rather than forcing us to go to your blog/plugin source to see it. for example, is it instead posting to an iframe? is it instead requiring the remote script to save the file and return a url to it?

I agree, a blog is a far better place to place a lengthy description of how to use your plugin and how it works. but you could have at least gave a short overview of how this plugin solves the problem. For example, this solves the problem by having the server set a cookie and having your javascript continuously look for the cookie until it exists. Once it exists, we can assume that the download is complete. With that kind of information one could easily roll their own solution very quickly, and the answer no longer relies 100% on your blog/plugin/jquery and can be applied to other libraries.

Royi, as I understand it AJAX can never support file downloads that result in a file download popup to save to disk. Have you found a way that I'm unaware of?

@StanE thanks for the comment. I updated the bottom of my answer which clarifies some better options now that it is 2016 (and jQuery was almost a given back when I wrote this plugin and answered this question -- which is certainly not the case anymore)

javascript - Download a file by jQuery.Ajax - Stack Overflow

javascript jquery ajax jsp download
Rectangle 27 561

Bluish is completely right about this, you can't do it through Ajax because JavaScript cannot save files directly to a user's computer (out of security concerns). Unfortunately pointing the main window's URL at your file download means you have little control over what the user experience is when a file download occurs.

I created jQuery File Download which allows for an "Ajax like" experience with file downloads complete with OnSuccess and OnFailure callbacks to provide for a better user experience. Take a look at my blog post on the common problem that the plugin solves and some ways to use it and also a demo of jQuery File Download in action. Here is the source

Here is a simple use case demo using the plugin source with promises. The demo page includes many other, 'better UX' examples as well.

$.fileDownload('some/file.pdf')
    .done(function () { alert('File download a success!'); })
    .fail(function () { alert('File download failed!'); });

Depending on what browsers you need to support you may be able to use https://github.com/eligrey/FileSaver.js/ which allows more explicit control than the IFRAME method jQuery File Download uses.

I love what you built but I suspect that to get more StackOverFlow credit your answer here should contain a bit more detail. Specifically on how you solved the problem.

it would be nice if you would mention exactly how this "plugin" gets around the limitation, rather than forcing us to go to your blog/plugin source to see it. for example, is it instead posting to an iframe? is it instead requiring the remote script to save the file and return a url to it?

I agree, a blog is a far better place to place a lengthy description of how to use your plugin and how it works. but you could have at least gave a short overview of how this plugin solves the problem. For example, this solves the problem by having the server set a cookie and having your javascript continuously look for the cookie until it exists. Once it exists, we can assume that the download is complete. With that kind of information one could easily roll their own solution very quickly, and the answer no longer relies 100% on your blog/plugin/jquery and can be applied to other libraries.

Royi, as I understand it AJAX can never support file downloads that result in a file download popup to save to disk. Have you found a way that I'm unaware of?

@StanE thanks for the comment. I updated the bottom of my answer which clarifies some better options now that it is 2016 (and jQuery was almost a given back when I wrote this plugin and answered this question -- which is certainly not the case anymore)

javascript - Download a file by jQuery.Ajax - Stack Overflow

javascript jquery ajax jsp download
Rectangle 27 561

Bluish is completely right about this, you can't do it through Ajax because JavaScript cannot save files directly to a user's computer (out of security concerns). Unfortunately pointing the main window's URL at your file download means you have little control over what the user experience is when a file download occurs.

I created jQuery File Download which allows for an "Ajax like" experience with file downloads complete with OnSuccess and OnFailure callbacks to provide for a better user experience. Take a look at my blog post on the common problem that the plugin solves and some ways to use it and also a demo of jQuery File Download in action. Here is the source

Here is a simple use case demo using the plugin source with promises. The demo page includes many other, 'better UX' examples as well.

$.fileDownload('some/file.pdf')
    .done(function () { alert('File download a success!'); })
    .fail(function () { alert('File download failed!'); });

Depending on what browsers you need to support you may be able to use https://github.com/eligrey/FileSaver.js/ which allows more explicit control than the IFRAME method jQuery File Download uses.

I love what you built but I suspect that to get more StackOverFlow credit your answer here should contain a bit more detail. Specifically on how you solved the problem.

+1 for the solution and +1 for the cool link from your blog reminding me to +1 the answer! (ok, I only did it once)

it would be nice if you would mention exactly how this "plugin" gets around the limitation, rather than forcing us to go to your blog/plugin source to see it. for example, is it instead posting to an iframe? is it instead requiring the remote script to save the file and return a url to it?

+1 You are my hero. After hours of research I finally stumbled on this post and got it working.

I agree, a blog is a far better place to place a lengthy description of how to use your plugin and how it works. but you could have at least gave a short overview of how this plugin solves the problem. For example, this solves the problem by having the server set a cookie and having your javascript continuously look for the cookie until it exists. Once it exists, we can assume that the download is complete. With that kind of information one could easily roll their own solution very quickly, and the answer no longer relies 100% on your blog/plugin/jquery and can be applied to other libraries.

Royi, as I understand it AJAX can never support file downloads that result in a file download popup to save to disk. Have you found a way that I'm unaware of?

@StanE thanks for the comment. I updated the bottom of my answer which clarifies some better options now that it is 2016 (and jQuery was almost a given back when I wrote this plugin and answered this question -- which is certainly not the case anymore)

javascript - Download a file by jQuery.Ajax - Stack Overflow

javascript jquery ajax jsp download
Rectangle 27 21

If you can control the URL used to download, you can put parameters in the URL to control how the built-in reader will display the file.

The above applies to the built-in reader supplied by Adobe. Other readers may not honor the parameters. In particular, see the answer to this question regarding Chrome.

acrobat - Is it possible to have a PDF file open at a predefined magni...

pdf acrobat adobe-reader
Rectangle 27 21

If you can control the URL used to download, you can put parameters in the URL to control how the built-in reader will display the file.

The above applies to the built-in reader supplied by Adobe. Other readers may not honor the parameters. In particular, see the answer to this question regarding Chrome.

acrobat - Is it possible to have a PDF file open at a predefined magni...

pdf acrobat adobe-reader
Rectangle 27 1

It's possible to download the file with with Apache's HttpComponents instead of Commons-IO. This code allows you to download a file in Java according to its URL and save it at the specific destination.

public static boolean saveFile(URL fileURL, String fileSavePath) {

    boolean isSucceed = true;

    CloseableHttpClient httpClient = HttpClients.createDefault();

    HttpGet httpGet = new HttpGet(fileURL.toString());
    httpGet.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0");
    httpGet.addHeader("Referer", "https://www.google.com");

    try {
        CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
        HttpEntity fileEntity = httpResponse.getEntity();

        if (fileEntity != null) {
            FileUtils.copyInputStreamToFile(fileEntity.getContent(), new File(fileSavePath));
        }

    } catch (IOException e) {
        isSucceed = false;
    }

    httpGet.releaseConnection();

    return isSucceed;
}

In contrast to the single line of code:

FileUtils.copyURLToFile(fileURL, new File(fileSavePath),
                        URLS_FETCH_TIMEOUT, URLS_FETCH_TIMEOUT);

this code will give you more control over a process and let you specify not only time outs but User-Agent and Referer values, which are critical for many web-sites.

How to download and save a file from Internet using Java? - Stack Over...

java download
Rectangle 27 16

To download release file from private repo, you can use Personal access token which can be generated at /settings/tokens with Full control of private repositories scope.

Then download the asset with curl command (change with appropriate values):

curl -vLJO -H 'Accept: application/octet-stream' 'https://api.github.com/repos/:owner/:repo/releases/assets/:id?access_token=:token'
:owner
:repo

:id is your asset id, can be found in tag release URL, like:

https://api.github.com/repos/:owner/:repo/releases/tags/:tag
:token
/settings/tokens

Here is the Bash script which can download asset file given specific name of file:

#!/usr/bin/env bash
# Script to download asset file from tag release using GitHub API v3.
# See: http://stackoverflow.com/a/35688093/55075    
CWD="$(cd -P -- "$(dirname -- "$0")" && pwd -P)"

# Check dependencies.
set -e
type curl grep sed tr >&2
xargs=$(which gxargs || which xargs)

# Validate settings.
[ -f ~/.secrets ] && source ~/.secrets
[ "$GITHUB_API_TOKEN" ] || { echo "Error: Please define GITHUB_API_TOKEN variable." >&2; exit 1; }
[ $# -ne 4 ] && { echo "Usage: $0 [owner] [repo] [tag] [name]"; exit 1; }
[ "$TRACE" ] && set -x
read owner repo tag name <<<$@

# Define variables.
GH_API="https://api.github.com"
GH_REPO="$GH_API/repos/$owner/$repo"
GH_TAGS="$GH_REPO/releases/tags/$tag"
AUTH="Authorization: token $GITHUB_API_TOKEN"
WGET_ARGS="--content-disposition --auth-no-challenge --no-cookie"
CURL_ARGS="-LJO#"

# Validate token.
curl -o /dev/null -sH "$AUTH" $GH_REPO || { echo "Error: Invalid repo, token or network issue!";  exit 1; }

# Read asset tags.
response=$(curl -sH "$AUTH" $GH_TAGS)
# Get ID of the asset based on given name.
eval $(echo "$response" | grep -C3 "name.:.\+$name" | grep -w id | tr : = | tr -cd '[[:alnum:]]=')
#id=$(echo "$response" | jq --arg name "$name" '.assets[] | select(.name == $name).id') # If jq is installed, this can be used instead. 
[ "$id" ] || { echo "Error: Failed to get asset id, response: $response" | awk 'length($0)<100' >&2; exit 1; }
GH_ASSET="$GH_REPO/releases/assets/$id"

# Download asset file.
echo "Downloading asset..." >&2
curl $CURL_ARGS -H 'Accept: application/octet-stream' "$GH_ASSET?access_token=$GITHUB_API_TOKEN"
echo "$0 done." >&2

Before running, you need to set your GITHUB_API_TOKEN with your GitHub token (see: /settings/tokens at GH). This can be placed in your ~/.secrets file, like:

GITHUB_API_TOKEN=XXX
./get_gh_asset.sh :owner :repo :tag :name

where name is your filename (or partial of it). Prefix script with TRACE=1 to debug it.

In case you wonder why curl fails sometimes with (as mentioned in other answer):

Only one auth mechanism allowed; only the X-Amz-Algorithm query parameter, Signature query string parameter or the Authorization header should be specified.

curl -vLJ -H 'Authorization: token <token>' -H 'Accept: application/octet-stream' https://api.github.com/repos/:owner/:repo/releases/assets/<id>
X-Amz-Algorithm
X-Amz-Signature
Authorization: token <token>

and since GitHub redirects you from asset page (when requesting application/octet-stream), it populates credentials automatically in query string and since curl is passing over the same credentials in the request header (which you've specified), therefore they're conflicting. So as for workaround you can use access_token instead.

Thanks for the script @kenorb, I will use it to allow my ansible playbook to grab release .deb files from a private repo. Much appreciated.

jq
ASSET_ID=$(echo "$response" | jq --arg name "$name" '.assets[] | select(.name == $name).id')

How to download GitHub Release from private repo using command line - ...

command-line github
Rectangle 27 16

To download release file from private repo, you can use Personal access token which can be generated at /settings/tokens with Full control of private repositories scope.

Then download the asset with curl command (change with appropriate values):

curl -vLJO -H 'Accept: application/octet-stream' 'https://api.github.com/repos/:owner/:repo/releases/assets/:id?access_token=:token'
:owner
:repo

:id is your asset id, can be found in tag release URL, like:

https://api.github.com/repos/:owner/:repo/releases/tags/:tag
:token
/settings/tokens

Here is the Bash script which can download asset file given specific name of file:

#!/usr/bin/env bash
# Script to download asset file from tag release using GitHub API v3.
# See: http://stackoverflow.com/a/35688093/55075    
CWD="$(cd -P -- "$(dirname -- "$0")" && pwd -P)"

# Check dependencies.
set -e
type curl grep sed tr >&2
xargs=$(which gxargs || which xargs)

# Validate settings.
[ -f ~/.secrets ] && source ~/.secrets
[ "$GITHUB_API_TOKEN" ] || { echo "Error: Please define GITHUB_API_TOKEN variable." >&2; exit 1; }
[ $# -ne 4 ] && { echo "Usage: $0 [owner] [repo] [tag] [name]"; exit 1; }
[ "$TRACE" ] && set -x
read owner repo tag name <<<$@

# Define variables.
GH_API="https://api.github.com"
GH_REPO="$GH_API/repos/$owner/$repo"
GH_TAGS="$GH_REPO/releases/tags/$tag"
AUTH="Authorization: token $GITHUB_API_TOKEN"
WGET_ARGS="--content-disposition --auth-no-challenge --no-cookie"
CURL_ARGS="-LJO#"

# Validate token.
curl -o /dev/null -sH "$AUTH" $GH_REPO || { echo "Error: Invalid repo, token or network issue!";  exit 1; }

# Read asset tags.
response=$(curl -sH "$AUTH" $GH_TAGS)
# Get ID of the asset based on given name.
eval $(echo "$response" | grep -C3 "name.:.\+$name" | grep -w id | tr : = | tr -cd '[[:alnum:]]=')
#id=$(echo "$response" | jq --arg name "$name" '.assets[] | select(.name == $name).id') # If jq is installed, this can be used instead. 
[ "$id" ] || { echo "Error: Failed to get asset id, response: $response" | awk 'length($0)<100' >&2; exit 1; }
GH_ASSET="$GH_REPO/releases/assets/$id"

# Download asset file.
echo "Downloading asset..." >&2
curl $CURL_ARGS -H 'Accept: application/octet-stream' "$GH_ASSET?access_token=$GITHUB_API_TOKEN"
echo "$0 done." >&2

Before running, you need to set your GITHUB_API_TOKEN with your GitHub token (see: /settings/tokens at GH). This can be placed in your ~/.secrets file, like:

GITHUB_API_TOKEN=XXX
./get_gh_asset.sh :owner :repo :tag :name

where name is your filename (or partial of it). Prefix script with TRACE=1 to debug it.

In case you wonder why curl fails sometimes with (as mentioned in other answer):

Only one auth mechanism allowed; only the X-Amz-Algorithm query parameter, Signature query string parameter or the Authorization header should be specified.

curl -vLJ -H 'Authorization: token <token>' -H 'Accept: application/octet-stream' https://api.github.com/repos/:owner/:repo/releases/assets/<id>
X-Amz-Algorithm
X-Amz-Signature
Authorization: token <token>

and since GitHub redirects you from asset page (when requesting application/octet-stream), it populates credentials automatically in query string and since curl is passing over the same credentials in the request header (which you've specified), therefore they're conflicting. So as for workaround you can use access_token instead.

Thanks for the script @kenorb, I will use it to allow my ansible playbook to grab release .deb files from a private repo. Much appreciated.

jq
ASSET_ID=$(echo "$response" | jq --arg name "$name" '.assets[] | select(.name == $name).id')

How to download GitHub Release from private repo using command line - ...

command-line github
Rectangle 27 6

If you want to do it with code only (no Internet Transfer Control), VBNet.mvps.org has a really good how-to article that uses the URLDownloadToFile API call.

The URLDownloadToFile API is available on all versions of the Windows operating system (except Win3, WinNT3.x). By passing the remote file name and the local file path and name, the API downloads the bits of the specified file saving them as the target name. The function works with all file types - plain text, images, html, mpg, wav and zip files etc. without modification to the routine or concern for the file being downloaded, nor is there any apparent size restriction or limitation.

Private Declare Function URLDownloadToFile Lib "urlmon" _
   Alias "URLDownloadToFileA" _
  (ByVal pCaller As Long, _
   ByVal szURL As String, _
   ByVal szFileName As String, _
   ByVal dwReserved As Long, _
   ByVal lpfnCB As Long) As Long

Private Const ERROR_SUCCESS As Long = 0
Private Const BINDF_GETNEWESTVERSION As Long = &H10
Private Const INTERNET_FLAG_RELOAD As Long = &H80000000

Public Function DownloadFile(sSourceUrl As String, _
                             sLocalFile As String) As Boolean

  //'Download the file. BINDF_GETNEWESTVERSION forces 
  //'the API to download from the specified source. 
  //'Passing 0& as dwReserved causes the locally-cached 
  //'copy to be downloaded, if available. If the API 
  //'returns ERROR_SUCCESS (0), DownloadFile returns True.
   DownloadFile = URLDownloadToFile(0&, _
                                    sSourceUrl, _
                                    sLocalFile, _
                                    BINDF_GETNEWESTVERSION, _
                                    0&) = ERROR_SUCCESS

End Function

FYI - in testing on Windows 7, it would only return the cached version, so I had to use the extra function mentioned in the article to clear it first (and that worked).

Private Declare Function DeleteUrlCacheEntry Lib "Wininet.dll" _
   Alias "DeleteUrlCacheEntryA" _
  (ByVal lpszUrlName As String) As Long

Then just call the above function with the destination URL first, to clear the cache.

don't need the Internet Transfer control

Download File - VB6 - Stack Overflow

vb6 download
Rectangle 27 36

You could supply a resourceLoader delegate to take over control of the resource loading process from AVPlayer and then supply it the data as and when it requests and becomes available. The resource loader is a property on AVURLAsset. I've documented a full solution on my blog but the main idea is to switch the protocol of your URL to something custom so AVURLAsset's resource loader requires your application's assistance in loading that URL. Then when you get the AVAssetResourceLoaderDelegate callbacks, start downloading the file and try to respond to the pending requests received from those delegate callbacks as and when you have data. This will allow progressive loading/playback of the content without having to run a full blown HTTP server in your app or resorting to other complicated solutions.

Great answer! I was about to go down the route of setting up a local http server that would somewhat act as a proxy, but this solution seems way more elegant. Will definitely give it a try.

Do you know which changes I have to make to get this working for video files? For some reason the player status changes to failure. I basically just inserted a video file instead of mp3 and added an avplayerlayer. The download starts and everything looks fine, but then the player's status changes from 0 (unknown) to 2 (failure)

Nice! Have you run into the problem described here? We've got the same issue: stackoverflow.com/questions/29683567/

the code works great for audio, but not for video :(

iphone - Saving buffer data of AVPlayer - Stack Overflow

iphone ios cocoa-touch avplayer
Rectangle 27 108

As Brandon Tilley said, but with the appropriate control flow:

var http = require('http');
var fs = require('fs');

var download = function(url, dest, cb) {
  var file = fs.createWriteStream(dest);
  var request = http.get(url, function(response) {
    response.pipe(file);
    file.on('finish', function() {
      file.close(cb);
    });
  });
}

Without waiting for the finish event, naive scripts may end up with an incomplete file.

cb
file.close

the callback is confusing me. if I now invoke download(), how would I do it? What would I place as the cb argument? I have the download('someURI', '/some/destination', cb) but don't understand what to put in the cb

@Abdul You specify the callback with a function only if you need to do something when the file has been successfully fetched.

javascript - How to download a file with Node.js (without using third-...

javascript node.js
Rectangle 27 41

WebBrowser is actually in the System.Windows.Forms namespace and is a visual control that you can add to a form. It is primarily a wrapper around the Internet Explorer browser (MSHTML). It allows you to easily display and interact programmatically with a web page. You call the Navigate method passing a web URL, wait for it to complete downloading and display and then interact with the page using the object model it provides.

HttpWebRequest is a concrete class that allows you to request in code any sort of file over HTTP. You usually receive it as a stream of bytes. What you do with it after that is up to your application.

HttpWebResponse allows you to process the response from a web server that was previously requested using HttpWebRequest.

WebRequest and WebResponse are the abstract base classes that the HttpWebRequest and HttpWebResponse inherit from. You can't create these directly. Other classes that inherit from these include Ftp and File classes.

WebClient I have always seen as a nice helper class that provides simpler ways to, for example, download or upload a file from a web url. (eg DownloadFile and DownloadString methods). I have heard that it actually uses HttpWebRequest / HttpWebResponse behind the scenes for certain methods.

If you need more fine grained control over web requests and responses, HttpWebRequest / HttpWebResponse are probably the way to go. Otherwise WebClient is generally simpler and will do the job.

Needs bold... :) jk, but thanks!

You're actually right, done. Are you really 12? You write more clearly than most people 3 times your age! It's great to see younger people on StackOverflow. If you want to be a programmer later on you'll learn a huge amount of good information here.

@Ash lol about the bold, but yes, I am 12 :). Thank you!

c# - .NET: WebBrowser, WebClient, WebRequest, HTTPWebRequest... ARGH! ...

c# .net system.net
Rectangle 27 1

You should use a PHP page to control access to the resources, rather than having the /files/ directory serve the content directly via the web server.

For example, a simple PHP page can read a file from the filesystem and serve this up so that it is downloaded to the browser.

You would want to ensure:

The simple example in that URL is vulnerable to directory traversal in the file parameter. You should validate any filename that is passed to your PHP script to protect against "../.." type attacks. This can actually get quite complex.

What may work for you is to have a token system where files are referenced by a unique, complex, random token. The database stores the actual file location on the filesystem, and when a request is recevied such as /download.php?token=blah... you lookup a) the location of the file referenced by token "blah", and b) that the session of the calling user is permitted to access the file. If all is well, serve the file to the user, otherwise raise an error and log the illegitimate access.

php - File Upload: User Security When Downloading - Stack Overflow

php security file-upload file
Rectangle 27 2

If you use asp.net, you can control pdf filename through page (url) file name. As other users wrote, Acrobat is a bit s... when it choose the pdf file name when you press "save" button: it takes the page name, removes the extension and add ".pdf". So /foo/bar/GetMyPdf.aspx gives GetMyPdf.pdf.

The only solution I found is to manage "dynamic" page names through an asp.net handler:

  • create a class that implements IHttpHandler
  • map an handler in web.config bounded to the class

Mapping1: all pages have a common radix (MyDocument_):

<httpHandlers>  
<add verb="*" path="MyDocument_*.ashx" type="ITextMiscWeb.MyDocumentHandler"/>

Mapping2: completely free file name (need a folder in path):

<add verb="*" path="/CustomName/*.ashx" type="ITextMiscWeb.MyDocumentHandler"/>

http - "name" web pdf for better default save filename in Acrobat? - S...

http pdf content-type acrobat
Rectangle 27 4

Your web server can not see the files outside the DocRoot, so it can not serve the files via the browser with direct links. You need to print their contents into the browser with readfile() with the headers properly set.

To make this work, you need to change the configuration in indexer.php:

// this way it works with accentuated letters in Windows
$Root = utf8_decode("G:\test"); // define the directory the index should be created for (can also be located outside the webserver root)

$AllowDownload = TRUE; // enclose file items with the anchor-tag (only makes sense when the files are in the webserver root)
// you need to place download.php in the same directory as indexer.php
$WebServerPath = dirname($_SERVER['SCRIPT_NAME']) . "/download.php?path="; // path where the indexed files can be accessed via a http URL (only required when $AllowDownload is TRUE)

And you have to place a new file called download.php in the same directory as indexer.php, with this content:

<?php

// it must be the same as in indexer.php
$Root = utf8_decode("G:\test");

function checkFileIsInsideRootDirectory($path, $root_directory) {
    $realpath = realpath($path);

    if (!file_exists($realpath))
        die("File is not readable: " . $path);

    // detects insecure path with for example /../ in it
    if (strpos($realpath, $root_directory) === false || strpos($realpath, $root_directory) > 0)
        die("Download from outside of the specified root directory is not allowed!");
}

function forceDownload($path) {
    $realpath = realpath($path);

    if (!is_readable($realpath))
        die("File is not readable: " . $path);

    $savename = (basename($path));

    header("Pragmaes: 0");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Cache-Control: private", false);
    header("Content-type: application/force-download");
    header("Content-Transfer-Encoding: Binary");
    header("Content-length: " . filesize($path));
    header("Content-disposition: attachment; filename=\"$savename\"");

    readfile("$path");
    exit;
}

if (!isset($_GET['path']))
    die("Path not specified!");

$fullPath = $Root . $_GET['path'];

checkFileIsInsideRootDirectory($fullPath, $Root);

forceDownload($fullPath);
indexer

Thanks for your ongoing support:) Where should I put the code and what does it need to replace?

@Jopper As I wrote, you need only to change the config parameters in indexer.php (in fact only $WebServerPath is changed to hack the download url), and you need to create a new php script which handles the downloads, and it must be named according to the $webServerPath's value (download.php in this case).

It is also possible to combine the two files into one, but it seemed to be simpler this way (and I didn't want to modify indexer.php).

html - PHP display/download directory files outside the webserver root...

php html directory
Rectangle 27 4

First, you have to designate your file field as the content type's "primary" field. Unfortunately this option doesn't show up in the UI so you have to edit the XML version of the schema (there's a button for this in recent versions of the dexterity control panel). Add xmlns:marshal="http://namespaces.plone.org/supermodel/marshal" as a namespace at the top, and add marshal:primary="true" to the field tag in question.

Then, find your type in portal_types and change the "Default view method" to @@download. (It usually starts out as view for Dexterity content types.) This should make the item's URL download the file rather than showing the normal view. It knows which field to use because you designated it as primary.

You can still access the normal view by adding /view to the end of the item's URL. If you want Plone to do this when linking to the type from navigation and folder contents (just like it does for built-in images and files), go to portal_properties/site_properties and add the type's id to the typesUseViewActionInListings list.

Ohhh my god!!! A TTW solution..?! This is amazing! Thanks David! 100 points to Gryffindor. I was able to implement everything the way you mention except I added it to the typesUseViewActionInListings and it doesn't go to /view automatically, it still downloads the file. I'm totally okay with this though for now. Thanks David!! :)

plone - Linking to a "File type" Dexterity Content Type - Stack Overfl...

plone dexterity plone-4.x
Rectangle 27 1

header('Cache-Control: public');  
header('Content-Description: File Transfer');  
header('Content-type: application/force-download');
header('Content-Disposition: attachment; filename="'.$filename.'"');

You could also try using cURL instead of readfile(), something like:

function file_get_contents_curl($url) {
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //Set curl to return the data instead of printing it to the browser.
    curl_setopt($ch, CURLOPT_URL, $url);

    $data = curl_exec($ch);
    curl_close($ch);

    return $data;
}
if(!file_exists($fileName)) {
   die('Zip file not found');
}
else {
   $file_content = file_get_contents($fileName);  // To download the ZIP file
   header('Cache-Control: public');  
   header('Content-Description: File Transfer');  
   header('Content-type: application/force-download');
   header('Content-Disposition: attachment; filename="'.$filename.'"');
   echo $file_content;
}
exit;

I have edited my post with the response headers from Firebug. Still it doesn't work.

I also have edited my response, maybe using cURL instead of readfile() could be of help. I'm not 100% sure but you could give it a try.

It's still the same, I will be trying to see if it is related to zip files only by sending csv files.

Well the csv doesn't work as well, checked in all browsers its the same problem.

I've used your original code, as well as those included in my answer and both work. Only difference is my PHP version (which I doubt is the reason of the problem) and my platform: Server:Apache/2.4.6 (Unix) PHP/5.5.1. I'm wondering how is your export button calling this function? It's indeed pretty weird though, in theory everything you have should just "work".

PHP Zip file download issue - Stack Overflow

php
Rectangle 27 0

From what I can tell on the javascript plugin the URL is coded into the file. Therefore the PHP file that emits the CSV file for download controls the details of the CSV file. To get around this you could easily modify the plugin and change the URL then host your own CSV generation tool that emits the file name you wish in any format. Todo this you must get the source for the javascript plugin, and the source for the PHP file.

From this page you can change the URL from the following line. (Line 48 on GIT)

Highcharts.post('http://www.highcharts.com/studies/csv-export/csv.php', {
                csv: this.getCSV()
            });

As you see the URL is coded in there to csv.php. Now reading through that file the PHP source code is also available. And its quite simple.

Now in this file you will see the file name is statically set to chart.csv on line 10.

header('Content-disposition: attachment;filename=chart.csv');

You can simply change the filename=chart.csv to anything you wish.

Now doing this means you must be hosting a PHP server (you can rewrite this in other languages) and you must use your copy of the javascript file.

javascript - How I can customize the file name when exporting using th...

javascript php jquery csv highcharts
Rectangle 27 0

You must install the ActiveX control in question on each client computer. If you want the page itself to offer it as a download, add a CODEBASE attribute to your object tag that contains the URL of the .DLL or OCX file that the browser should download. For download and install to work inside the browser, you must digitally sign the file: http://blogs.msdn.com/b/ieinternals/archive/2011/03/22/authenticode-code-signing-for-developers-for-file-downloads-building-smartscreen-application-reputation.aspx

i have written the codebase into the object tag it asked for download the ActiveX control & i have stored the dll file into the apache htdocs folder it start downloading but it display the message box as Error Windows has blocked this software because it cannot verify the publisher any solution

c# - how to access the registered ActiveX control from the LAN network...

c# apache activex webserver
Rectangle 27 0

It depends what do you mean. If you want to measure network speed when downloading or uploading something you can create network connection, send some garbage and measure how long does it take to send. Better results can be achieved if both server and client sides are under your control. But you can even write simple client that downloads file from external URL and measure how long does it take.

If you wish to know measure network parameters of other applications I recommend you to read about JPcap.

thanks for your response. but what i want is to no the network utilization for any time i want, not the network power.

networking - using java to get network utilization - Stack Overflow

java networking network-programming