2014-01-19 41 views
9

我知道這個問題已經被問了很多,我嘗試了至少10個不同的代碼來運行這個沒有成功。 我想用jquery.ajax上傳單個文件,但它不起作用。 下面總是代碼輸出:或 '請選擇一個文件',因爲該文件的名稱沒有被設置的東西jquery ajax單個文件上傳

HTML:

<form enctype="multipart/form-data"> 
<input name="file" type="file" /> 
<input type="button" value="Upload" /> 

的jQuery:

$(function() 
$(document).ready(function(){ 
    var files; 

    $('input[type=file]').on('change', prepareUpload); 
    function prepareUpload(event){ 
     files = event.target.files; 
    }; 
    $(':button').click(function(){ 
     var formData = new FormData(); 
     $.each(files, function(key, value){ 
      formData.append(key, value); 
     }); 
     alert(formData); 
     $.ajax({ 
      url: 'check.php', 
      type: 'GET', 
      data: formData, 
      success:function(data){ 
            $('#result').html(data); 
           }, 
      cache: false, 
      contentType: false, 
      processData: false 
     }); 
    }); 
}); 

});

PHP:

 if(isset($_GET['file'])){ 
    $filename = $_FILES['file']['name']; 
    if(isset($filename) && !empty($filename)){ 
     echo 'sup my man?!'; 
    }else{ 
     echo 'please choose a file'; 
    } 
}else{ 
    echo 'not set'; 
} 

我不知道是什麼問題,我知道這是在FORMDATA創建對象,因爲alert-好走,不能正常工作。

在此先感謝您的幫助。 順便說一句,這對我來說真的很重要,它會寫在jQuery中。

+1

你試過 [**此插件**](HTTP://放棄.ie/notebook/simple-file-uploads-using-jquery-ajax) 。我已經使用過2次,或者可能會使用3次,但它的作用就像魅力。 – CodeMonk

+2

我使用plUpload插件。似乎是一個更受歡迎的,它對我來說很好。 http://www.plupload.com/ – johnnyarguelles

+0

謝謝你們,CodeMonk是的,我試過使用這個代碼,這幾乎是問題中的代碼。和約翰尼謝謝你,但我試圖解決這個問題,我不想使用插件。 – user3195129

回答

8

從文件場

做的第一件事A.抓取文件數據的功能結合到你的文件字段的變化事件和抓取文件數據的函數:

// Variable to store your files 
var files; 

// Add events 
$('input[type=file]').on('change', prepareUpload); 

// Grab the files and set them to our variable 
function prepareUpload(event) 
{ 
    files = event.target.files; 
} 

這將文件數據保存到文件變量供以後使用。

B.手柄上提交

當提交表單時,你需要處理在自己的AJAX請求的文件上傳文件上傳。添加下面的結合和功能:

$('form').on('submit', uploadFiles); 

// Catch the form submit and upload the files 
function uploadFiles(event) 
{ 
    event.stopPropagation(); // Stop stuff happening 
    event.preventDefault(); // Totally stop stuff happening 

// START A LOADING SPINNER HERE 

// Create a formdata object and add the files 
var data = new FormData(); 
$.each(files, function(key, value) 
{ 
    data.append(key, value); 
}); 

$.ajax({ 
    url: 'submit.php?files', 
    type: 'POST', 
    data: data, 
    cache: false, 
    dataType: 'json', 
    processData: false, // Don't process the files 
    contentType: false, // Set content type to false as jQuery will tell the server its a query string request 
    success: function(data, textStatus, jqXHR) 
    { 
     if(typeof data.error === 'undefined') 
     { 
      // Success so call function to process the form 
      submitForm(event, data); 
     } 
     else 
     { 
      // Handle errors here 
      console.log('ERRORS: ' + data.error); 
     } 
    }, 
    error: function(jqXHR, textStatus, errorThrown) 
    { 
     // Handle errors here 
     console.log('ERRORS: ' + textStatus); 
     // STOP LOADING SPINNER 
    } 
}); 
} 

什麼這個函數的作用是創建一個新的FORMDATA對象和每個文件追加到它。然後它將該數據作爲請求傳遞給服務器。 2個屬性需要被設置爲false:

  • 過程數據 - 因爲jQuery將文件數組轉換成字符串 和服務器不能把它撿起來。
  • contentType - 將此設置爲false,因爲jQuery默認爲application/x-www-form-urlencoded並且不發送文件。同樣將它設置爲multipart/form-data 似乎也不起作用。

C.上傳文件

快速和骯髒的PHP腳本上傳的文件,並傳回一些信息:

<?php // You need to add server side validation and better error handling here 

$data = array(); 

if(isset($_GET['files'])) 
{ 
$error = false; 
$files = array(); 

$uploaddir = './uploads/'; 
foreach($_FILES as $file) 
{ 
    if(move_uploaded_file($file['tmp_name'], $uploaddir .basename($file['name']))) 
    { 
     $files[] = $uploaddir .$file['name']; 
    } 
    else 
    { 
     $error = true; 
    } 
} 
$data = ($error) ? array('error' => 'There was an error uploading your files') : array('files' => $files); 
} 
else 
{ 
    $data = array('success' => 'Form was submitted', 'formData' => $_POST); 
} 

echo json_encode($data); 

?> 

IMP:不要用這個,寫你自己。

D.處理窗體提交

上傳功能的成功方法傳遞從服務器發送回提交函數的數據。然後,您可以傳遞到服務器。您的文章的一部分:

function submitForm(event, data) 
{ 
    // Create a jQuery object from the form 
$form = $(event.target); 

// Serialize the form data 
var formData = $form.serialize(); 

// You should sterilise the file names 
$.each(data.files, function(key, value) 
{ 
    formData = formData + '&filenames[]=' + value; 
}); 

$.ajax({ 
    url: 'submit.php', 
    type: 'POST', 
    data: formData, 
    cache: false, 
    dataType: 'json', 
    success: function(data, textStatus, jqXHR) 
    { 
     if(typeof data.error === 'undefined') 
     { 
      // Success so call function to process the form 
      console.log('SUCCESS: ' + data.success); 
     } 
     else 
     { 
      // Handle errors here 
      console.log('ERRORS: ' + data.error); 
     } 
    }, 
    error: function(jqXHR, textStatus, errorThrown) 
    { 
     // Handle errors here 
     console.log('ERRORS: ' + textStatus); 
    }, 
    complete: function() 
    { 
     // STOP LOADING SPINNER 
    } 
}); 
} 

最後說明

這個腳本僅是一個例子,你需要同時處理服務器和客戶端驗證和一些方式來通知用戶文件上傳正在發生。如果你想看到它的工作,我在Github上爲它做了一個項目。

Referenced From

+0

再次感謝,但我已經嘗試過使用它沒有成功。 – user3195129

+0

你能展示一個demo/screendump /任何東西來看看發生了什麼! – CodeMonk

+0

http://sell4you.co.il/study/ajaxFileUpload.html – user3195129

8

經過搜索和尋找答案的時間,最後我做到了!!!!! 代碼如下:))))

HTML:

<form id="fileinfo" enctype="multipart/form-data" method="post" name="fileinfo"> 
    <label>File to stash:</label> 
    <input type="file" name="file" required /> 
</form> 
<input type="button" value="Stash the file!"></input> 
<div id="output"></div> 

的jQuery:

$(function(){ 
    $('#uploadBTN').on('click', function(){ 
     var fd = new FormData($("#fileinfo")); 
     //fd.append("CustomField", "This is some extra data"); 
     $.ajax({ 
      url: 'upload.php', 
      type: 'POST', 
      data: fd, 
      success:function(data){ 
       $('#output').html(data); 
      }, 
      cache: false, 
      contentType: false, 
      processData: false 
     }); 
    }); 
}); 

upload.php文件,您可以訪問$_FILES['file']傳遞的數據。

感謝大家的努力幫助:)

我把答案從這裏(含部分變更) MDN

+2

處指定一個動作改進:不要將完整的formdata傳遞給構造函數。使用var formData = new FormData(); ('file',$('input [type = file]')[0] .files [0]); data:formData – tjm1706