Retrieve an image from the server, store it in localStorage, and display it

后端 未结 4 679
终归单人心
终归单人心 2021-02-01 10:12

This should be simple enough, but after wrestling with it for hours, I still can\'t get it to work. So far, all my attempts have resulted in the image becoming \'corrupted or tr

4条回答
  •  自闭症患者
    2021-02-01 10:41

    Turns out, AJAX can't be used to reliably transfer binary data. The solution is to run the Base64 encoding server-side, and transfer the resulting string through AJAX.

    The above php-code works. For whoever is looking for a ASP.Net / C# solution:

        public string Image(string relpath)
        {
            Response.ContentType = "image/jpeg";
    
            string base64;
            string filename = Request.PhysicalApplicationPath + relpath;
            try
            {
                using (var fs = new FileStream(filename, FileMode.Open, FileAccess.Read))
                {
                    var buffer = new byte[fs.Length];
                    fs.Read(buffer, 0, (int)fs.Length);
                    base64 = Convert.ToBase64String(buffer);
                }
            }
            catch (IOException e)
            {
                return filename + " / " + e.Message;
            }
            return base64;
        }
    

    Please note that this code is NOT SECURE to expose directly to the outer world. I personally use a wrapper-function that parses the path from a db.

提交回复
热议问题