tauri: [bug] Can not download in front end

About this issue

  • Original URL
  • State: open
  • Created 4 years ago
  • Reactions: 4
  • Comments: 28 (11 by maintainers)

Most upvoted comments

Temporary solution:

import { saveAs } from 'file-saver';
import { save } from '@tauri-apps/api/dialog';
import { writeTextFile } from '@tauri-apps/api/fs';

export const downloadFile = async (filename, text, type = 'application/json') => {
    if (window.__TAURI__) {
        const filePath = await save({ defaultPath: filename });
        await writeTextFile(filePath, text);
    } else {
        saveAs(new Blob([text], { type }), filename);
    }
};

Don’t forget to enable dialogs.

Is there any plan for this being added to tauri still? It’s still not working in tauri 1.4 almost one year after it being fixed upstream (it was planned apparently to be added to tauri 1.3). It’s quite a critical issue for us.

My experience of the out of the box behaviour of downloads (Tauri 1.3.0):

  • On Windows, files are downloaded to the downloads folder. The web view shows a notification. If the file already exists, the new file is saved with a unique name.
  • On Linux (Ubuntu 22.04), files are downloaded to the downloads folder. There is no notification from the web view. If the file already exists, it’s deleted and no new file is saved.

(I don’t have access to macOS to test there.)

On macOS nothing seems to happen at all. No errors in the console, no file is downloaded.

At least not to this locations:

  • Desktop
  • Documents
  • User Folder ~/

It looks like this has been solved upstream. Has that made it into any releases for tauri? Are there any workarounds?

Is there any way to solve this part in the latest version of tauri? In my case, the download code is in the external domain, so I need a way to resolve it in the Tauri app if possible.

it still needs to be implemented in Tauri. wry#530 just made it possible to do so (by adding new apis). 530 by itself shouldn’t have added any behavior changes outside these new apis.

Thanks, it’s not throwing any errors anymore, just a few warnings:

warning: unused imports: `CspDirectiveSources`, `Csp`, `WebviewUrl`
 --> src/main.rs:5:19
  |
5 |   utils::config::{Csp, CspDirectiveSources, WebviewUrl},
  |                   ^^^  ^^^^^^^^^^^^^^^^^^^  ^^^^^^^^^^
  |
  = note: `#[warn(unused_imports)]` on by default

warning: unused variable: `webview_window`
  --> src/main.rs:21:15
   |
21 |           let webview_window = WebviewWindowBuilder::from_config(handle, &app.config().app.windows.get(0).unwrap().clone())?
   |               ^^^^^^^^^^^^^^ help: if this is intentional, prefix it with an underscore: `_webview_window`
   |
   = note: `#[warn(unused_variables)]` on by default

warning: unused variable: `webview`
  --> src/main.rs:22:27
   |
22 |             .on_download(|webview, event| {
   |                           ^^^^^^^ help: if this is intentional, prefix it with an underscore: `_webview`

On top of that, I also don’t know what to replace the destination with, since I don’t have a default download path or anything like that. 🤔 Maybe I’ll stick with the workaround for now, as that also includes a save file dialogue.

In main.rs or lib.rs depending on where you already have a tauri::Builder line.

Presumably one from the .run(tauri::generate_context!()) command and one from the on_download example that creates a new webview, right?

yep. If you want to keep configuring the window in tauri.conf.json you can add create: false to the window config (requires latest tauri version) and then do something like this

use tauri::{
  utils::config::{Csp, CspDirectiveSources, WebviewUrl},
  webview::{DownloadEvent, WebviewWindowBuilder},
};

tauri::Builder::default()
  .setup(|app| {
    let handle = app.handle();
    // `get(0)` assumes that we're talking about the first window in the tauri.conf.json window config array.
    let webview_window = WebviewWindowBuilder::from_config(handle, &app.config().app.windows.get(0).unwrap().clone())
      .on_download(|webview, event| {
        match event {
          DownloadEvent::Requested { url, destination } => {
            println!("downloading {}", url);
            *destination = "/home/tauri/target/path".into();
          }
          DownloadEvent::Finished { url, path, success } => {
            println!("downloaded {} to {:?}, success: {}", url, path, success);
          }
          _ => (),
        }
        // let the download start
        true
      })
      .build()?;

    Ok(())
  });

I was in a situation where I couldn’t install the tauri module on the front-end, and I eventually handled it like this. Hope it helps someone.

  • Frontend
export const useSaveFile = () => {
  const blobToBase64 = async (blob: Blob) => {
    return new Promise((resolve, reject) => {
      const reader = new FileReader()
      reader.onloadend = () => {
        resolve((reader.result as string).split(',')[1])
      }
      reader.onerror = reject
      reader.readAsDataURL(blob)
    })
  }

  const saveFile = async (blob: Blob, fileName: string) => {
    if (window.isTauri) {
      const base64Data = await blobToBase64(blob)
      await invoke(`save_file`, { filename: fileName, data: base64Data })
    } else {
      saveAs(blob, fileName)
    }
  }

  return { saveFile }
}
  • Backend
use base64::engine::general_purpose::STANDARD;
use base64::Engine;
use std::fs::File;
use std::io::Write;

#[tauri::command]
fn save_file(app_handle: AppHandle, filename: &str, data: &str) {
  let data = data.to_owned().clone();
  app_handle
    .dialog()
    .file()
    .set_file_name(filename)
    .save_file(move |file_path| {
      match STANDARD.decode(&data) {
        Ok(decoded_data) => {
          let file_path = file_path.unwrap().into_os_string().into_string().unwrap();
          match File::create(file_path) {
            Ok(mut file) => {
              if let Err(e) = file.write_all(&decoded_data) {
                println!("Failed to write to file: {}", e);
              }
            }
            Err(e) => {
              println!("Failed to create file: {}", e);
            }
          }
        }
        Err(e) => {
          println!("Failed to decode base64: {}", e);
        }
      }
    });
}

@FabianLars Would be useful to know if this issue is likely to be fixed in the 2.0 release.