简体   繁体   中英

Alter the content of a file before upload with FileReader using javascript

Is it possible to change the content of a file before beeing uploaded in javascript ? I can read the content but changing it seems impossible.

    f = document.getElementById('input').files[0];
    var reader = new FileReader();
    reader.onload = function(e){
        console.log(e.target)
        e.target.result = "new content"
        console.log(e.target);
    };
    reader.readAsDataURL(f);

You can't rewrite the value of a file input.

You can take the content of the file and send it with Ajax though.

reader.onload = function(e){
    const data = new FormData();
    const url = this.result;
    const blob = convertUrlToBlob(url);
    data.append("file_input", blob, "filename.ext");
    const xhr = new XMLHttpRequest();
    xhr.open('POST', '/example/url');
    xhr.send(data);
};

I won't go into the detail of how to write a convertUrlToBlob function, it is covered by this question .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM