Skip to content

Downloads API #2491

Closed
Closed

Description

@kjlaw89

I know it was discussed in #2030 (comment) about having a downloads API... what was the end result of that? I can't find any reference to that in the documentation, so I'm guessing it hasn't been done? It'd be really nice if there was a way for me to automatically start downloading certain files and have an event for when they finished (especially useful for my PDF issue #2490)

Activity

  1. afocus commented on Aug 15, 2015

    @afocus

    i want it too

  2. kjlaw89 commented on Aug 19, 2015

    @kjlaw89
    Author

    We just put up a bounty for this, as it's going to be the next hold-up in our project. We need an API that both allows us to start downloads and to control downloads that were started by navigating to a link or loading a PDF.

    1. Event on Browser-Window to detect when a new download has started (window.on("download", function (details, downloadID) {})
      a. Need the ability to approve/deny download
      b. Need the ability to change the download location
      c. This should produce a download ID that we can use to pause/resume downloads
    2. Implement this interface for managing downloads:
    downloads.download({url: "", download_dir:"", file_name""}, function(error, downloadId) {})
    downloads.pause(downloadId, callback)
    downloads.resume(downloadId, callback)
    downloads.cancel(downloadId, callback)
    downloads.show(downloadId)
    
    // details = {
    //   download_id: "",
    //   url: "",
    //   file_name: "",
    //   total_bytes: "",
    //   downloaded_bytes: "",
    //   download_location: ""
    // }
    
    downloads.on('changed', function(details) {})
    downloads.on('progress', function(details) {})
    

    It might be better to have the downloads manager be a per-Browser Window instance.

    If you have any questions, feel free to ask!

    Bountysource

  3. bengotow commented on Aug 25, 2015

    @bengotow
    Contributor

    Hey folks—This may eventually be built into Electron, but you can implement it yourself in a BrowserWindow. We do something very similar in the Electron mail client I work on (download attachments, cache them, specify download folder, etc.) We use the https://github.com/request/request library to stream directly to files in the user's temp folder and then move them / open them when downloads have completed.

  4. zcbenz commented on Aug 25, 2015

    @zcbenz
    Contributor

    We can just add a new will-download event for WebContents instead of inventing a whole set of download API:

    window.webContents.on('will-download', function(event, url, filename, mimeType, userGesture) {
      event.preventDefault();
      require('request')(url, function(data) {
        require('fs').writeFileSync('/somewhere', data);
      });
    });
  5. kjlaw89 commented on Aug 25, 2015

    @kjlaw89
    Author

    @zcbenz Hopefully that would work well for us, though it would almost be more preferable if the download was handled by Electron so we wouldn't need to deal with the client-certificate aspect of things. I'm assuming the method you provided would require me to setup the request object with our client certificate?

  6. zcbenz commented on Aug 28, 2015

    @zcbenz
    Contributor

    @zcbenz Hopefully that would work well for us, though it would almost be more preferable if the download was handled by Electron so we wouldn't need to deal with the client-certificate aspect of things. I'm assuming the method you provided would require me to setup the request object with our client certificate?

    Yeah it would require you to use Node.js's API to handle requests, and since it is independent from Chrome's networking stack you have to handle the certificate things yourself.

  7. kjlaw89 commented on Aug 28, 2015

    @kjlaw89
    Author

    Okay, I think that'd work since we were planning on packaging our certificate with the application anyways. It's not the best solution for everyone, but it would be enough to get us by! Thanks for looking at it!

  8. mmommo commented on Aug 29, 2015

    @mmommo

    Hi kjlaw89,
    Would you please give some hints on "packaging our certificate"? Will read cookies & add them back to header be enough?

    Thanks!

  9. hokein commented on Aug 30, 2015

    @hokein
    Contributor

    After some investigationa, the download process seems to be hard-coded in Chromium. The WebContents in Chromium doesn't expose any download related interfaces(except CanDownload) that allow us to customize the download process.

  10. steelbrain commented on Aug 31, 2015

    @steelbrain
    Contributor

    @zcbenz just a side note, your example loads everything into ram and then flushes it, here's a better example

    const request = require('request')
    const fs = require('fs')
    window.webContents.on('will-download', function(event, url, filename, mimeType, userGesture) {
      event.preventDefault();
      request(url).on('response', function(res){
        res.pipe(fs.createWriteStream('/somewhere'))
      })
    });
  11. kjlaw89 commented on Aug 31, 2015

    @kjlaw89
    Author

    @mmommo What part of it do you want to know? Basically I'll be putting a PEM file in our application directory and using it to access certain resources on an external server. Right now I also have to install a .p12 file on the computer because we can't pass in a PEM file directly yet (see #1956), but eventually we'll be able to do that too.

  12. kjlaw89 commented on Sep 3, 2015

    @kjlaw89
    Author

    @zcbenz @deepak1556 Unfortunately I don't think this event is enough for me to do the download I need to do. These are PDF (http://fpdf.org/en/doc/output.htm) files that are being sent through PHP by essentially doing:

    header('Content-Description: File Transfer');
    header('Content-Type: application/pdf');
    header('Content-Disposition: inline; filename="attachmentname.pdf"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    readfile($file);
    

    I did notice that I could change where the downloads would be stored in this event, so maybe we could do some sort of hybrid method? If we updated the "item" on will-download to contain a unique ID for the download (randomly generated would be fine...), maybe we could introduce a method to download without prompt (maybe on the event object, in addition to event.preventDefault () have an event.preventDialog ()?) and add another event on session called "download-finished", which references the same information in will-download?

  13. zcbenz commented on Sep 7, 2015

    @zcbenz
    Contributor

    I'm reopening this issue since current API is not able to handle downloads with custom headers.

  14. 1 remaining item

  15. zcbenz commented on Sep 7, 2015

    @zcbenz
    Contributor

    I think we probably still need to wrap the Chromium's download API to cover all cases, one possible API is:

    webContents.session.on 'will-download', (event, item, webContents) ->
      item.on 'update', ->
        console.log(item.percentComplete);
      item.on 'complete', ->
        console.log('completed');
  16. kjlaw89 commented on Sep 15, 2015

    @kjlaw89
    Author

    I'd love to see this introduced soon! Especially if I can choose a place for it to download to through the code and prevent the dialog from appearing (so I could download the file to a temporary place for viewing first). We still have a bounty open on this!

    Bountysource

  17. kjlaw89 commented on Sep 17, 2015

    @kjlaw89
    Author

    We just bumped the bounty on this one by another $200! Someone please jump on this, because if I have to do it I it won't be pretty! Haha

    Bountysource

  18. adilanchian commented on Sep 17, 2015

    @adilanchian

    Quick question for you guys, I just updated to v 0.33.0 and I originally was able to inject a pdf url into a pdf.js viewer I implemented in an iFrame. Now when a pdf is detected I get the save pdf dialog. Is this because of this? I was originally running v 0.30.4 and my implementation worked fine! Thanks for all your help in advance

  19. kjlaw89 commented on Sep 18, 2015

    @kjlaw89
    Author

    @denim2x Preferably I'd like Electron to manage the download process, I just need the capability to detect when the file has started, choose where it gets saved to behind the scenes (no dialog), and have some sort of notice when it has finished.

    The reason I'm trying to do this is because our web application serves up PDF files through the browser (obviously with Adobe reader support). Moving to Electron, I don't want to lose this feature, as it's pretty important, so I need the capability to detect when a PDF download with an inline Content Disposition starts, save the file automatically (no dialog) to a temporary directory, then display it in Electron using PDF.js.

    The problem with the current method is that the path to the download file is just a reference to the PHP file in our system which started the download, not the actual PDF itself because the content was returned using PHP and even with all of the headers and session details I cannot get the PDF download from just PHP, though, there may be some way around this that I cannot figure out...

    I think @zcbenz's API would be just fine - I'd envision it working something like this for us:

    webContents.session.on ('will-download', function (event, item, webContents) {
      event.preventDialog ();
      event.session.setDownloadPath ("path/to/tmp/folder");
    
      item.on ('update', function () {
        console.log(item.percentComplete);
      }
      item.on ('complete', function () {
        console.log('completed');
        mainWindow.createPdfView ("path/to/tmp/folder/item.name");
      }
    }
    
  20. kjlaw89 commented on Sep 18, 2015

    @kjlaw89
    Author

    @denim2x This is a simple example of FPDF an Content-Disposition: Inline: http://www.fpdf.org/en/tutorial/tuto2.php

    This doesn't quite mirror our problem and I'm sure PDF.js will load this just fine because it only returns a PDF file. In our use case though, if you went to tuto2.php it would present you with a normal HTML form and a button you would click to generate the PDF, which would POST the form to the current page (lets say tuto2.php, for example) and may or may not return a PDF as the result using headers.

    Most of our problem comes from the fact that, depending on how you access tuto2.php you may or may not get a HTML form or PHP form as the result. When you try access everything now and click "Generate Report" it pops up with a Download box for the PDF that was sent back and doesn't leave the page (which is what I would expect since there's no way for me to handle anything otherwise).

  21. steelbrain commented on Sep 19, 2015

    @steelbrain
    Contributor

    I wonder why wouldn't the fetch API work? It lets you stream data.

  22. kjlaw89 commented on Sep 19, 2015

    @kjlaw89
    Author

    @denim2x Pausing/resuming isn't really necessary in our case, we simply need the ability to download. The original API I specified (the Downloads API in #2491 (comment)) was just the continuation of another idea in a separate thread (also linked to in that same comment). I think the API that zcbenz specified would be best though because the code already exists at this point (and matches up better with the style of everything else).

    I'm not sure if you're going to follow through with the idea you had on Bountysource or not - I'm not quite sure that'll work in the end, but I won't know until I see it. Something to keep in mind is that we require the use of client certificates in order to access our server and that the session established with Electron for the current webview would need to be carried over to the XML Request object in order to do anything. This is another big reason why I'd like all of this to be handled in the Electron side of things because it eliminates the need for us to start a new request and manually add the client certificates and session data from the current webview session.

  23. mmommo commented on Sep 20, 2015

    @mmommo

    @denim2x @kjlaw89 Pausing/resuming isn't really necessary in just your paticular case. It's not even necessary for most of the use cases. The download api would open up a broad opportunities for lots of apps. The majority use of the api would be download a big amount of small files so user only need to see folder selection dialogue for once(or silently). For the small amount of large files I really don't see the necessary to do automatic download in the background.

    I'm planning to develop a app for my business to login to Net Banks downloading bank statements automatically. Vote for download API. Vote for zcbenz API.

    Cheers!

  24. hetal-patadia commented on Apr 1, 2016

    @hetal-patadia

    @adilanchian Were you able to disable the show pdf dialog? I am facing the exact same problem and showing the pdfs in pdf.js viewer also shows me the save dialog which I want to hide.
    TIA.

  25. coreybruce commented on Jul 7, 2016

    @coreybruce

    Hey @steelbrain where exactly do I put your download api code in, I am using it for my Google Drive application and would really need this until it's implemented or hard coded into electron.

  26. P0oOOOo0YA commented on Oct 29, 2018

    @P0oOOOo0YA

    Is there any way to access a session download history. Suppose a webview is inside a BrowserWindow. with the current api you can do whatever you want until the session is alive. But what happens if the session is destroyed. Then how to resume downloads. It should be a mechanism to restore downloads and resume them.

  27. P0oOOOo0YA commented on Oct 29, 2018

    @P0oOOOo0YA

    Wow. Electron is aweeeeesome.20 minutes after i post the above comment i found this. couldn't find any example on it though. This is a method of the Session object.

    session.createInterruptedDownload
       * Allows resuming cancelled or interrupted downloads from previous Session. The
         * API will generate a DownloadItem that can be accessed with the will-download
         * event. The DownloadItem will not have any WebContents associated with it and the
         * initial state will be interrupted. The download will start only when the resume
         * API is called on the DownloadItem.
         */
        createInterruptedDownload(options: CreateInterruptedDownloadOptions): void;

    a silly example just for illustration:

      webview.getWebContents().session.createInterruptedDownload({
        path: '/path/to/the/file.ext',
        urlChain:['http://www.example.com/file.ext'],
        offset: 25412,
        length: 12548554,
        lastModified: '2018-05-14',
        eTag: 'ahau84a1'
      })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions