开发者

Javascript & Multi File Upload Fields - Manipulating POST (File Input)

I am developing a php ajax-based application, and one of it's components is an image upload. I know ajax is incapable of posting files, since it's Request based, but i did find a nifty iframe work around.

My goal is to send multiple files, but post them individually so i can process the upload and validate serversided, send the result, and then move on to the next file.

I would like to achieve this with a:

<input name="files[]" type="file" multiple=""/>

It all works all fine and dandy, but when it comes to sending them individually.. there doesn't teem to be a possible way.

My original idea was to treat the (element.files) as an array.. So i create duplicate form, and attempted to copy over the input to the other form (that was successfull)

but then when i tried to splice, or remove the unwanted elements so i can submit the form, i couldn't find a way to do it. Nothing worked...

Trying to alter the element.files.length to 1, didn't work Trying to splice it didn't work.. Trying to just clear the indexes didn't work either...

If anyone could shed a green light, or just blast the ultra red light let开发者_JS百科ting me know that this is not possible w/ an html input, it'll be greatly appreciated.

p.s: Flash isn't an option.

Here's some examples of my failed attempts:

<form name="image_upload" id="image_upload_form" action="image_uploader" method="POST" enctype="multipart/form-data">
    <input name="userfile[]" id="filesToUpload" type="file" title="Select Your Files" multiple=""/> <br /><br />
    <input type="button" id="imageUploadButton" value="Upload" onclick="valif('image_upload'); return false;" />
</form>

<!-- Hidden Form and File Input -->
<form name="single_image_upload" id="single_image_upload_form" action="image_uploader" method="POST" enctype="multipart/form-data">
    <input name="userfile[]" id="fileToUpload" type="file" style="visibility: none; position: absolute; top: 0; left: 0;/> 
</form>

<script type="text/javascript">
    //This happens on submit
    var multi_input = getElementById("image_upload");
    var single_input = getElementById("single_image_upload");

    single_input = multi_input;

    //Assuming there are 2+ files chosen for upload, attempt to only upload the first one.

    //Attempt 1
    multi_input.files.length = 1;

    //Attempt 2
    multi_input.files.splice(1);

    //Attempt 3
    for (x = 1; x < multi_input.files.length; x++) { //skip 0, we wanna keep that one
        multi_input.files[x] = null; // or ''.. same difference in this scneario.
    }
</script>

Below is the actual code right now, working w/ 1 iframe.... This code works great, however it actually unfortunately sends every single file, every time.. And i just validate the right one on the serverside, but it's not practical, as i shouldn't have to send every single file all the time.

function ajaxUpload(form,url_action,id_element){
    var detectWebKit = isWebKit();

    form = typeof(form)=="string"?$m(form):form;

    //Error Validator
    var error="";

    if (form==null || typeof(form)=="undefined"){
        error += "Invalid Form.\n";
    } else if(form.nodeName.toLowerCase()!="form"){
        error += "Element Exists but it is not a form.\n";
    }

    if (id_element==null){
        error += "The element of 3rd parameter does not exists.\n";
    }

    if (error.length>0){
        alert("Error in image upload attempt:\n" + error);
        return;
    }

    //Create Frame On The Fly
    var iframe = document.createElement("iframe");
    iframe.setAttribute("id","ajax-temp-"+rt_img);
    iframe.setAttribute("name","ajax-temp-"+rt_img);
    iframe.setAttribute("width","0");
    iframe.setAttribute("height","0");
    iframe.setAttribute("border","0");
    iframe.setAttribute("style","width: 0; height: 0; border: none;");
    form.parentNode.appendChild(iframe);
    window.frames['ajax-temp-'+rt_img].name="ajax-temp-"+rt_img;

    //Upload Image
    var doUpload = function(){
        removeEvent($m('ajax-temp-'+rt_img),"load", doUpload);
        var cross = "javascript: ";
        cross += "window.parent.upload_result(document.body.innerHTML); void(0);";

        $m('ajax-temp-'+rt_img).src = cross;

        if(detectWebKit){
            remove($m('ajax-temp-'+rt_img));
        }else{
            setTimeout(function(){ remove($m('ajax-temp-'+rt_img))}, 250);
        }
    }

    //Post Form
    addEvent($m('ajax-temp-'+rt_img),"load", doUpload);
    form.setAttribute("target","ajax-temp-"+rt_img);
    form.setAttribute("action",url_action);
    form.setAttribute("method","post");
    form.setAttribute("enctype","multipart/form-data");
    form.setAttribute("encoding","multipart/form-data");

    form.submit();
}

function upload_run() {
    var send_index = rt_img;
    rt_img += 1;

    var li = $('#fileList li:nth-child('+rt_img+')');
    var filetype = li.html().substr(-3).toLowerCase();
    var skip_mod = '';

    //validate file type
    if ((filetype != 'jpg') && (filetype != 'png') && (filetype != 'gif')) {
        li.append(' - <b>invalid image file</b>');
    } else {
        li.append(' <img src="'+base_url+'sds_ajax/upload-ani.gif">');

        //Initiate File Upload
        ajaxUpload($m('image_upload_form'),base_url+'includes/core.php?post_action=image_upload&si='+send_index,li);
    }
}



 //Get the input and UL list
        var button = document.getElementById('imageUploadButton');
        var input = document.getElementById('filesToUpload');
        var list = document.getElementById('fileList');

        //Empty list for now
        while (list.hasChildNodes()) {
          list.removeChild(ul.firstChild);
        }

        //Populate List w/ files
        rt_max = input.files.length;
        for (var x = 0; x < input.files.length; x++) {
          //add to list
          var li = document.createElement('li');              
          li.innerHTML = 'Image ' + (x + 1) + ':  ' + input.files[x].name;
          list.appendChild(li);
        }

        //Run through created list
        rt_img = 0;
        upload_run();

        //Disable Submit Button
        button.disabled=true;

bump


It sounds like you need an iframe per file upload. So what I would do is have hidden fields for every other field in your normal form (in each iframe). Then when you click the submit button, you take all the visible fields and place the values in the corresponding hidden fields for each image. Then call post on each iframe now that they all have the data they need.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜