简体   繁体   English

在使用JavaScript使用FileReader上传之前,请更改文件的内容

[英]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 ? 在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. 您可以获取文件的内容,然后使用Ajax发送。

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 . 我不会详细介绍如何编写convertUrlToBlob函数, 该问题对此进行了介绍

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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