Home > front end >  How to convert BinData and display Image at react Front end?
How to convert BinData and display Image at react Front end?

Time:08-01

I have to Display Images at react front end which is currently in BinData Format from MongoDB and what I got this in response object and response.data Now I have Passed the Binary Data in src attribute of img element with mimetype and data encoding type.

    <img src = {'data:image/jpeg;base64,${this.state.responseData}'} />

But it did not worked. I tried to use Blob, File and Filereader object as well but nothing worked. Here is the Object Values I have logged on Console

I also Tried using Buffer but that too didn't worked Click here to view Here is my front end code

    componentDidMount() {
    const headers = { "Content-Type": "application/json" };
    axios.post('http://127.0.0.1:8103/api/display_posts', { 'username' : localStorage.getItem('username')}, {headers})
        .then(res => {
            const responseData= res.data;
            console.log(res)
            console.log(responseData)

            const blobData = new Blob([responseData] , {
                type: "image/jpeg"
            })
            console.log(blobData);
            

            const myFile = new File([blobData], 'image.jpeg', {
                type: blobData.type,
            });
            console.log(myFile);

            const blob= new FileReader();
            blob.onload = function(){
                var dataURL = blob.result;
                var output = document.getElementById('here');
                output.src = dataURL;
            }
            blob.readAsDataURL(blobData);
            console.log(blob);

            const bufff =new Buffer(responseData, "binary").toString('base64');
            console.log(bufff)
            
            const bufff2 =new Buffer(responseData, "base64").toString('base64');
            console.log(bufff2)
            
            const buffer=Buffer.from(responseData, "base64");
            console.log(buffer);
            const desh = fs.writeFileSync("abc.jpg", buffer);
        

            this.setState({
                picture1: bufff,
                picture2: bufff2,
                picture3: responseData,
            });
            
        })
        .catch(
            (error) => console.log(error)
        )
}render(){
    return(
        <>
            <div>
                {this.state.respo}
                <img id="here"/>
                <img src = {'data:image/jpeg;base64,${this.state.picture1}'} /> 
                <img src = {'data:image/jpeg;base64,${this.state.picture2}'} /> 
                <img src = {'data:image/jpeg;base64,${this.state.picture3}'} />        

This is how I am sending image stored in fs.chunks in MongoDB Database using Flask App.

    postImage = self.Posts.objects(username=self.content['username']).only('background').first()

    
    
    bgImage=postImage.background
    filename = postImage.background.filename
    content_type = postImage.background.content_type
    return send_file(bgImage, download_name=filename, mimetype=content_type), 200

What am I doing Wrong? I think the Image is stored in Base64 format in fs.chunks collection as you can see But sending it on front end it is converted back into Binary Bytes Data Now it can be converted back into base64 using btao() & Buffer toString()

    const buffer= new Buffer.from(responseData);
    const vd= buffer.toString('base64');
    console.log(vd);
    const cc= window.btoa(unescape(encodeURIComponent(responseData)));
    console.log(cc);

But it's also not working as I got to know that in Opera 11 and older versions their is a limited URLs to 65535 characters long which limits data URLs to 65529 characters (65529 characters being the length of the encoded data, not the source, if you use the plain data:, without specifying a MIME type)Read Here And also the 100KB image became 247kB. Please Suggest me what to do?

CodePudding user response:

JS have btoa() function for it.

You can do that like

var img = document.createElement('img');
img.src = 'data:image/jpeg;base64,'   btoa('your-binary-data');
document.body.appendChild(img);

Read about it here BTOA

also if your binary wasn't valid , you need to convert it

function hexToBase64(str) {
    return btoa(String.fromCharCode.apply(null, str.replace(/\r|\n/g, "").replace(/([\da-fA-F]{2}) ?/g, "0x$1 ").replace(/  $/, "").split(" ")));
}

and use it instead

img.src = 'data:image/jpeg;base64,'   hexToBase64('your-binary-data');

CodePudding user response:

Can you try to change response type

const config = { responseType: 'blob' };
axios.get(blobUrl, config).then(response => {
    new File([response.data], fileName);       
});
  • Related