use*_*114 1 javascript php ajax jquery file-upload
我有一个这样的表格:
<form method="post" class="form_cnvc">
<p><input type="text" name="f_nm" value="" placeholder="type your first name"></p>
<p><input type="text" name="l_nm" value="" placeholder="type your last name"></p>
<div class="dropfile visible-lg">
<input type="file" id="image_file_input" name="image_file_input">
<span>Select Images(.jpg , .png, .bmp files) </span>
</div>
<p class="submit"><input type="submit" name="submit" value="post"></p>
</form>
Run Code Online (Sandbox Code Playgroud)
我希望当用户选择一个图像时,它会自动提交到我的PHP页面,这样我就可以将它保存在数据库中并返回带有图片缩略图的insert_id.
我想用jQuery做但不能这样做.
PHP代码是:
很简单,在输入元素上使用更改触发器并在内部执行ajax-request:
$("#image_file_input").change(function() {
$.ajax({
url: "my-target-url.php",
type: "post",
dataType: 'json',
processData: false,
contentType: false,
data: {file: $("#image_file_input").val()},
success: function(text) {
if(text == "success") {
alert("Your image was uploaded successfully");
}
},
error: function() {
alert("An error occured, please try again.");
}
});
});
Run Code Online (Sandbox Code Playgroud)
创建一个URL或路由并在url:tag(domain/file.php)中输入它,然后编写服务器代码:
function processFileUpload() {
if(count($_FILES) > 0) {
foreach($_FILES as $file) {
//DO whatever you want with your file, save it in the db or stuff...
//$file["name"];
//$file["tmp_name"];
//Insert here bla blubb
echo "success";
}
}
die();
}
Run Code Online (Sandbox Code Playgroud)