Error html download

In html5 i am trying to use download attribute , here is a sample code If a link is invalid or forbidden it still downloads a forbidden html...

In html5 i am trying to use download attribute , here is a sample code

<a href="/images/myw3schoolsimage.jpg" download>

If a link is invalid or forbidden it still downloads a forbidden html error page or some other error page. Instead is there a way to check if the header is 200 or download resource if only accessible/exists?

asked Dec 12, 2017 at 2:34

loveprogramming's user avatar

3

I just solved the problem with this solution, for a PDF download:

const onDownloadClick = async (evt) => {
    const anchor = evt.target.parentNode;

    try {
        const response = await axios({
            method: 'get',
            url: '/pdf',
            responseType: 'blob',
            headers: {
                'Accept': 'application/pdf'
            }
        });

        const blob = new Blob([response.data], {
            type: 'application/pdf',
        });
        anchor.href = window.URL.createObjectURL(blob);
        anchor.download = 'filename.pdf';
        anchor.click();
    } catch (err) {
        console.log(err);
    }
}

Initially, the link does not have the download attribute. I just set it dynamically and simulate clicking on the link with JavaScript. For images, you just need a different header and blob type. image/jpeg would do it, i guess.

answered Aug 24, 2018 at 9:17

andyrandy's user avatar

andyrandyandyrandy

72.1k8 gold badges111 silver badges129 bronze badges

Designing an API that serves files to be downloaded is not easy. In a way, it is an exception to the standard way of designing APIs. Nowadays most APIs produce XML or JSON, and that is not the case with download, which produces the format of the file being downloaded.

Multiple methods are deployed to achieve the goal of making a browser accept a file and start the downloading process. We’ll discuss some of them, along with their advantages and disadvantages.

OBJECTIVES

Our main objective is to ensure a robust file downloading process. That means the detection of download failures as well.

Let’s assume the most demanding use case (not including on-the-fly encryption): on event (e.g. button click) start the download process (browser taking control of pausing/stopping, progress tracking) but if for some reason the download failed show dialog and inform user, staying on the same page. This is not as easy as it sounds at first glance — and we will write about this in a moment.

Other objectives:

  • Preserve original file name and extension
  • Preserve content-type
  • User shall be notified about download start immediately (not wait until it is finished)
  • Make no difference between small files (a couple of kilobytes) and big ones (few gigabytes)
  • Take advantage of file streaming (chunked response) if possible

PROBLEM

While designing standard APIs, there are best practices to follow. So, various styles are created, e.g. SOAP, REST (or REST-like), GraphQL, and so on. In this blog, we’ll focus on a REST-like approach but the same applies to others, especially GraphQL.

There are two ways to signal to an API consumer that something went wrong: 

  • HTTP status codes (e.g. 404 – NOT FOUND, 400 – BAD REQUEST
  • Structured response indicating error

HTTP status codes are easy but limited. For example the 400 BAD REQUEST status code – it tells us that our input may be malformed or incorrect. But it won’t tell us anything else, e.g. what fields are incorrect.

A structured response may have a little more information, but it may be harder to use. For example, we may structure our JSON response as follows:

{
 "success": true|false,
 "data": {
   "some_data_if_success": 1
 },
 "error": {
   "error_info_if_failure": 0
 }
}

Usually, a combination of http status code and structured responses is used, even in case of error.

But, for download there is an exception! Our goal is to make browsers handle downloading and all subsequent things (user interaction, pausing, resuming, progress tracking, download speed tracking and so on), which nowadays browsers are very good at. So we need to serve files directly, not via structured response. Also, we are serving different kinds of files, not JSON, but we’ll discuss this as well.

There are several methods for downloading files, and they all are shortly described below.

DOWNLOAD FILES FROM BACKEND

To keep our blog concise as possible, we’ll use NodeJS with Express for our backend example. The server starts at port 8082, allows CORS for our example frontend app (on port 8000, see below) and exposes Content-Disposition header, so we can extract filename from header in some of our methods. Only one route is present – to download the file. Path parameter should_fail is used to simulate download failure.

This code will be updated later to accommodate new download methods.

const express = require('express');
const cors = require('cors');

const app = express();
app.use(cors({
 origin: 'http://localhost:8000',
 credentials: true,
 exposedHeaders: ['Content-Disposition']
}))

app.get('/download/:should_fail', function (req, res) {
  if (req.params.should_fail === 'true') {
    res.status('404').send("Download failed!")
  } else {
    res.download(`${__dirname}/sample.pdf`);
  }
})

var server = app.listen(8082, function () {
  console.log(`Started server at port ${server.address().port}!`);
})

POSSIBLE SOLUTIONS

All methods are written in plain JavaScript without any external libraries. ES6 is used. For simplicity, the code is served using python’s simple http server, but other web servers could be used (e.g. Apache, nginx, …). Python’s server will start at port 8000.

We can start the server like this:

For python2:

python -m SimpleHTTPServer

For python3:

python -m http.server

Method 1: Wrapped download response

The first possible solution we’ll discuss is to somehow include the downloaded file inside the structured response. Of course, file content shall be encoded in some form, e.g. Base64, because file content may not be text (it may be binary data), and structured response (e.g. JSON) is a text, and there can be misinterpretation of file content bytes leading to a corrupted file.

An example may look like this (actual content is obviously trimmed down):

{
 "success": true,
 "data": {
   "file_name": "sample.pdf",
   "content_type": "application/pdf",
   "content": "JVBER ... NCg=="
 }
}

This way we can detect possible errors, field success will be false and error field will be present indicating the nature of the error. However, there are many disadvantages with this approach:

  • The file must be encoded (e.g. via Base64) on the backend which takes CPU time, and probably RAM resources if the encoding is not done in a streaming fashion
  • The file cannot be streamed
  • The user must wait for the request to finish before the download will be shown
  • The browser tricks may be deployed to trigger the download (e.g. via data URL, will be described in another method)
  • The file must be decoded on the user’s browser which also takes CPU time and this time almost certainly RAM resources because whole response will be in memory at one point

Advantages:

  • Can detect errors
  • The user stays on the same page (no refreshing, no redirects)
  • May be acceptable for (very) small files e.g. user avatars or some icons.

Method 2: AJAX/FETCH request

As already stated, the biggest problem is how to reliably detect download errors and do something about them. With this method we use AJAX to perform a direct call to the backend, fetch file, read content-type or HTTP status code to determine if the download is successful and then use some tricks to determine filename and trigger download.

To determine filename, we can read Content-Disposition header which may look like this: content-disposition: attachment; filename=”sample.pdf”. Filename can be extracted via RegEx (see this StackOverflow answer) or in some other way.

When a response is received we check for status code and if it is 404 (see server implementation above) we show some kind of a dialog. Otherwise, we prepare the anchor element (link) and set its href property. There are two ways of doing this:

  1. As a data url: we construct data url as follows:
    data:<CONTENT_TYPE>;base64,<ACTUAL_DATA>, for example: data:application/pdf;base64,JVBER … NCg==
  2. As an URL object: we create Blob (with specified content type) and create URL object, like: window.URL.createObjectURL(blob)

Option 2 is preferred because it is much better for big files (some browsers may stream it into their internal buffer), and can be revoked (removed from memory).

Here is a code snippet, using the fetch API (shorter and more robust than plain old AJAX). 

let downloadedBlob;
function download(shouldFail) {
   fetch(`http://localhost:8082/download/${shouldFail}`)
       .then(response => {
           const statusCode = response.status;
           if (statusCode === 404) {
               alert("Download failed!") //show real dialog
           } else {
               let link = document.getElementById("ex-download-link");
               if (!link) { //element not created yet
                   link = document.createElement('a');
                   link.id = 'ex-download-link';
                   document.body.appendChild(link);
               }
               if (downloadedBlob) { //check if URL component is already created
                   window.URL.revokeObjectURL(downloadedBlob);
                   downloadedBlob = 'undefined';
               }
               response.blob().then(blob => {
                   const disposition = response.headers.get("Content-Disposition");
                   link.download = extractFilename(disposition);
                   downloadedBlob = blob;
                   link.href = window.URL.createObjectURL(blob);
                   link.click();
               })
           }
       })
}

Code is called as download(true) or download(false). We may add on Click listeners to two buttons to demonstrate this.

<button onclick="download(true)">Download (fail)</button>
<button onclick="download(false)">Download (success)</button>

Advantages:

  • Detects errors
  • The user stays on the same page (no refresh, no redirect)
  • May be acceptable for (very) small files e.g. user avatars or some icons.

Disadvantages:

  • Event if the file is streamed from backend, it is fully loaded on browser
  • The user must wait for the request to finish before download will be shown
  • Browser tricks may be deployed to trigger the download (data url or createObjectUrl)

Method 3: Simple redirect

This is probably the most simple method here. It just redirects the app to the backend URL which is serving files. Redirect is done by the browser so all cookies are sent as well and the backend can authenticate the request.  

<button onclick="download(true)">Download (fail)</button>
<button onclick="download(false)">Download (success)</button>
function download(shouldFail) {
   window.location.href = `http://localhost:8082/download/${shouldFail}`;
}

Advantages:

  • Simple
  • The file can be streamed if supported
  • The filename is preserved
  • No need to encode on frontend or backend
  • The user is notified immediately
  • When download is successful, there is no redirect nor refresh

Disadvantages:

  • When a download fails, the user is really redirected to the page (Figure 1), which may not be acceptable. Actually, one of our mandatory goals from the beginning of the blog is that no redirects are not allowed.

download failed

Figure 1, this is shown in case of download failure

So, if there is no requirement to stay on the same page, this method is preferred. But in other cases and in cases of single-page applications, this is not acceptable.

Method 4: HEAD and GET

This solution requires lifting the weight to the backend. The idea is that the frontend app first sends a HEAD http request (via e.g. fetch from method 2) to the backend to check if the file is there or if there are any errors with the file. Backend may respond via header and/or http status code. If the frontend app concludes that there are no errors, it may fallback to classic window.location.href = workingUrl from method 3.

function download(shouldFail) {
   const URL = `http://localhost:8082/download/${shouldFail}`;
   fetch(URL, {method: 'HEAD'})
       .then(response => {
           const statusCode = response.status;
           if (statusCode === 404) {
               alert("Download failed!") //show real dialog
           } else {
               window.location.href = URL; //from method 3, actual GET
           }      
       })
}

Advantages:

  • The file streaming is supported if possible
  • The user stays on the same page (no refresh, no redirect)
  • Fairly simple
  • Detects errors if any
  • The user is notified immediately
  • The filename is preserved

Disadvantages:

  • Two requests required
  • Complex backend logic. For example if retrieving a file means that it is created on the backend (e.g. real-time reports), the backend must create the file twice (for HEAD and GET requests) or somehow store it between the request (which is also a problem if the file is deleted after being served – how long to keep the file, what if the GET request is never done…)
  • There may not be a guarantee that the GET request will succeed. E.g. if the backend is retrieving a file from Amazon S3 and on HEAD there is a file but on the second request, the GET one, the file may not be there and we have our first problem. Also, imagine the complexity of the HEAD method on the backend to check if there is a file on another, external, server (eg. the S3) without retrieving it!

Method 5: IFrame trick

HTML element <iframe> can be used to download files. Just like with method 2, but simpler. We create an iframe, “load” file in it and viola! Download is triggered.

function download(shouldFail) {
   let iframe = document.getElementById("ex-download-iframe");
   if (!iframe) { //element not created yet
       iframe = document.createElement('iframe');
       iframe.id = 'ex-download-iframe';
       iframe.style.display = 'none'
       document.body.appendChild(iframe);

   }
   iframe.onload = e => {
       //what?
       //check content?
   }
   iframe.src = `http://localhost:8082/download/${shouldFail}`;
}

Advantages:

  • Simple
  • The user stays on the same page (no refresh, no redirect)
  • May support file streaming
  • The user is immediately notified of the download process

Disadvantages:

  • Impossible (or really hard) to detect download failure. Because the iframe is hidden, on download failure nothing happens from the user’s perspective.
  • We do have onload event, but it is hard to retrieve content (impossible on a different domain because of CORS) and if we somehow do retrieve the content, what about it? To check specific strings? When? When download is finished? Those are the questions that are steering us from this method.

Method 6: Backend redirect

Backend can redirect (via 302 FOUND status code) response in case of a download failure. This differs from method 3 (window.location.href = url) in a way that different URL may be specified and if some advanced framework is used on the frontend, it may trigger a specific route which will show the desired dialog. For example, the backend may redirect to <frontend.url>/components/download-error. If that URL can be used to show dialog only and not redirect or refresh, our problem is solved!

In this approach we can use AngularJS or some advanced framework with substate management to achieve a desired result. Backend would redirect to some route, the app will follow it and show dialog without redirecting. We tried an approach with AngularJS and it’s working fine, but unfortunately, we couldn’t avoid refresh. So if you have some ideas to make it work, please let us know.

Advantages: same as with method 3, but the real disadvantage is refresh.

SOLUTION

To achieve all of our goals from the beginning of the blog, we figured out this solution. The idea is that the backend returns executable JavaScript code in case of a download error. Returned JavaScript will do a very simple task: post a message to the parent that says “download error happened”. 

const express = require('express');
const cors = require('cors');

const app = express();
app.use(cors({
 origin: 'http://localhost:8000',
 credentials: true,
 exposedHeaders: ['Content-Disposition']
}))

app.get('/download/:should_fail', function (req, res) {
  if (req.params.should_fail === 'true') {
    res.status('404')
       .header('Content-Type', "text/html")
       .send(`
       <!DOCTYPE html>
         <html lang="en">
           <head>
             <script>
               window.onload = () => parent
                 .postMessage('download.error', 'http://localhost:8000');
             </script>
           </head>
           <body>
           </body>
         </html>`
       )
  } else {
    res.download(`${__dirname}/sample.pdf`);
  }
})

var server = app.listen(8082, function () {
  console.log(`Started server at port ${server.address().port}!`);
})

The script is sent in a <head> tag. When the body finishes loading (and that is when the body is loaded into our iframe), a message is posted to the parent window.

Our modified frontend looks like this:

const SERVER = 'http://localhost:8082';
//listen to events 
const event = window.addEventListener ? 'addEventListener' : 'attachEvent';
const messageEvent = window.addEventListener ? 'message' : 'onmessage';
const eventFunction = window[event];
eventFunction(messageEvent, listenToEvents); //listen to events

function download(shouldFail) {
   let iframe = document.getElementById("ex-download-iframe");
   if (!iframe) { //element not created yet
       iframe = document.createElement('iframe');
       iframe.id = 'ex-download-iframe';
       iframe.style.display = 'none';
       document.body.appendChild(iframe);

   }
   iframe.src = `${SERVER}/download/${shouldFail}`;
}
function listenToEvents(event) {
   const key = event.data ? 'data' : 'message';
   if (event.origin === SERVER
           && event[key] === 'download.error') {
       alert ('Download failed'); //show real dialog
   }
}

On the frontend, we register postMessage listener to listenToEvents function. When download is successful, iframe will load content and start the downloading process. In case of a failed download, an iframe will load our HTML we returned from the backend. That HTML contains JavaScript code that sends a message “download.error” to its parent. We specify the origin of the parent (frontend app).

On the frontend, listenToEvents will be triggered when an iframe loads JavaScript code that sends a message. We check for origin (mandatory! Malicious sites can send messages too) and if message data is “download.error” we show the dialog.

To support older browsers (e.g. IE8), we need to check if addEventListener is available, so the code that attaches itself for events may look like this.

const SERVER = 'http://localhost:8082';
//listen to events 
const event = window.addEventListener ? 'addEventListener' : 'attachEvent';
const messageEvent = window.addEventListener ? 'message' : 'onmessage';
const eventFunction = window[event];
eventFunction(messageEvent, listenToEvents); //listen to events

function download(shouldFail) {
   let iframe = document.getElementById("ex-download-iframe");
   if (!iframe) { //element not created yet
       iframe = document.createElement('iframe');
       iframe.id = 'ex-download-iframe';
       iframe.style.display = 'none';
       document.body.appendChild(iframe);

   }
   iframe.src = `${SERVER}/download/${shouldFail}`;
}
function listenToEvents(event) {
   const key = event.data ? 'data' : 'message';
   if (event.origin === SERVER
           && event[key] === 'download.error') {
       alert ('Download failed'); //show real dialog
   }
}

SUMMARY & CONCLUSION

The title “How to detect download errors” is justified by showing multiple ways of detecting errors. Every method has its advantages and disadvantages, and we listed most of them

# Description Disadvantages
1 Wrapped download response CPU & Memory resources on the backend

CPU & Memory resources on the frontend

Cannot be streamed

Must wait for download to finish

Not suitable for larger files

2 AJAX/FETCH Must wait for download to finish

The file must be loaded in browser

Not suitable for larger files

3 Simple redirect User is redirected to page with content that is served in case of error
4 HEAD & GET Complex backend logic

May still fail

5 IFrame In case of error, it may be ignored silently

Cannot reliably detect download failure

6 Backend redirect It may be redirect anyway

Complex sub-state logic on frontend

Two requests & still may fail

7 IFrame & JS postWindow Backend must be changed (not too much)

Backend must know frontend origin

For one (rather specific) case “detect download error and show a dialog if it happens, staying on the same page without refreshing it”, the last method was the solution because it fulfills all the objectives from the beginning of the blog including file streaming.

For other use cases, method 3 is probably best, it is easy to implement, covers most cases and concerns, and it can notify users about failed download via a simple redirect to a “generic” page e.g. “Download failed… Go Back (link/button)”.

Last Updated: 07/15/2022
[Time to Read Article: 5 minutes]

Error.html is considered a type of Hypertext Markup Language file. It is most-commonly used in Wondershare UniConverter 11 developed by Wondershare Software Co., Ltd.. It uses the HTML file extension and is considered a HTML (Hypertext Markup Language) file.

The first release in the Windows 10 Operating System for error.html was on 07/27/2018 inside Hotspot Shield 7.9.0.

The latest file update released for Wondershare UniConverter 11 was on 05/08/2019 [file version 11].

Error.html is included in Wondershare UniConverter 11, Wondershare Filmora 9.2, and DVD Slideshow Builder Deluxe 6.5.1.

In this article, you will find detailed error.html information, a HTML file troubleshooting guide, and a list of versions that are available for free download.

What are error.html Error Messages?

General error.html Runtime Errors

Error.html file errors often occur during the startup phase of Wondershare UniConverter, but can also occur while the program is running.
These types HTML errors are also known as “runtime errors” because they occur while Wondershare UniConverter is running. Here are some of the most common error.html runtime errors:

  • error.html could not be found.
  • error.html error.
  • error.html failed to load.
  • Error loading error.html.
  • Failed to register error.html / Cannot register error.html.
  • Runtime Error — error.html.
  • The file error.html is missing or corrupt.

Microsoft Visual C++ Runtime Library

Runtime Error!

Program: C:Program Files (x86)Common FilesWondershareWondershare Helper CompactPageserror.html

This application has requested the Runtime to terminate it in an unusual way.
Please contact the application’s support team for more information.

Most HTML errors are due to missing or corrupt files. Your error.html file could be missing due to accidental deletion, uninstalled as a shared file of another program (shared with Wondershare UniConverter), or deleted by a malware infection. Furthermore, error.html file corruption could be caused from a power outage when loading Wondershare UniConverter, system crash while loading or saving error.html, bad sectors on your storage media (usually your primary hard drive), or malware infection. Thus, it’s critical to make sure your anti-virus is kept up-to-date and scanning regularly.

How to Fix error.html Errors in 3 Steps (Time to complete: ~5-15 minutes)

If you’re encountering one of the error messages above, follow these troubleshooting steps to resolve your error.html issue. These troubleshooting steps are listed in the recommended order of execution.

Step 1: Restore your PC back to the latest restore point, «snapshot», or backup image before error occurred.

To begin System Restore (Windows XP, Vista, 7, 8, and 10):

  1. Hit the Windows Start button
  2. When you see the search box, type «System Restore» and press «ENTER«.
  3. In the search results, find and click System Restore.
  4. Please enter the administrator password (if applicable / prompted).
  5. Follow the steps in the System Restore Wizard to choose a relevant restore point.
  6. Restore your computer to that backup image.

If the Step 1 fails to resolve the error.html error, please proceed to the Step 2 below.

Step 2: If recently installed Wondershare UniConverter (or related software), uninstall then try reinstalling Wondershare UniConverter software.

You can uninstall Wondershare UniConverter software by following these instructions (Windows XP, Vista, 7, 8, and 10):

  1. Hit the Windows Start button
  2. In the search box, type «Uninstall» and press «ENTER«.
  3. In the search results, find and click «Add or Remove Programs«
  4. Find the entry for Wondershare UniConverter 11 and click «Uninstall«
  5. Follow the prompts for uninstallation.

After the software has been fully uninstalled, restart your PC and reinstall Wondershare UniConverter software.

If this Step 2 fails as well, please proceed to the Step 3 below.

Wondershare UniConverter 11

Wondershare Software Co., Ltd.

Step 3: Perform a Windows Update.

When the first two steps haven’t solved your issue, it might be a good idea to run Windows Update. Many error.html error messages that are encountered can be contributed to an outdated Windows Operating System. To run Windows Update, please follow these easy steps:

  1. Hit the Windows Start button
  2. In the search box, type «Update» and press «ENTER«.
  3. In the Windows Update dialog box, click «Check for Updates» (or similar button depending on your Windows version)
  4. If updates are available for download, click «Install Updates«.
  5. After the update is completed, restart your PC.

If Windows Update failed to resolve the error.html error message, please proceed to next step. Please note that this final step is recommended for advanced PC users only.

If Those Steps Fail: Download and Replace Your error.html File (Caution: Advanced)

If none of the previous three troubleshooting steps have resolved your issue, you can try a more aggressive approach (Note: Not recommended for amateur PC users) by downloading and replacing your appropriate error.html file version. We maintain a comprehensive database of 100% malware-free error.html files for every applicable version of Wondershare UniConverter. Please follow the steps below to download and properly replace you file:

  1. Locate your Windows operating system version in the list of below «Download error.html Files».
  2. Click the appropriate «Download Now» button and download your Windows file version.
  3. Copy this file to the appropriate Wondershare UniConverter folder location:

    Windows 10: C:Program Files (x86)Common FilesWondershareWondershare Helper CompactPages
    Windows 10: C:Program FilesTrend MicroTitaniumwwwMainConsole.cmptpluginsProtectedBrowser.cmptresourcescommon.lproj
    Windows 10: C:Program Files (x86)Common FilesWondershareWondershare Helper CompactPages
    Windows 10: C:xampptomcatwebappsexamplesjsperror
    Windows 10: C:Program FilesTrend MicroTitaniumwwwMainConsole.cmptpluginsQuietMode.cmptresourcescommon.lproj

    Show 11 more directories +

    Windows 10: C:Program FilesTrend MicroTitaniumwwwMainConsole.cmptpluginsProtectedBrowser.cmptresourcescommon.lproj
    Windows 10: C:Program FilesMATLABR2019bhelpmatlabref
    Windows 10: C:Program FilesTrend MicroTitaniumwwwMainConsole.cmptpluginsProtectedBrowser.cmptresourcescommon.lproj
    Windows 10: C:Program FilesTrend MicroTitaniumwwwMainConsole.cmptpluginsQuietMode.cmptresourcescommon.lproj
    Windows 10: C:Program FilesMATLABR2019btoolboxmatlabconnector2connectordocroot
    Windows 10: C:Program FilesTrend MicroTitaniumwwwMainConsole.cmptpluginsQuietMode.cmptresourcescommon.lproj
    Windows 10: C:Program Files (x86)AdobeAdobe Creative CloudACCresourceuihostlegacyerror
    Windows 10: C:Program Files (x86)Foxit SoftwareFoxit ReaderConnectedPDFen-USwelcome
    Windows 10: C:Program Files (x86)Hotspot Shieldhtdocs
    Windows 10: C:Program Files (x86)WinHTTrackhtmlserver
    Windows 10: C:Program Files (x86)Common FilesWondershareWondershare Helper CompactPages

  4. Restart your computer.

If this final step has failed and you’re still encountering the error, you’re only remaining option is to do a clean installation of Windows 10.

GEEK TIP : We must emphasize that reinstalling Windows will be a very time-consuming and advanced task to resolve error.html problems. To avoid data loss, you must be sure that you have backed-up all of your important documents, pictures, software installers, and other personal data before beginning the process. If you are not currently backing up your data, you need to do so immediately.

Download error.html Files (Malware-Tested 100% Clean)

CAUTION : We strongly advise against downloading and copying error.html to your appropriate Windows system directory. Wondershare Software Co., Ltd. typically does not release Wondershare UniConverter HTML files for download because they are bundled together inside of a software installer. The installer’s task is to ensure that all correct verifications have been made before installing and placing error.html and all other HTML files for Wondershare UniConverter. An incorrectly installed HTML file may create system instability and could cause your program or operating system to stop functioning altogether. Proceed with caution.

Files Related to error.html

HTML Files Related to error.html

File Name Description Software Program (Version) File Size (bytes) File Location
error.html Hypertext Markup Language Wondershare UniConverter 11 1274 C:Program Files (x86)Common FilesWondershare…
vcu11slice.html Hypertext Markup Language Wondershare UniConverter 11 23229 C:Program Files (x86)WondershareVideo Conver…
LoadingPage.html Hypertext Markup Language Wondershare UniConverter 11 6400 C:UsersTesterAppDataLocalMicrosoftOneDriv…
sites.html Hypertext Markup Language Wondershare UniConverter 11 8105 C:Program Files (x86)WondershareVideo Conver…
cd.html Hypertext Markup Language Wondershare UniConverter 11 17693 C:Program Files (x86)WondershareVideo Conver…

You are downloading trial software. The purchase of a one-year software subscription at the price of $39.95 USD is required to unlock all software features. Subscription auto-renews at the end of the term (Learn more). By clicking the «Start Download» button above and installing «Software», I acknowledge I have read and agree to the Solvusoft End User License Agreement and Privacy Policy.

The download() function of the downloads API downloads a file, given its URL and other optional preferences.

If the URL uses the HTTP or HTTPS protocol, the request includes all the relevant cookies, that is, those cookies set for the URL’s hostname, secure flag, path, and so on. The default cookies, the cookies from the normal browsing session, are used unless:

  • the incognito option is used, then the private browsing cookies are used.
  • the cookieStoreId option is used, then the cookies from the specified store are used.

If both filename and saveAs are specified, the Save As dialog is displayed, populated with the filename.

This is an asynchronous function that returns a Promise.

Syntax

let downloading = browser.downloads.download(
  options                   // object
)

Parameters

options

An object specifying what file you wish to download, and any other preferences you wish to set concerning the download. It can contain the following properties:

allowHttpErrors Optional

A boolean flag that enables downloads to continue even if they encounter HTTP errors. Using this flag, for example, enables the download of server error pages. Default value false. When set to:

  • false, the download is canceled when it encounters an HTTP error.
  • true, the download continues when an HTTP error is encountered and the HTTP server error is not reported. However, if the download fails due to file-related, network-related, user-related, or other error, that error is reported.
body Optional

A string representing the post body of the request.

conflictAction Optional

A string representing the action you want taken if there is a filename conflict, as defined in the downloads.FilenameConflictAction type (defaults to «uniquify» when it is not specified).

cookieStoreId Optional

The cookie store ID of the contextual identity the download is associated with. If omitted, the default cookie store is used. Use requires the «cookies» API permission.

filename Optional

A string representing a file path relative to the default downloads directory — this provides the location where you want the file to be saved, and what filename you want to use. Absolute paths, empty paths, path components that start and/or end with a dot (.), and paths containing back-references (../) will cause an error. If omitted, this value will default to the filename already given to the download file, and a location immediately inside the downloads directory.

If the URL uses the HTTP or HTTPS protocols, an array of objects representing additional HTTP headers to send with the request. Each header is represented as a dictionary object containing the keys name and either value or binaryValue. The headers that are forbidden by XMLHttpRequest and fetch cannot be specified, however, Firefox 70 and later enables the use of the Referer header. Attempting to use a forbidden header throws an error.

incognito Optional

A boolean: if present and set to true, then associate this download with a private browsing session. This means that it will only appear in the download manager for any private windows that are currently open.

method Optional

A string representing the HTTP method to use if the url uses the HTTP[S] protocol. This may be either «GET» or «POST».

saveAs Optional

A boolean that specifies whether to provide a file chooser dialog to allow the user to select a filename (true), or not (false).

If this option is omitted, the browser will show the file chooser or not based on the general user preference for this behavior (in Firefox this preference is labeled «Always ask you where to save files» in about:preferences, or browser.download.useDownloadDir in about:config).

Note: Firefox for Android raises an error if saveAs is set to true. The parameter is ignored when saveAs is false or not included.

url

A string representing the URL to download.

Return value

A Promise. If the download started successfully, the promise will be fulfilled with the id of the new downloads.DownloadItem. Otherwise, the promise will be rejected with an error message taken from downloads.InterruptReason.

If you use URL.createObjectURL() to download data created in JavaScript and you want to revoke the object URL (with revokeObjectURL) later (as it is strongly recommended), you need to do that after the download has been completed. To do so, listen to the downloads.onChanged event.

Browser compatibility

BCD tables only load in the browser

Examples

The following snippet attempts to download an example file, also specifying a filename and location to save it in, and uniquify as the value of the conflictAction option.

function onStartedDownload(id) {
  console.log(`Started downloading: ${id}`);
}

function onFailed(error) {
  console.log(`Download failed: ${error}`);
}

let downloadUrl = "https://example.org/image.png";

let downloading = browser.downloads.download({
  url : downloadUrl,
  filename : 'my-image-again.png',
  conflictAction : 'uniquify'
});

downloading.then(onStartedDownload, onFailed);

jquery.fileDownload.js Library

jQuery File Download is a cross server platform compatible jQuery plugin that allows for an Ajax-like file download experience that isn’t normally possible using the web.

  • Demo of jquery.fileDownload.js in action with some different examples
  • Example VS2010 MVC 3 application using jquery.fileDownload.js
  • GitHub – Send me a pull request!
  • Download jquery.fileDownload.js v1.2.0 – Changelog
  • You’ll need jQuery 1.3+ installed.
  • Fully tested on:
    • Internet Explorer 6 – 9
    • Firefox 11 – reasonably sure it will work on earlier versions
    • Chrome 17 – reasonably sure it will work on earlier versions

Features

  • Brings control back to the developer by exposing a “successCallback” and “failCallback” that allows the developer to control the user experience in either situation.
  • In conjunction with jQuery UI a developer can easily show a modal telling the user that a file download is occurring, disband the modal after the download starts or even inform the user in a friendly manner that an error has occurred. See the Demo for an example of this.
  • File downloads don’t occur in the current window’s location bar. This means if a failure or something unexpected happens the user doesn’t leave the current page they are on or even have to see an ugly error message. This is critical for a good user experience especially on a highly Ajax application.

A classic problem with browser file downloads – Error handling

In a general case a file downloads occur after a user clicks an <a href=”location“> link. The href in the instructs the browser to browse to the location indicated. This is equivalent to setting the window.location of a page using JavaScript.

When the response comes back the HTTP response headers can contain many different things (in fact almost anything). Here are some examples:

Normal, HTML Response

Content-Type: text/html; charset=utf-8

The above “Content-Type” indicates to the browser that it should parse the DOM in the response and display it to the user. The location in the user’s location bar changes to reflect the address of the just-downloaded content.

Normal, “File Download” Response

Content-Disposition: attachment; filename=Report0.pdf

The above “Content-Disposition” indicates to the browser that the server is trying to invoke a file download in the browser. The browser responds by opening up a file download dialog (or ribbon) for the user to download the file. As a convenience when the browser detects a response like this it doesn’t change the address bar so effectively the user stays on the same page.

Failed, “File Download” Response

Content-Type: text/html; charset=utf-8

As you may have guessed from that ugly highlighter color we’ve got trouble here. The response from a file download error is generally no different from a normal HTML response, the only difference here is that is has an error message as HTML content. The browser will now happily replace your existing page and address with the new error message. Not only have we now displayed an ugly error message to the user but we have also caused them to leave whatever page they were on.

Imagine you have created a nearly exclusively Ajax site like Gmail. A response like this from the server will cause your entire DOM to be replaced by an error message. Imagine this happening to you in Gmail and having to load up everything all over again. Ouch! My current role creating the framework for a highly Ajax application (like Gmail) inspired me to write this plugin for all to use – “web applications” is where the web is going anyways so there has to be a better way…

Another classic problem with browser file downloads – “Happy path” user experience

I probably just caught you thinking this: “well so what… my site never has any problems that cause error messages”… fair enough, but consider this:

  • What is the response time of your web site in terms of serving up static files? Is it instantaneous? Is a user going to immediately look in the far corners of their screen for some sort of a spinning indicator or might they get confused or angry based on their technical prowess? Maybe they are looking at one of these? http://www.ict.griffith.edu.au/images/Animation/netscape_anim.gif (I hope not or you’ve got bigger issues)
  • What if you are serving up a dynamically generated file (perhaps a report of SQL data?) based on user input that may take a few seconds. An average user might expect some sort of indication of what is going on. At the very least from a developer’s perspective it’d be nice if it wasn’t easy for them to hammer the download link a few times (to make it faster of course) wasting cycles across an entire n-tiered application.

I’ve got a solution… just use Ajax to download it!

Good idea! Unfortunately this is not possible due to one key problem:

  • JavaScript, by design, doesn’t have the ability to perform lower level tasks on a users computer out of security concerns. Initiating file download prompts is one of these limitations.

You can certainly use an XMLHttpRequest object to download a binary (or otherwise) file but there is nothing you can do to the response to somehow get it saved on the user’s computer. Flash doesn’t have this limitation, but we really don’t want to get into Flash do we?

Enter jQuery File Download

jQuery File Download overcomes all of the aforementioned limitations of a “normal” browser file downloads. Well how the heck does that work? The concept is nothing new in fact: If you browse around the web you will find plenty of forum posts discussing the same technique, I just wasn’t able to find a succinct easy to use plug-in to do it hence my decision to create this plugin. The answer is:

An iframe and cookie

What?! I have to rely on Web .1 technology to make my Web 2.0 Ajax application user friendly? Turns out this is the magic bullet combination to work around normal limitations of file downloads, here’s how:

iframe

An iframe (which is generally a mortal sin of modern web development) can exist in a DOM but in most respects is treated like an entirely different window. By dynamically inserting a hidden iframe into the DOM and setting its location to the desired file path we can initiate a file download just like it was occurring in the main application window. This directly gets us around one of the nasties of file downloads – if an error occurs the user has now been forced off of the page they were on (which may contain an Ajax application like Gmail) to see an ugly error message.

Like a normal file download in the main window an iframe will never fill with content when a successful file download occurs. It simply contains an empty DOM. Well how do we detect what is going on if nothing happens when the file download is successful. Well this is where the cookie comes in:

cookie + iframe

Since the creation of cookies exists in HTTP headers, which is standard fare for all web requests and responses, we can actually write a cookie to indicate that a file download has been initiated properly (instead of an error page). The response from the web server will now look something like this:

Content-Disposition: attachment; filename=Report0.pdf

Set-Cookie: fileDownload=true; path=/

While we can’t directly tell if a file download has occurred we can check for the existence of a cookie which is exactly how jQuery File Download works. Once a download is initiated on the iframe a configurable duration poll of cookies and the iframe contents occurs. If the iframe fills with contents then we know a file download has occurred (in most cases, make sure to set a MIME type!). If the cookie gets written then we know to stop polling and kill the iframe because the file download dialog/ribbon has been displayed.

Using jQuery File Download – JavaScript

jQuery File Download is easy to use in the simple case but also allows for various callback options as well. Don’t forget to add the required cookie code in the next section!

Very simple code demo

$.fileDownload(‘/url/to/download.pdf’);

Use of the very simple approach only protects you from the page changing in the event of a file download error. This alone is pretty useful. If an error occurs the user gets an alert() dialog that says  “A file download error has occurred, please try again.” You can see this demoed here under the “Barebones – jquery.fileDownload.js” heading. I wouldn’t recommend using this option given a much better experience is only a few more lines away…

Impractical code demo of commonly used features

This just demos what you could do but I’d highly recommend against it unless you want confused and annoyed users. This will result in an alert() dialog telling you a file download initiation has just occurred for the specified URL. If a failure occurred it will display the attempted URL and error message in a dialog.

$.fileDownload(‘/url/to/download.pdf’, {

    successCallback: function (url) {

        alert(‘You just got a file download dialog or ribbon for this URL :’ + url);

    },

    failCallback: function (html, url) {

        alert(‘Your file download just failed for this URL:’ + url + ‘rn’ +

                ‘Here was the resulting error HTML: rn’ + html

                );

    }

});

Simple rich user experience code demo

You can see this one running at the top of the demo page. In order for the below code to work for you, you will also need jQuery UI installed and an image (if you want) as a downloading spinner.

This code will cause any <a> with class=”fileDownload” like below

<a href=«http://jqueryfiledownload.apphb.com/FileDownload/DownloadReport/0» class=«fileDownloadSimpleRichExperience»>Report0.pdf</a>

that is ever loaded into your site (assuming a globally loaded JavaScript reference) to initiate a “rich user experience”:

  • User is informed of a pending report download via a jQuery UI modal that says “We are preparing your report, please wait…”
  • Success:
    • Modal goes away just as the browser’s file download dialog/ribbon occurs
  • Failure:
    • User is informed of an error in a jQuery UI modal: “There was a problem generating your report, please try again.”

Another plus to this approach is that it degrades gracefully in case the user doesn’t have JavaScript running because an a href certainly better work in any web browser out there! 

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

//the below uses jQuery «on» http://api.jquery.com/on/ (jQuery 1.7 + required, otherwise use «delegate» or «live») so that any

//<a class=»fileDownload…»/> that is ever loaded into an Ajax site will automatically use jquery.fileDownload.js

//if you are using «on»:

//you should generally be able to reduce the scope of the selector below «document» but it is used in this example so it

//works for possible dynamic manipulation in the entire DOM

//

// Simple rich user experience — jquery.fileDownload.js & jQuery UI Dialog

// uses the optional «options» argument

//

$(function() {

    $(document).on(«click», «a.fileDownloadSimpleRichExperience», function() {

        $.fileDownload($(this).attr(‘href’), {

            preparingMessageHtml: «We are preparing your report, please wait…»,

            failMessageHtml: «There was a problem generating your report, please try again.»

        });

        return false; //this is critical to stop the click event which will trigger a normal file download!

    });

});

Custom rich user experience code demo

This demo does almost the same thing as above but handles the modals manually by using the callbacks and it uses modal HTML that already exists on the page.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

//the below uses jQuery «on» http://api.jquery.com/on/ (jQuery 1.7 + required, otherwise use «delegate» or «live») so that any

//<a class=»fileDownload…»/> that is ever loaded into an Ajax site will automatically use jquery.fileDownload.js

//if you are using «on»:

//you should generally be able to reduce the scope of the selector below «document» but it is used in this example so it

//works for possible dynamic manipulation in the entire DOM

//

//Custom rich user experience — jquery.fileDownload.js & jQuery UI Dialog

//uses the optional «options» argument

//

$(function() {

    $(document).on(«click», «a.fileDownloadCustomRichExperience», function() {

        var $preparingFileModal = $(«#preparing-file-modal»);

        $preparingFileModal.dialog({ modal: true });

        $.fileDownload($(this).attr(‘href’), {

            successCallback: function(url) {

                $preparingFileModal.dialog(‘close’);

            },

            failCallback: function(responseHtml, url) {

                $preparingFileModal.dialog(‘close’);

                $(«#error-modal»).dialog({ modal: true });

            }

        });

        return false; //this is critical to stop the click event which will trigger a normal file download!

    });

});

HTML for jQuery UI Modals (place anywhere on page) 

<div id=«preparing-file-modal» title=«Preparing report…» style=«display: none;»>

We are preparing your report, please wait…

<!—Throw what you’d like for a progress indicator below—>

<div class=«ui-progressbar-value ui-corner-left ui-corner-right» style=«width: 100%; height:22px; margin-top: 20px;»></div>

</div>

<div id=«error-modal» title=«Error» style=«display: none;»>

There was a problem generating your report, please try again.

</div>

Using jQuery File Download – Server Code for Cookie

Only the MVC 3 server code has been tested. Actually if you want to see it running just head over to the demo page. Just make sure to write a cookie in the same HTTP response as the file download occurs with, that results in this HTTP Response Header (using default configuration):

Set-Cookie: fileDownload=true; path=/

ASP.NET MVC 3

If you are using a Controller Action to serve up your files (I hope you are!) you can very easily enable automatic cookie writing by inheriting your Controllers from a base class that writes the cookie automatically for you. This assumes that you are using MVC helpers for returning “FileResult”s (or derived classes like FileStreamResult). MVC FTW.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

public class FileDownloadController : Controller

{

    protected override void OnResultExecuting(ResultExecutingContext context)

    {

        CheckAndHandleFileResult(context);

        base.OnResultExecuting(context);

    }

    private const string FILE_DOWNLOAD_COOKIE_NAME = «fileDownload»;

    /// <summary>

    /// If the current response is a FileResult (an MVC base class for files) then write a

    /// cookie to inform jquery.fileDownload that a successful file download has occured

    /// </summary>

    /// <param name=»context»></param>

    private void CheckAndHandleFileResult(ResultExecutingContext context)

    {

        if (context.Result is FileResult)

            //jquery.fileDownload uses this cookie to determine that a file download has completed successfully

            Response.SetCookie(new HttpCookie(FILE_DOWNLOAD_COOKIE_NAME, «true») { Path = «/» });

        else

            //ensure that the cookie is removed in case someone did a file download without using jquery.fileDownload

            if (Request.Cookies[FILE_DOWNLOAD_COOKIE_NAME] != null)

                Response.Cookies[FILE_DOWNLOAD_COOKIE_NAME].Expires = DateTime.Now.AddYears(1);

    }

}

ASP.NET

Static Code

HttpContext.Current.Response.SetCookie(new HttpCookie(«fileDownload», «true») { Path = «/» });

Response-aware code

Response.SetCookie(new HttpCookie(«fileDownload», «true») { Path = «/» });

PHP (with example file)

header(‘Set-Cookie: fileDownload=true; path=/’);

header(‘Cache-Control: max-age=60, must-revalidate’);

header(«Content-type: text/csv»);

header(‘Content-Disposition: attachment; filename=»‘.$title.‘-‘ . $timestamp . ‘.csv»‘);

That’s it!

Let me know if you have any issues or can think of some nice features to add.

Понравилась статья? Поделить с друзьями:
  • Error hresult e fail has been returned from a call to a com component
  • Error host lookup на телевизоре
  • Error hooking port
  • Error homebrew core is a shallow clone
  • Error history report