2014-07-20 45 views
0

我想用php导入csv文件到数据库表。问题是上传的文件在接收页面中未被识别为csv文件。这里是我的代码:CSV文件上传不起作用

我的形式:

<form enctype='multipart/form-data' method='post' action="new_campaign.php" class="add_campaign_form"> 
    <table class="add_campaign_table"> 
     <tr> 
      <td><label>Campaign Name<label></td> 
     </tr> 
     <tr> 
      <td><input type="text" id="name" class="name" name="camp_name" value='' required/></td> 
     </tr> 
     <tr> 
      <td><label>Notes<label></td> 
     </tr> 
     <tr> 
      <td><textarea id="notes" name="camp_note" rows="4" cols="50" maxlength="250"      placeholder="Campaign details" value='' required> 
      </textarea></td> 
     </tr> 
     <tr> 
      <td><label>Upload CSV File<label></td> 
     </tr> 
     <tr> 
      <td><input type="file" name="csv_file" id="csv" /></td> 
     </tr> 
    </table> 


    <input type="submit" class="submit" alt="Submit" width="120" height="30"/> 

    <br><br> 
</form> 

new_campaign.php

if(isset($_FILES) && $_FILES["file"]['error']==0){ 
if (($_FILES["file"]["type"] == "application/vnd.ms-excel")) { 
    if ($_FILES["file"]["error"] > 0) { 
     echo "error uploading the file"; 
     } 
    else { 
     echo "hooray!"; 
     } 
} 
else { 
    echo "this is not a csv file"; 
    } 
} 
else{ 
    echo "no files"; 
} 

它不断抛出我说: “这不是一个CSV文件” 我收到其他字段值在接收页面中。任何帮助?

+1

是什么'$ _FILES [ “文件”] [ “型”]'说,文件类型是什么? – Andy

+1

增加了这个echo“file type:”。$ _ FILES [“file”] [“type”]; 现在得到这个:“文件类型:这不是一个csv文件” – Abhijith

回答

-1

你输入name="csv_file"

<input type="file" name="csv_file" id="csv" /> 

所以应该

if(isset($_FILES) && $_FILES["csv_file"]['error']==0){ 
if (($_FILES["csv_file"]["type"] == "application/vnd.ms-excel")) { 
    if ($_FILES["csv_file"]["error"] > 0) { 
... 

$_FILES["file"]['error']/$_FILES["file"]["type"]

+0

谢谢很多肖恩。它拯救了我的一天。 – Abhijith

0

感谢肖恩。这里是工作代码:

if(isset($_FILES) && $_FILES["csv_file"]['error']==0){ 

//echo "file type: ".$_FILES["csv_file"]["type"]; 
if (($_FILES["csv_file"]["type"] == "text/csv")) { 
    if ($_FILES["text/csv"]["error"] > 0) { 
     echo "error uploading the file"; 
     } 
    else { 
     echo "hooray!"; 
     } 
} 
else { 
    echo "this is not a csv file"; 
    } 
} 
else{ 
    echo "no files"; 
}