2014-01-30 126 views
0

我想用ajax和php上傳一個沒有頁面刷新和提交的文件。 我的代碼能夠運行並提醒有效的消息,如果我只是做preg_match,但是當我添加需要使用$_FILES[$filrec]["tmp_name"]的驗證的其餘部分時,它不會提醒我有效的消息。如何在不提交表單的情況下上傳文件?

這裏有什麼問題?如果沒有用下面的方法提交表單,上傳文件是不可能的?

有一堆不同的建議和例子,更復雜的JavaScript或jQuery方法,但我試圖簡單地ajax和剩下的PHP。這可能與我的bellow 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); 
} 

讚賞

+0

究竟爲什麼你要在'fileprs'上做一個mysql轉義?你只在你剛剛在SQL查詢中使用轉義字符串時才這樣做。將它用於任何其他目的不是一個好主意。 –

+0

是唯一的問題嗎? –

+1

'fileselected'也不會出現在任何地方,除非你把它塞進ajax調用中... –

回答

0

您可以使用下面的PHP代碼來獲取文件從阿賈克斯獲得:

$數據=拆分( 「」 的file_get_contents( 'PHP://輸入'));

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

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

相關問題