【问题标题】:how to upload an image with a text post AJAX, php, and html如何上传带有文本帖子 AJAX、php 和 html 的图像
【发布时间】:2017-04-01 21:02:57
【问题描述】:

您好,我正在尝试使用 php ajax 和 html 将添加了 cmets 的图像上传到数据库中。

这里是html部分:

<form name="form1" enctype="multipart/form-data" action="">
            <h2></h2>
            <div class="form-group">
            <textarea name="msg" class="form-control status-box" id="post" rows="3" cols="60" placeholder="What\'s on your mind?"></textarea>

            <p>Upload an image.</p>
            <input type="file" id="postPhoto" name="postPhoto" value="upload" placeholder="Upload Image">

            </div>
    </form>

    <div class="button-group pull-right">
        <p class="counter">200</p>
        <a href="#" type="submit" onclick="submitChat()" class="post btn btn-primary">
            Post</a>
    </div><br><br>

这就是我对 ajax 的要求,它与 html 位于同一页面上

<script>
function submitChat() {
var file = document.getElementById("postPhoto");
var formData = new FormData();
// alert(formData);
formData.append("file[]", file.files[0]);

if(form1.msg.value == '') {
    alert('You must Enter a Post');
    return;
}



var msg = form1.msg.value;
var xmlhttp = new XMLHttpRequest();

xmlhttp.onreadystatechange = function() {
    if(xmlhttp.readyState==4 && xmlhttp.status==200) {
        document.getElementById('logs').innerHTML = xmlhttp.responseText;

    console.log(xmlhttp.statusText);
    }
}
xmlhttp.open('POST', 'userposts.php?msg='+msg, true);
xmlhttp.setRequestHeader("Content-type", "multipart/form-data");
xmlhttp.send(formData);


}
<script>

这是php部分:

$msg = stripslashes(htmlspecialchars($_REQUEST['msg']));
 if(isset($_FILES['postPhoto']['type'])) {
$imageData = "";
$validextensions = array("jpeg", "jpg", "png");
$temporary = explode(".", $_FILES['postPhoto']['name']);
$file_extension = end($temporary);

if((($_FILES['postPhoto']['type'] === 'image/png') || ($_FILES['postPhoto']['type'] == 'image/jpg') || ($_FILES['postPhoto']['type'] == 'image/jpeg')) && ($_FILES['postPhoto']['size'] < 2500000) && in_array($file_extension, $validextensions)) {
    if($FILES['postPhoto']['error'] > 0) {
        echo "return code: " . $_FILES['postPhoto']['error'] . "<br/><br/>";
    }
    else {
        $imageData = mysqli_real_escape_string($connection, file_get_contents($_FILES["postPhoto"]["tmp_name"]));
    }
}
}



$stmt = "INSERT INTO posts VALUES ('', '$uname', '$msg', '$imageData')";
$result = $connection->query($stmt);

图像似乎没有被发送到 php 文件 idk 如何解决这个问题。任何帮助将不胜感激。

【问题讨论】:

  • 试试$_FILES['postPhoto']而不是$_FILES['file']
  • 试试我的解决方案,我已经在另一个帖子上回答了,看看这个->stackoverflow.com/questions/40582426/…
  • @AmitChauhan 我认为 OP 不想使用 jQuery
  • 可能他得用ajax,很简单
  • 嘿,你有答案吗?如果有,请提供给我们,谢谢,,[等待的家伙]

标签: javascript php html ajax image-processing


【解决方案1】:

也许有帮助,

您根本无法使用纯 Javascript ajax 函数上传文件(至少不能以跨浏览器的方式,请参阅本文了解更多信息)

这是因为 XMLHttpRequest 不支持 multipart/form-data,您可以使用 iframe 或使用 flash 等技巧。

互联网上有足够多的文章来解释这一点。(也许有帮助)

http://www.ajaxf1.com/tutorial/ajax-file-upload-tutorial.html

http://www.faqs.org/rfcs/rfc2388.html

推荐

使用 jQuery Ajax。有简单的库。支持和功能上传图像和提交/解析到目标文件。

下面是用于演示的示例 jQuery AJAX 代码

   $(document).ready(function(){
      $(document).on('submit','form[name="form1"]',function(e){
        e.preventDefault();
        var form = $(this)[0];
        var formData = new FormData(form);
            $.ajax({
              url: 'Your url here',
              data: formData,
              type: 'POST',
              // THIS MUST BE DONE FOR FILE UPLOADING
              contentType: false,
              processData: false,
              // ... Other options like success and etc
              success : function(data){
                  //Do stuff for ahed process....
              }
            });

      });
    });

【讨论】:

    猜你喜欢
    • 2011-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-19
    • 2013-07-19
    • 2020-09-05
    • 2015-12-18
    • 1970-01-01
    相关资源
    最近更新 更多