0

In order to have complete UI style over a form type="file" upload, I have a pseudo form field (#fileName), browse, upload button. I have a hidden form below with the actual form field (#fileAttach), browse, and upload buttons. I'm trying to trigger it such that when the user clicks browse, it triggers the actual browse button, and then grab the value of the actual input field's file path and populated the file on the pseudo input field.

    browse = function () {
        $("#fileAttach").click();
        var file = $("#fileAttach").val();
        $("#fileName").val(file);
        }

It works in Safari and IE. However, in Chrome and Firefox it seems to stop executing after the user selects the file. The file name is not passed to the pseudo form field. However, if I fire browse() a second time, it immediately populates the first file path to the pseudo form field, then spawns a new file browse window. Chrome/FF seems to only execute the first line of the function and pause. The 2nd and 3rd line gets executed if the function is called again, etc.

What's going on here and how can I solve it? Thank you in advance.

2 Answers2

1

Browsers don't really like you triggering the upload dialog via code, I've found.

I've always just displayed my own browse button and absolutely positioned the input[type=file] over the top with opacity: 0. Works in all browsers.

alex
  • 479,566
  • 201
  • 878
  • 984
  • Thanks. But unfortunately, I cant use that option. I have a huge input form that must include a file upload in the middle. Hence, in order to emulate ajax, I'm placing a second hidden form below the first. Any ideas how I can copy the path name to the pseudo form field once the user has selected the file? – user728302 Apr 28 '11 at 00:22
  • @user I doubt there is a way to extract the path from the user's computer (or at least the real one). – alex Apr 28 '11 at 00:24
  • @alex _"I doubt there is a way to extract the path from the user's computer (or at least the real one)."_ See [How FileReader.readAsText in HTML5 File API works?](http://stackoverflow.com/questions/40146768/how-filereader-readastext-in-html5-file-api-works) – guest271314 Nov 09 '16 at 03:23
0

This is how I'm doing it. Also working on an upload problem but, having trouble cause the Option Explicit statement

Add Record to Database and Upload an Image at the same time (2nd Attempt with different code)

Not sure if this is what you looking for or not.

.photodiv{
  padding:8px 16px;
  background:;
  border:0px;
  position:relative;
  color:#fff;
  border-radius:2px;
  text-align:center;
  float:left;
  cursor:pointer
}
.hide_file {
    position: absolute;
    z-index: 1000;
    opacity: 0;
    cursor: pointer;
    right: 0;
    top: 0;
    height: 100%;
    font-size: 24px;
    width: 100%;
    
}
<button class="photodiv">Photo<input type="file" name="attach1" class="hide_file"></button>
James Nelson
  • 61
  • 13