【问题标题】:Image not uploading via ajax图片未通过ajax上传
【发布时间】:2013-12-12 12:26:28
【问题描述】:

我正在尝试通过提交表单来上传图片。以下是我的代码 sn-p:

html:

<form method="POST" id="statusform" action="insertstatus.php" enctype="multipart/form-data">
<textarea name="statusText" onclick="javascript:this.value='';" class="retroText" style="width:600px;height:100px;font-family:lucida sans unicode,lucida grande,sans-serif;resize:none;padding:5px;">Post your crap here ...</textarea>
<input type="file" name="statusPhoto" accept="image/gif, image/jpeg, image/x-ms-bmp, image/x-png" size="26" />
</form>

jquery:

$("#statusform").submit(function() {

        $.post($("#statusform").attr("action"), $("#statusform").serialize(), function(data){           
            alert(data);
        });


        //Important. Stop the normal POST
        return false;
    });

php:

if(isset($_FILES['statusPhoto']) && $_FILES['statusPhoto']['size'] > 0)
{
         <Image Upload Code>
}
else
echo "Photo not submitted";

ajax返回的信息是:照片未提交。 请帮忙..!!

【问题讨论】:

  • 您必须使用 FormData 对象通过 ajax 上传文件

标签: php ajax image


【解决方案1】:

您上传的是图片,而不是图片,您上传的是名称。

$("#statusform").serialize() 返回一个字符串,图像是一个 blob。例如,尝试使用一些jQuery plugins

【讨论】:

  • 我只是在测试是否设置了 $_FILES['statusPhoto'].. 但是事情本身就失败了..
  • 好的。我明白那个。但是,如果我不想使用该插件,可能的解决方案是什么。 ?
  • $_FILES 将始终由您的$.post 为空,因为您不发送文件内容,只发送名称。如果您不想重新加载页面,请尝试将表单提交到 iframe。
【解决方案2】:

您可以按照文章中的说明通过 iframe 异步上传文件:

http://viralpatel.net/blogs/ajax-style-file-uploading-using-hidden-iframe/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-06
    • 1970-01-01
    • 2017-03-27
    相关资源
    最近更新 更多