Jasny Bootstrap – File input with existing file

by Arnold Daniels on 02/15/2013

I’m happy to say that many developers have found their way to Jasny Bootstrap. Especially the file upload component, is very popular. It can replace any normal <input type="file"> element to display a nice widget that is consistent across browsers and can show a preview for images.

The documentation shows the HTML to use, but it doesn’t show how to use it with existing files. I’ll explain it here.

Standard implementation

The HTML stays largely the same. Change fileupload-new to fileupload-exists for the .fileupload container div (line 1). Put the <img> for the existing image in the .fileupload-preview div (line 4). If you’re not image preview, put the file name in the .fileupload-preview div instead.

1
2
3
4
5
6
7
8
9
10
<div class="fileupload fileupload-exists" data-provides="fileupload">
  <div class="fileupload-new thumbnail" style="width: 200px; height: 150px;"><img src="http://www.placehold.it/200x150/EFEFEF/AAAAAA&text=no+image" /></div>
  <div class="fileupload-preview fileupload-exists thumbnail" style="max-width: 200px; max-height: 150px; line-height: 20px;">
    <img src="/images/example.png">
  </div>
  <div>
    <span class="btn btn-file"><span class="fileupload-new">Select image</span><span class="fileupload-exists">Change</span><input type="file" name="myimage" /></span>
    <a href="#" class="btn fileupload-exists" data-dismiss="fileupload">Remove</a>
  </div>
</div>
<div class="fileupload fileupload-exists" data-provides="fileupload">
  <div class="fileupload-new thumbnail" style="width: 200px; height: 150px;"><img src="http://www.placehold.it/200x150/EFEFEF/AAAAAA&text=no+image" /></div>
  <div class="fileupload-preview fileupload-exists thumbnail" style="max-width: 200px; max-height: 150px; line-height: 20px;">
    <img src="/images/example.png">
  </div>
  <div>
    <span class="btn btn-file"><span class="fileupload-new">Select image</span><span class="fileupload-exists">Change</span><input type="file" name="myimage" /></span>
    <a href="#" class="btn fileupload-exists" data-dismiss="fileupload">Remove</a>
  </div>
</div>

When a user presses submit without changing or removing the image, the form post contains an entry for ‘myimage’ without a new file. When clear is pressed the value for ‘myimage’ is an empty string. In PHP you could handle it as

1
2
3
4
5
  if (isset($_POST['myimage']) && $_POST['myimage'] == '') {
    // Delete file
  } elseif ($_FILES['myimage']['error'] == 0)  {
    // Save uploaded file
  }
  if (isset($_POST['myimage']) && $_POST['myimage'] == '') {
    // Delete file
  } elseif ($_FILES['myimage']['error'] == 0)  {
    // Save uploaded file
  }

If the above example isn’t working for you, try one of the 2 alternatives.

Alternative 1 – Omit from POST

However this in some languages and frameworks you can’t easily make the distinction between no file being selected and the post containing an empty string. In that case you can use the `data-name` attribute and leave you the `name` attribute on the <input type="file">.

1
2
3
4
5
6
7
8
9
10
<div class="fileupload fileupload-exists" data-provides="fileupload" data-name="myimage">
  <div class="fileupload-new thumbnail" style="width: 200px; height: 150px;"><img src="http://www.placehold.it/200x150/EFEFEF/AAAAAA&text=no+image" /></div>
  <div class="fileupload-preview fileupload-exists thumbnail" style="max-width: 200px; max-height: 150px; line-height: 20px;">
    <img src="/images/example.png">
  </div>
  <div>
    <span class="btn btn-file"><span class="fileupload-new">Select image</span><span class="fileupload-exists">Change</span><input type="file" /></span>
    <a href="#" class="btn fileupload-exists" data-dismiss="fileupload">Remove</a>
  </div>
</div>
<div class="fileupload fileupload-exists" data-provides="fileupload" data-name="myimage">
  <div class="fileupload-new thumbnail" style="width: 200px; height: 150px;"><img src="http://www.placehold.it/200x150/EFEFEF/AAAAAA&text=no+image" /></div>
  <div class="fileupload-preview fileupload-exists thumbnail" style="max-width: 200px; max-height: 150px; line-height: 20px;">
    <img src="/images/example.png">
  </div>
  <div>
    <span class="btn btn-file"><span class="fileupload-new">Select image</span><span class="fileupload-exists">Change</span><input type="file" /></span>
    <a href="#" class="btn fileupload-exists" data-dismiss="fileupload">Remove</a>
  </div>
</div>

Now when the user presses submit without changing or clearing the file, the ‘myimage’ entry will not be part of the post data. In the next PHP example both $_FILES and $_POST are processed and present in $data.

1
2
3
4
5
6
7
  if (isset($data['myimage'])) {
     if ($data['myimage'] == '') {
       // Delete file
     } else {
       // Handle uploaded file
     }
  }
  if (isset($data['myimage'])) {
     if ($data['myimage'] == '') {
       // Delete file
     } else {
       // Handle uploaded file
     }
  }

Alternative 2 – Posting a specific value

In some cases this still won’t do, for instance when you’re using a form builder which combines the defaults with posted data. In that case you can manually add the <input type="hidden"> and set it to a specific value. (In the following example ’1′ is chosen, but you can also use the basename of the file or whatever you want.)

1
2
3
4
5
6
7
8
9
10
11
<div class="fileupload fileupload-exists" data-provides="fileupload" data-name="myimage">
  <input type="hidden" name="myimage" value="1" />
  <div class="fileupload-new thumbnail" style="width: 200px; height: 150px;"><img src="http://www.placehold.it/200x150/EFEFEF/AAAAAA&text=no+image" /></div>
  <div class="fileupload-preview fileupload-exists thumbnail" style="max-width: 200px; max-height: 150px; line-height: 20px;">
    <img src="/images/example.png" />
  </div>
  <div>
    <span class="btn btn-file"><span class="fileupload-new">Select image</span><span class="fileupload-exists">Change</span><input type="file" /></span>
    <a href="#" class="btn fileupload-exists" data-dismiss="fileupload">Remove</a>
  </div>
</div>
<div class="fileupload fileupload-exists" data-provides="fileupload" data-name="myimage">
  <input type="hidden" name="myimage" value="1" />
  <div class="fileupload-new thumbnail" style="width: 200px; height: 150px;"><img src="http://www.placehold.it/200x150/EFEFEF/AAAAAA&text=no+image" /></div>
  <div class="fileupload-preview fileupload-exists thumbnail" style="max-width: 200px; max-height: 150px; line-height: 20px;">
    <img src="/images/example.png" />
  </div>
  <div>
    <span class="btn btn-file"><span class="fileupload-new">Select image</span><span class="fileupload-exists">Change</span><input type="file" /></span>
    <a href="#" class="btn fileupload-exists" data-dismiss="fileupload">Remove</a>
  </div>
</div>

In this case when the user presses submit without changing or clearing the file, the ‘myimage’ entry will be ’1′. When the user clears the image it will be an empty string. In the next PHP example both $_FILES and $_POST are processed and combined with all the default/original values as $data.

1
2
3
4
5
  if ($data['myimage'] === '') {
    // Delete file
  } elseif ($data['myimage'] !== '1') {
    // Handle uploaded file
  }
  if ($data['myimage'] === '') {
    // Delete file
  } elseif ($data['myimage'] !== '1') {
    // Handle uploaded file
  }

Please contribute

If you’re using the file upload component with Ruby, Python, C# or Java, please leave a comment with the above PHP examples in your language. Thanks.

2014-04-13 — I’ve closed commenting on this article. If you have any questions about Jasny Bootstrap, please use Stack Overflow. I’m on there often, so I’ll probably pick up your question if it hasn’t already been answered. If not, you can drop me a message via @ArnoldDaniels on Twitter.

2014-07-05 — Updated article to reflect Jasny Bootstrap 3

Arnold Daniels

I've spend a big part of my life behind a computer, learning about databases (MySQL), programming (PHP) and system administration (Linux). Currently I playing with HTML5, jquery and node.js.

More Posts

Follow Me:
TwitterLinkedIn

There are 24 comments in this article:

  1. 20 February 2013hyh says:

    Can u add some demo?

  2. 26 February 2013Vikram says:

    Hey Arnold,

    Thanks a lot for creating this library and sharing it. I have a question regarding the library. I am using the same code as you have mentioned in the sample. It works as expected on the iphone and android mobile devices. But, on the the ipad I am getting the banner with a “loading” text and icon. Is there something that I am missing to set in the function.

    I appreciate your help.

    Thanks,
    Vikram ..

  3. 1 March 2013Arnold Daniels says:

    @Vikram: I’m experiencing trouble on Android as well. The page is reloaded when using the element. I haven’t had the chance to test on iOS yet. Best just disable this element for mobile devices for now :(

  4. 2 April 2013Shiv says:

    Is there a way to make the input field required. If you add the “required” attribute to the field, but try and submit a parent form, no error message is produced. Am I missing something?

    Thanks!

  5. 16 April 2013Alex G says:

    @Shiv:
    Yeah, I am experiencing the same issue. If the file input is required and you don’t supply a file, no error is displayed. Not sure how to fix this :(

  6. 24 April 2013Michael G says:

    The work you put into this is great appreciated! I’m currently using it with Node.js/Express, with the help of req.files. If anybody wants an example, let me know and I can upload something to Github.

  7. 15 May 2013Arnold Daniels says:

    @Alex G and @Shiv: The actual input is hidden, so the message is hidden as well. You could use a solution like http://reactiveraven.github.io/jqBootstrapValidation/ to get around this.

  8. 21 May 2013Srdjan says:

    Hi,

    is it possible to upload only images?

    I have used uploadtype: ‘image’, but there is no restriction.

    Best regards

  9. 23 May 2013sadman says:

    Nice tutorial.

    I have found another website with fancy php scripts like contact form,php file upload,user registration form etc for free.

  10. 26 May 2013loiste says:

    Hello, Arnold! I’m trying to implement jasny bootstrap image preview fileupload in my html form like you show it here. Form action is php script which is processing all form data posted. I tried every method you’ve described here. But I only get a $_POST['myimage'] with ‘photo001.jpg’ (filename) info in my php script. No any $_FILES array data, no $data either. How can I obtain full uploaded image file path for saving that file in my server folder?

  11. 26 May 2013loiste says:

    Oh, Arnold, it was my fault! I’ve forgot to add multipart attribute to my form. Now everything works just fine! Thanks! :)

  12. 28 May 2013Arnold Daniels says:

    @Srdjan: Yes you can by using the ‘accept’ attribute. It’s not specific to this widget, but a general attribute of the input file element. http://www.w3schools.com/tags/att_input_accept.asp

  13. 1 June 2013Rajan says:

    Hi Arnold, It can possible for drag and drop image ??

  14. 17 June 2013Fery says:

    Hi @Arnold, just try that you described here. I put a hidden input as parameter of existing image;

    then I click change button, and my hidden input become:

    any solution??

  15. 4 July 2013Jens says:

    Is it possible to auto crop the image to a square?

  16. 9 July 2013Arnold Daniels says:

    Note that this is just a preview, not the final image. You could set a fixed height and width on the `.thumbnail` div with `overflow: hidden` and set the width of `.fileupload .thumbnail img` to 100% and the height to auto.

  17. 20 September 2013Dennis says:

    Hi Arnold,

    I’ve been having this issue, after clicking the “Select File” button the file browser dialog, doesn’t show. I looked at it in the chrome console and it’s not showing errors.

    Best,

    Dennis

  18. 24 November 2013Joe says:

    The file upload has issues in IE9.

  19. 7 January 2014Ger says:

    Hi Arnold,

    I need to add some functionality to the select button but this:
    [code]
    $('#image_rows').on('click', 'span.fileupload-new', function(e){
    console.log('test');
    })
    [/code]
    doesn’t work.
    Only when I use ‘span’ only something is logged.

  20. 31 January 2014Cameron says:

    Firstly, thanks for the awesome library!!

    Now, a C# example (hopefully the code displays ok):

    							
    <div class="controls">
      @{
        string fileinputvar = "fileinput-new";
        if(Model.ProductImage != null) {
          fileinputvar = "fileinput-exists";
        }
      }
      <div class="fileinput @fileinputvar" data-provides="fileinput">
        <div class="fileinput-new thumbnail" style="width: 200px; height: 150px;">
          <img src="~/Content/images/200x150.png" alt="No Image">
          <!--<img data-src="holder.js/100%x100%" alt="...">-->
        </div>
        <div class="fileinput-preview fileinput-exists thumbnail" style="max-width: 200px; max-height: 150px;">
          @if (Model.ProductImage != null)
          {
            <img src='@Url.Action("ShowImage", "MyController", new { tId = Model.Id })'  />
            <input type="hidden" name="existingImage" value="1" />
          }
        </div>
        <div>
          <span class="btn btn-default btn-file"><span class="fileinput-new">Select image</span><span class="fileinput-exists">Change</span><input type="file" name="pImage"></span>
          <a href="#" class="btn btn-default fileinput-exists" data-dismiss="fileinput">Remove</a>
        </div>
      </div>
    </div>
    

    My Controller then checks for the existence of the “existingImage” field, and checks it has a value of 1. Because I have placed it inside the div with class “fileinput-preview fileinput-exists thumbnail”, it is removed as part of the HTML being replaced when a new image is chosen, or the image is removed. The Controller’s handling of pre-existing image data is predicated on this value.

  21. 4 February 2014Morten says:

    Hi,

    I have just downloaded this file upload component, but I am struggling to figure out the best way to use this with Knockout. Do you have an example of this?

    Thanks.

  22. 4 February 2014Udo says:

    @Arnold Daniels:

    I didn’t want too big pictures on my server.
    But how can i resize the original Image, after upload?

  23. 20 February 2014Joby Tom says:

    I have a question regarding the File upload. Is that feature included in Bootsrap 3.1.1? For one of my project, I need to use this feature. But when I compared the bootsrap 3.0.1 and 3.11, file upload function is removed . Is there any way to do that ?

  24. 16 March 2014Henry Wright says:

    Is there a way to automatically submit the form once a file has been selected?