dsutuyxe088689 2015-12-01 15:44
浏览 29

获取用户选择的文件作为base64编码的字符串,用于图像的实时预览以及在最终结果中链接它

I am using a PHP file uploader to enable a user to upload images. However, due to some issues it is not working at all - the images are not uploading and the PHP script is not even creating an (empty in such cases) entries in a file. As a workaround, I am trying to use base64 encoding. The user clicks the input button which executes a little JS function. It reads the said image via readAsDataURL() and then uses onload to change the src of the img tag to this result. The function:

function readIMGURL(input) {
            if (input.files && input.files[0]) {
                var reader = new FileReader();

                reader.onload = function (e) {
                    $('#theIMG').attr('src', e.target.result);
                }

                reader.readAsDataURL(input.files[0]);
            }
        }

(Thanks to meVeekay here: https://stackoverflow.com/a/16207641/4112779)

This works well for displaying the preview of the image in the desired place. However, to complete the course of my application, the entire contents of the parent div is copied and placed in another location (or another div, another file, parent div processed by a script and placed in another div, etc)

The said div:

<div id="toCopy">
<img src="#" alt="" id="theIMG">
</div>

And the calling button:

<form style="  margin-top: 10%;" id="imageform" >        
   <input style=" margin-top: 10%;" class="input-btn" type="file" onChange="readIMGURL(this);">            
</form>

After "uploading" the image, it is posted via XMLHttpRequest to a working PHP script which does its job based on the above toCopy.

(I'm suspicious that the $content = str_replace("\\", "", $content); I added in the PHP script to remove extra escape sequences added during the POST may be messing up with the base64 text, but as far as I know, base64 doesn't have \ anywhere. Also, I have tried removing this instruction to no avail)

Eventually, in the final result, the image does not appear, instead a missing image image appears.

What could I be doing wrong, and what may be the possibilities to solve it? Do I need to further modify the JS variable(s)/encode something else to enable it to be viewed as a proper base64 image?

All possibilities and proper explanations would be appreciated.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 韩国网站购物,KG支付的支付回调如何解决
    • ¥15 workstation导入ovf文件,报错,怎么解决呢?
    • ¥15 关于#c语言#的问题:构成555单稳态触发器,采用LED指示灯延时时间,对延时时间进行测量并显示(如楼道声控延时灯)需要Proteus仿真图和C语言代码
    • ¥15 workstation加载centos进入emergency模式,查看日志报警如图,怎样解决呢?
    • ¥50 如何用单纯形法寻优不能精准找不到给定的参数,并联机构误差识别,给定误差有7个?matlab
    • ¥15 workstation加载centos进入emergency模式,查看日志报警如图,没有XFS,怎样解决呢?
    • ¥15 应用商店如何检测在架应用内容是否违规?
    • ¥15 Ubuntu系统配置PX4
    • ¥50 nw.js调用activex
    • ¥15 数据库获取信息反馈出错,直接查询了ref字段并且还使用了User文档的_id而不是自己的