javascript 如何使用 jquery ajax 和 php 上传文件(不点击任何提交按钮)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21164867/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to upload file using jquery ajax and php (without clicking any submit button)
提问by user3177114
I have a form like this:
我有一个这样的表格:
<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>
I want that when the user will selects an image, it would be automatically submitted to my PHP page so that I can save it in the database and return an insert_id with the thumbnail of the picture.
我希望当用户选择图像时,它会自动提交到我的 PHP 页面,以便我可以将其保存在数据库中并返回带有图片缩略图的 insert_id。
I want to do it using jQuery but not able to do so.
我想使用 jQuery 来做到这一点,但无法做到。
PHP code is:
PHP代码是:
回答by Steini
Easy, use a change trigger on your input Element and do an ajax-request inside:
很简单,在输入元素上使用更改触发器并在内部执行 ajax 请求:
$("#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.");
}
});
});
Create a url or route and enter it at url: tag (domain/file.php) and then code serversided stuff:
创建一个 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();
}