Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
251 views
in Technique[技术] by (71.8m points)

javascript - Get base64 string of an image and store to hidden element

I need to send a base64 encoded string of images uploaded by a user to some URL for processing.

Due to some reason (my old API), I need that string in a paragraph element and use its content in a Java class to attach string in response(which you can ignore, I have to do it).

HTML:

<input type="file" name="attachment" id="attachment" accept="image/*"
    onchange='onChooseFile(event, onFileLoad.bind(this, "imageData"))'>

<p id="imageData"></p>

Javascript:

function onFileLoad(elementId, event) {
    document.getElementById(elementId).value = event.target.result;
}

function onChooseFile(event, onLoadFileHandler) {
    if (typeof window.FileReader !== 'function')
        throw ("The file API isn't supported on this browser.");
    let input = event.target;
    if (!input)
        throw ("The browser does not properly implement the event object");
    if (!input.files)
        throw ("This browser does not support the `files` property of the file input.");
    if (!input.files[0])
        return undefined;
    let file = input.files[0];
    let fr = new FileReader();
    fr.onload = onLoadFileHandler;
    fr.readAsText(file);
}

The data going on the server is causing the image to be somehow corrupted(getting an error on opening and server code is fine because it's working with other sources of base64 encoded images). Can you please point out how to do it, I'm not a front-end developer, please forgive me for my naive mistakes.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I used below code instead on those two javascript methods

function onChooseFile(element) {
        let file = element.files[0];
        let reader = new FileReader();
        reader.onloadend = function() {
            document.getElementById("imageData").value = reader.result;
        }
        reader.readAsDataURL(file);
    }

worked like a charm


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...