//NOTE: this code is jquery, go to JQuery.com and find the download then link it in a script tag
$("#activateFile").on('click', function(){
$("#fileBrowser").click();
});
//if you want a finish edit button then use this otherwise put this code in the fileBrowser change event handler below KEEP THE readURL(this) OR IT WON'T WORK!
$("#finishEdit").on('click', function(){
var imgData = document.getElementById('image').src;
//imageData is the variable you use $_POST to get the data in php
$.post('phpscriptname.php', {imageData:imgData}, function(data){
//recieve information back from php through the echo function(not required)
});
});
$("#fileBrowser").change(function(){
readURL(this);
});
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#image').attr('src', e.target.result)
};
reader.readAsDataURL(input.files[0]);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>Whatever your title is</title>
</head>
<body>
<img id="image" src="somesource.png" alt="somesource"/>
<!-- NOTE: you can use php to input the users current image in the source attribute -->
<br/>
<br/>
<!-- position and style these however you like -->
<input type="file" id="fileBrowser"> <!-- this is display none in css -->
<button id="activateFile">Choose files</button>
<br/>
<br/>
<button id="finishEdit">Done</button>
</body>
</html>
现在我将展示带有数据库的服务器端
require("yourconnectiontodatabase.php"); //create a connection to your db.
$imgData = $_POST['imageData']; //the same variable we gave it in the jquery $.post method.
//The bad part now is because we are using data straight from the input I don't think it's possible to know if the content type of the file is an image. This is a security flaw as people could try upload .exe files however, I do know the imagedata we get in javascript contains the filetype it is so you could check in javascript if it's an image type like if it's png or jpeg.
//NOTE: when looking for types in images use image/type for example image/png
//upload image to database
$updateprofile = mysql_query("UPDATE table_name SET profileimage='$imgData' ");
2条答案
按热度按时间hwazgwia1#
这不是最好的方式来做的事情,事实上,我正在寻找一个更快的方法来做到这一点,但这里是我自己编码,将上传的图像数据到数据库,也自动更改您的个人资料照片没有刷新。
首先是客户端的HTML、CSS和Javascript/JQuery。
现在我将展示带有数据库的服务器端
1zmg4dgp2#
创建连接文件conn.php
用index.php创建图片上传页面
创建图片上传php脚本ajaxupload.php