Javascript upload files without any HTML code, Forms, inputs etc

313 Views Asked by At

I'm new in webdevelopment and especially in javascript. My taks is to make use of DHTMLX library in the project I'm working on.

I have a problem with uploading files to django server. Right now I'm using DHTMLX javascript library, There is DHTMLXToolBar on mine site with a button. I want to upload files by clicking on this button. but Mine code do not show me any window to choose a file / files (many praferably).There are not any html code whatsoever regarding this.

I have tried with hidden forms, even hidden iframes with forms, bare javasctip, but still nothing.

Mine js code

var iframe = document.createElement("iframe");   
filesToolbarObject.attachEvent("onClick", function(id) {
    if (id == "new"){

        var form = document.createElement("form");
        form.setAttribute("method", "post");
        form.setAttribute("action", "");
        form.setAttribute("id", "playlist_form");
        form.setAttribute("enctype", "multipart/form-data");

        var hiddenField = document.createElement("input");
        hiddenField.setAttribute("type", "hidden");
        hiddenField.setAttribute("name", "filesToUpload[]");
        hiddenField.setAttribute("id", "filesToUpload");
        hiddenField.setAttribute("type", "file[]");
        hiddenField.setAttribute("multiple", "");
        hiddenField.setAttribute("onChange", "makeFileList();");

        var crfcTokenField = document.createElement("input");
        crfcTokenField.setAttribute("type", "hidden");
        crfcTokenField.setAttribute("name", "csrfmiddlewaretoken");
        crfcTokenField.setAttribute("value", '{{ csrf_token }}');

        form.appendChild(hiddenField);
        form.appendChild(crfcTokenField);

        iframe.name = "myTarget";

        // Next, attach the iFrame to the main document
        window.addEventListener("load", function () {
          iframe.style.display = "none";
          document.body.appendChild(iframe);
        });


        iframe.addEventListener("load", function () {
            $('.upload').show();
        });                             
        form.target = iframe.name;
        form.style.display = "none";
        document.body.appendChild(form);
        form.submit();
        document.body.removeChild(form);
    }
});

Server side:

for fileToUpload in request.FILES.getlist('filesToUpload[]'):
    fileType=get_file_type(fileToUpload.name.split('.')[-1])
    if fileType:
        newFile = Media()
        newFile.type = fileType
        newFile.ext = newFile.name.split('.')[-1]
        newFile.size=fileToUpload.size
        newFile.file=fileToUpload
        newFile.name=fileToUpload.name
        newFile.save()
0

There are 0 best solutions below