【问题标题】:Converting file upload to binary, post to server and save file using PHP使用PHP将文件上传转换为二进制,发布到服务器并保存文件
【发布时间】:2013-12-24 13:53:29
【问题描述】:

我正在使用无法将文件发布到服务器的应用程序。因此,我选择将其作为字符串发送到服务器,并使用 PHP 将其重新制作为文件。下面是我用来将图像转换为字符串的 javascript 代码。

var file = document.getElementById("fileForUpload").files[0];
if (file) {
    var reader = new FileReader();
    reader.readAsText(file);
    reader.onload = function (evt) {
        document.getElementById("fileContents").value = utf8_to_b64(evt.target.result);
    }
    reader.onerror = function (evt) {
        document.getElementById("fileContents").value = "error reading file";
    }
}

function utf8_to_b64(str) {
    return window.btoa(unescape(encodeURIComponent(str)));
}

在服务器端我正在这样做

header("Content-type: image/png");
$data = preg_replace('/\s+/', '', $data);
echo base64_decode($data);
exit;

但它说图像无法显示,因为它包含错误。

你能告诉我我在这里做错了什么吗?我正确地接收到服务器的 Base64 编码字符串。

编辑

请注意,我正在尝试通过 HTML 表单发布字符串。

【问题讨论】:

    标签: php html image file-upload base64


    【解决方案1】:

    简单:

    $imagedata = file_get_contents("/path/to/image.jpg");
                 // alternatively specify an URL, if PHP settings allow
    $base64 = base64_encode($imagedata);
    bear in mind that this will enlarge the data by 33%, and you'll have problems with files whose size exceed your memory_limit.
    

    【讨论】:

    • 这是在解决完全不同的问题。请再次阅读问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-14
    • 2010-12-23
    • 2017-07-11
    • 1970-01-01
    • 1970-01-01
    • 2016-02-21
    • 2013-02-12
    相关资源
    最近更新 更多