[英]Converting file upload to binary, post to server and save file using PHP
I am working with an app where I am unable to post the File to the server. 我正在使用无法将文件发布到服务器的应用程序。 Therefor I have chose to send it as a string to the server, and remake it to a file using PHP.
因此,我选择将其作为字符串发送到服务器,然后使用PHP将其重新制作为文件。 Below is the javascript code I am using to convert the image to a string.
以下是我用来将图像转换为字符串的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)));
}
On the server side I'm doing this 在服务器端,我正在这样做
header("Content-type: image/png");
$data = preg_replace('/\s+/', '', $data);
echo base64_decode($data);
exit;
But it says that the image cannot be displayed because it contains errors. 但是它说图像无法显示,因为它包含错误。
Can you please tell me what I am doing wrong here? 您能告诉我我在做什么错吗? I am correctly receiving the Base64 encoded string to the server.
我正确地将Base64编码的字符串接收到服务器。
Edit 编辑
Please note that I am trying to post the string through an HTML form. 请注意,我正在尝试通过HTML表单发布字符串。
Easy: 简单:
$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.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.