如何上传文件而不提交表格?

时间:2014-01-30 14:30:25

标签: php jquery html ajax

我正在尝试使用ajax和php上传文件而不刷新页面并提交。 如果我只执行preg_match,我的代码就可以运行并提醒有效消息,但是当我添加需要使用$_FILES[$filrec]["tmp_name"]的其余验证时,它不会提醒我有效消息。

这里有什么问题?如果没有使用以下方法提交表单,是不是可以上传文件?

有许多不同的建议和示例以及更复杂的javascript或jquery方法,但我正在尝试简单地使用ajax并将其余部分留给PHP。这可能与我的轰鸣声ajax功能?

Javascript

    var fileselected = $("#browse").val().replace(/C:\\fakepath\\/i, '');
    setTimeout(function() {

                    $.ajax({
                    type: 'POST',
                    url: "ajax/extval.php",
                    data: {fileprs: fileselected},
                    dataType: 'json',
                    cache: false,
                      success: function(resuval) {
                          // file validation result
                          if (resuval === "valid"){
                                   alert ("valid")

PHP

    <form id="upload" method="post" class="<?php echo $orvalue."<separator>".$user_id ?>" action="" enctype="multipart/form-data">
        <div id="formcontent">
       <label class="required" for="unitprice" title="Unit price"><input type="text" id="unitprice" name="unitprice" />Unit price</label>
        <label class="required" for="qty" title="How many pcs"><input type="text" id="qty" name="qty" />Quanity</label>
        <label class="required" for="express" title="Express within China"><input type="text" id="express" name="express" />Express</label>
        <label class="required" for="linkURL" title="Insert a full URL http:\\"><input type="text" id="linkURL" name="linkURL" />Link</label>
       <label  for="yourdesc" title="Describe your need clearly"><textarea id="yourdesc" name="yourdesc"></textarea>Description<li><font size="-2">You can type 400 letters only, you typed :</li><li id="lettercounter"></li>letters</font></label>
        <label for="formsubmit" class="nocontent"><input type="button" id="submitButton" href="#" class="progress-button" value="Add to order" /><strong>Note:</strong> Items marked <img src="../../images/required.jpg" alt="Required marker" width="20" height="20" /> are required fields</label>

      </div>
    </form>

PHP:

 $filrec =mysql_real_escape_string($_POST['fileprs']);

   if(preg_match("/\.(gif|png|jpg|JPG|jpeg|bmp|BMP)$/", $filrec))
    {

    $fileType = exif_imagetype($_FILES[$filrec]["tmp_name"]);
        $allowed = array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG);
    $allin = "valid";
        echo json_encode($allin);
 }

赞赏

2 个答案:

答案 0 :(得分:0)

您可以使用以下PHP代码来获取从Ajax收到的文件:

  

$ data = split(“,”,file_get_contents('php:// input'));

     

$ img_data = base64_decode($ data [1]);

     

file_put_contents('uploads /'。$ _SERVER ['HTTP_X_FILENAME'],     $ img_data);

答案 1 :(得分:0)

您可以使用Follow Ajax POST Request这将为您提供帮助

<script>
$(document.body).on('click','.postDefects',function(){
      var form_data = new FormData();
      var defect = $(this).closest('tr').find( "input[name='defect_id']" ).val();
      var txt_defect=$("#text_defect").val();
      var upload_defect = document.getElementById("upload_defect").files[0];
       form_data.append("upload_defect",upload_defect);
       form_data.append("defect_id",defect_id);
       form_data.append("txt_defect",txt_defect);
      console.log(form_data);
      $.ajax({
          url:"postsample_defects.php",
          method:"POST",
          data: form_data,
          contentType: false,
          cache: false,
          processData: false,
          beforeSend:function(){
          $('#uploaded_image').html("<label class='text-success'>Image Uploading..</label>");
          },
          success:function(data)
          {
           $('#uploaded_image').html(data);             
          }
         });
    });
 </script>