D
D
Dmitry2021-06-14 14:46:13
JavaScript
Dmitry, 2021-06-14 14:46:13

How can I add a file to a form?

Hello!
I have a dead end, I need to add a file to the form, I do this:
There is a form

<form name="test">
        <input type="file" id="files" accept=".docx" value=""/>
        <button id="loadButton">load</button>
    </form>


let fileInputElement = document.getElementById('files');
        let container = new DataTransfer();
        let data = new Blob();
        let file = new File([data], "y9ai4V96h1oMTyfUZrBsAFb8sopJ79PSxxqg7FdH.docx",{type:"application/vnd.openxmlformats-officedocument.wordprocessingml.document", lastModified:new Date().getTime()});
        container.items.add(file);
        fileInputElement.files = container.files;
        var size = file.size;
        console.log(size);


What am I doing wrong?
And so I tried
var formData = new FormData();
var file_obj = document.querySelector('input[type="file"]').files[0];
formData.append("file", file_obj, "y9ai4V96h1oMTyfUZrBsAFb8sopJ79PSxxqg7FdH.docx");


Doesn't work and that's it.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
Nadim Zakirov, 2021-06-14
@zkrvndm

Firstly, it is not clear where you take the file for insertion from. What is in the data variable and where does it get there from?
Secondly, you completely misunderstand the purpose of the FormData and DataTransfer constructors.

K
kalibr17, 2021-06-25
@kalibr17

For security reasons, the file field cannot be manually assigned a value. And all)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question