Html file input, set selection from File object

2019-04-26 20:02发布

问题:

I understand that the <input type="file"> for the most part cannot be manipulated by javascript for security reasons, but is it possible if I have a File object?

I have a drag area on a page, that I can get a File object out of. I don't want to use the xhr.sendAsBinary, I'd rather just upload from a regular form with the target set as a frame.

I've tried doing something like

var select = document.getElementById('upload_1'); 
select.files[0] = myFile;
myForm.submit();

Is there a way to do this?

回答1:

UPDATE

It seems like you want to take the File object from the drop event and assign it to the <input> element. Unfortunately, you can't do that. Only the user can select files; you can't dynamically change the files which will be uploaded because browsers deny JavaScript this ability for security reasons.


Since you said you have a drag area, I'm assuming you are using and targeting a browser that supports drag and drop. Note that not all browsers support drag and drop so my example here is limited to such browsers.

With drag and drop, you can get the File object out of the drop event and you don't need an input element.

// when you attach the 'drop' event listener
var dropzone = document.getElementById('drag_area'); // <-- ID of your drag area
attachEvent(dropzone, 'drop', function(event) {

    var dt = event.dataTransfer;
    var fileList = dt.files;
    var file = fileList[0]; // you would have to change this if you allow multi-file upload

    uploadFile(file);

});

function uploadFile(fileToUpload) {

    var xhr = new XMLHttpRequest();
    xhr.open("POST", "url", true);   // <-- provide the proper URL

    var form_data = new FormData();
    form_data.append('file', fileToUpload);
    xhr.send(form_data);

}

function attachEvent(element, type, fn) {
    if (element.addEventListener) {
        element.addEventListener(type, fn, false);
    } else if (element.attachEvent) {
        element.attachEvent('on' + type, fn);
    }
}

Note that this isn't 100% browser compatible. Some browsers don't support file uploading through XMLHttpRequest(). If you want to support those browsers, then you have to do something different.

Finally, my example doesn't consider using forms. If you want a form-based approach, please let me know. I can help you with that as well :)

Let me know if you have any questions.