1

Is there a way to "peek" at the file size without uploading files to R Shiny?

ismirsehregal
  • 30,045
  • 5
  • 31
  • 78
Jeff Bezos
  • 1,929
  • 13
  • 23
  • uploading or downloading? `fileInput` is used for uploading – lz100 Nov 09 '22 at 00:28
  • Upload, edited for clarity – Jeff Bezos Nov 09 '22 at 02:55
  • 2
    [Here](https://stackoverflow.com/questions/7497404/get-file-size-before-uploading) you can find a related question. – ismirsehregal Nov 09 '22 at 08:00
  • Thanks @ismirsehregal, I was wondering if anyone had a solution in R. If not I will adapt the javascript solution and post it here. – Jeff Bezos Nov 09 '22 at 16:01
  • 4
    `file.size` will only work on the host. If you want to check the file size on the client side you need JS. – ismirsehregal Nov 11 '22 at 18:34
  • 1
    It is certainly not possible with the standard `fileInput` widget. The documentation states clearly, that the reactive value of the widget is only invalidated after an upload succeeded. There may however be upload widgets in other packages that have different functionality. Note: If your goal is to restrict the file size for uploads, you can do so by setting the `options(shiny.maxRequestSize=...)` option. – AEF Nov 15 '22 at 07:40

1 Answers1

7

With suggestions provided by @ismirsehregal, we can modify the fileInput and add some JS to achieve your goal.

library(shiny)
ui <- fluidPage(
    fileInput("check", NULL, buttonLabel = "Upload to check", placeholder = "Check File Size"),
    # remove progress bar since we are not truely uploading
    tags$style("#check .shiny-file-input-progress {display: none}"), 
    tags$script(
        "
        $('#check').on('change', function() {
          $(this)
            .parents('div.input-group')
            .find('.form-control')
            .attr('placeholder', `File size is ${this.files[0].size}`); // update text
            
          // If you want R server to also know the size, we can set up an input 
          Shiny.setInputValue('check_size', this.files[0].size)
          $(this).val(''); // this prevents shiny to takeover the file and upload the file
        });
        "
    )
)
server <- function(input, output, session) {
    observe(print(input$check_size))
}


shinyApp(ui, server)

This will get you the file size both on UI and server. Hope this is what you want. enter image description here

lz100
  • 6,990
  • 6
  • 29