我正在编写一个页面,它允许用户将文件上传到我的远程数据库中。
因此,当用户成功上传文件时,我的标签将显示"文件上传成功"。
如果文件不是我的服务器接受的类型,标签将显示"文件格式不正确。请重试。"
有可能吗?
<form method="post" role="form" action="/LS/import_export.html">
<div class="form-group">
<input type="file" name="file" id="file" size="75">
<label for="file">PHP Code here?</label>
</div>
<button type="submit" name="Import" value="Import">Upload</button>
</form>
这是为了让您从基础知识开始。
<?php
if( isset($_FILES["file"]) and $_FILES["file"]["tmp_name"] != ""){
/* Do your validation here
Reference URL
http://www.w3schools.com/php/php_file_upload.asp
*/
if($move_file){
$status = "File Uploaded Successfully";
} else {
$status = "Incorrect file format. Please try again.";
}
}
?>
<form method="post" role="form" method="post" enctype="multipart/form-data">
<div class="form-group">
<input type="file" name="file" id="file" size="75">
<label for="file">PHP Code here?</label>
</div>
<button type="submit" name="Import" value="Import">Upload</button>
</form>
是的,您需要检查
$_FILES['file']['type']
你可以将其与一系列可接受的文件格式进行比较,比如
$aExceptedFormats = array('image/jpg', 'image/png');
if (!in_array($_FILES['file']['type'], $aExceptedFormats)) {
echo "Incorrect file format. Please try again.";
}
$con = mysql_connect(...) or die(mysql_error());
$db = mysql_select_db('database', $con);
if($db)
{
$query = "INSERT INTO upload(u_name,name,size,type,content) VALUES (specific values ...)";
mysql_query($query) or die('Error, query failed');
mysql_close();
echo "<ul class='testimonials'>
<li>
<blockquote>
<center><span style='color: green;'>File Uploaded Successfully</span></center>
</blockquote>
</li>
</ul>";
}
else
{
echo "<ul class='testimonials'>
<li>
<blockquote>
<center>span style='color: red;'>File Uploading Failed</span></center>
</blockquote>
</li>
</ul>";
}
}
你可以试试这个。。
将操作属性更改为空白或使用$_SERVER['PHP_SELF']
。
将您的POST
操作放在表单之前。
注意:使用enctype="multipart/form-data"
上传文件
例如。
if(isset($_POST['Import'])){
if ($_FILES["file"]["error"] > 0) {
echo "Error: " . $_FILES["file"]["error"] . "<br>";
} else {
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Stored in: " . $_FILES["file"]["tmp_name"];
}
}
<form method="post" role="form" action="/LS/import_export.html" enctype="multipart/form-data">
<div class="form-group">
<input type="file" name="file" id="file" size="75">
<label for="file">PHP Code here?</label>
</div>
<input type="submit" name="Import" value="Upload" />
</form>
关于PHP上传的参考资料。你可以在这里查一下。
您可以使用HTML5 accept属性限制使用:
<input type="file" name="my-image" id="image" accept="image/gif, image/jpeg, image/png" />
或使用PHP
$approved_types = array("image/png","image/jpg","image/jpeg");
$approved_exts = array("png","jpg","jpeg");
if (!in_array($_FILES['new_image']['type'], $approved_types)) {
die("Wrong type of file submitted press use your back button and try again.");
}
参考:http://www.dreamincode.net/forums/topic/148485-restricting-file-types-and-size-in-upload-form/