【发布时间】:2012-03-27 13:02:22
【问题描述】:
很长一段时间以来,我一直在我的 PHP 上传脚本中使用非常标准的 HTML 帖子来上传图片。我想通过 JQuery/JSON 将图像发送到 PHP uplaod 脚本来尝试新的东西。我网站上的所有文本数据都是通过这个发送的,我想尝试让图像上传与 JQUery 一起使用。我用谷歌搜索,但只找到预制脚本,没有人有关于自己制作或从哪里开始的教程,使用预制脚本没有任何问题,但很多时候我无法让它与我的网站或风格一起使用它使它适合,所以我开始写一个快速的东西,你们能告诉我这是否可行,因为图像不是文本数据?
我的 HTML:
<div class="upload_box_logged">
<input type="file" id="file_up"><br />
<button id="up_btn">Upload</button>
<em style="display:none; color:red;" id="no_file" >Please Select a File!</em>
<em style="display:none; color:red;" id="up_fail" >Failed!</em>
<em style="display:none; color:red;" id="up_success" >Success!</em>
</div>
我的 JQuery:
$('#up_btn').click(function(){
var fileCheck = $('#file_up').val();
if(fileCheck == '')
{
$('#no_file').fadeIn();
}
else
{
var file_upVar = encodeURIComponent($('#file_up').val());
$.ajax({
type: 'POST', url: 'upload.php', dataType: "json", data: { file_up: file_upVar },
success: function(result) {
if (!result.success) { $('#up_fail').fadeIn().fadeOut(5000); }
else { $('#up_success').fadeIn().fadeOut(5000); }
}
});
}
});
现在这是我的 PHP 文件,我一直在使用我的标准 HTML 发布到 PHP 方法:
$file_name = $HTTP_POST_FILES['ufile1']['name'];
$file_name_for_db = ($HTTP_POST_FILES['ufile1']['name']);
$new_file_name = $id."_pic1_".$file_name;
$allowedTypes = array("image/jpg", "image/jpeg", "image/png");
$maxSize = 5 * 1024 * 1024; // 3Mb
$fileType = $HTTP_POST_FILES['ufile1']["type"];
$fileSize = $HTTP_POST_FILES['ufile1']["size"];
// check if there was an error
if ($HTTP_POST_FILES['ufile1']["error"] > 0)
{
die($HTTP_POST_FILES['ufile1']["error"]);
}
// check if the filetype is valid
if (!in_array($fileType, $allowedTypes))
{
die("Invalid file type: $fileType");
}
// check if the size doesn't exceed the limitations
if ($fileSize > $maxSize)
{
die("The file was too big: $fileSize");
}
$name = $HTTP_POST_FILES['ufile1']["name"];
$tmpfile = $HTTP_POST_FILES['ufile1']["tmp_name"];
// check if the filename is valid
if (preg_match("/[\w-]+\.(jpg|jpeg|png)$/", $name) != 1)
{
die("Invalid file name: $name");
}
$path = "../pic/";
move_uploaded_file($tmpfile, $path);
显然,我必须用类似这样的方式对帖子进行解码。如果这是一种正确的处理方式,我会这样做。
$uploaded_file = htmlspecialchars(trim(urldecode($_POST['file_up'])));
好吧,如果是文本,我会这样做。有什么办法可以用图像数据做到这一点?
非常感谢 -迈克
【问题讨论】:
-
我在想,你知道如何通过 base64 加密将图像作为文本存储在 MySQL 数据库中吗?我可以在JQuery中以某种方式将图像分解为base64,然后将其作为文本发送到PHP文件,然后在那里取消base 64,重新渲染为jpg或png,然后将其保存在我想要的位置......或是不是太奇怪了?
-
我不确定是否可以上传这样的文件。在表单上传中,浏览器从本地磁盘读取文件内容。在 ajax 中,不执行表单发布,您将如何在 javascript 中读取本地文件的内容?它只能从文件输入元素中获取文件名。我听说您可以尝试一个解决方案,即在包含上传表单的页面中嵌入一个 iframe,页面中的脚本将操作 iframe 中的表单。所以上传过程不会刷新页面而是iframe,看起来就像正常的ajax动作,没有页面刷新。