php上傳HTML選取的圖片到伺服器
阿新 • • 發佈:2019-01-06
參考:https://blog.csdn.net/zxh543362234/article/details/47019325
主要是對php進行了一些修改~
html程式碼:
<html>
<head>
<script>
function setImagePreview()
{
var docObj=document.getElementById("file");
var imgObjPreview=document.getElementById("preview");
if(docObj.files && docObj.files[0 ])
{
//火狐下,直接設img屬性
imgObjPreview.style.display = 'block';
imgObjPreview.style.width = '200px';
imgObjPreview.style.height = '200px';
//imgObjPreview.src = docObj.files[0].getAsDataURL();
//火狐7以上版本不能用上面的getAsDataURL()方式獲取,需要一下方式
imgObjPreview.src = window.URL.createObjectURL(docObj.files[0]);
}
else
{
//IE下,使用濾鏡
docObj.select();
var imgSrc = document.selection.createRange().text;
var localImagId = document.getElementById("localImag" );
//必須設定初始大小
localImagId.style.width = "300px";
localImagId.style.height = "120px";
//圖片異常的捕捉,防止使用者修改後綴來偽造圖片
try
{
localImagId.style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)";
localImagId.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = imgSrc;
}
catch(e)
{
alert("您上傳的圖片格式不正確,請重新選擇!");
return false;
}
imgObjPreview.style.display = 'none';
document.selection.empty();
}
return true;
}
</script>
</head>
<body>
<form action="這裡寫你這個php介面在伺服器的路徑/uplp.php" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" onchange="javascript:setImagePreview();">
<div id="localImag"><img id="preview" width=-1 height=-1 style="diplay:none" /></div>
<br>
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
主要是對php程式碼進行了一些修改:
<?php
header("Content-type: text/html; charset=utf-8");
if (1)
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";//檔案返回錯誤
}
else
{
$imgname = $_FILES["file"]["name"];
$url="/var/www/html/SG/uploads/";//記錄路徑
if (file_exists($url.$_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
$url=$url.$_FILES["file"]["name"];
move_uploaded_file($_FILES["file"]["tmp_name"],$url);
$imgurl = substr($url,strpos($url,'/')+13);//擷取第一個斜槓後13個字元(包括斜槓)後的字串
}
}
}
else
{
echo "Invalid file";
}
?>
結果顯示:
上傳成功: