问题
I have a working php code to upload image in the database. Is it Possible to transform it to jquery? If so, what do I need to do? I am new to jquery btw. Thanks
This code works just fine. But I need to do it in jquery.
<form action = 'upload.php' method = 'post' enctype="multipart/form-data">
<input type="file" name="image" > <br>
<input type= 'submit' value = 'Add' id = 'Add' name = 'Add'>
</form>
<?php
if(isset($_FILES['image']))
{
$target_Path = "images/";
$target_Path = $target_Path.basename($_FILES['image']['name'] );
move_uploaded_file( $_FILES['image']['tmp_name'], $target_Path );
$name = $_FILES['image']['name'];
}
if(isset($_POST['Add']))
{
if($_POST["Add"] == "Add")
{
$add = "Insert Into img(path) Values('$name')";
$up = mysql_query($add);
$status = "Upload success!";
print '<script type="text/javascript">';
print 'alert(" '.$status.' ")';
print '</script>';
}
}
回答1:
<form action='upload.php' method='post' enctype="multipart/form-data" id="formupload">
<input type="file" name="image"/> <br>
<input type='submit' value='Add' id='Add' name='Add/>
</form>
You need to first setup a callback for the submit event of the form.
$("#formupload").on("submit", upload_image);- JQuery selectors work a lot like CSS;
$("#formupload")selects the element whose id isformupload. onis used to register a handler for an event.- Here, we are setting up a handler(the upload_image function) for the
submitevent of the element whose id isformupload.
- JQuery selectors work a lot like CSS;
Make an AJAX call to the php script.
function upload_image(event){ event = event || window.event; // Prevent the default form action i.e. loading of a new page if(event.preventDefault){ // W3C Variant event.preventDefault(); } else{ // IE < 9 event.returnValue = false; } $.ajax({ url: "upload.php", type: "POST", data: new FormData($('#formupload')[0]), success : function(data){ // Show success message }, enctype: 'multipart/form-data', processData: false, contentType: false, cache: false }); }- You can prevent the default action of form submission, which is to load the POST response, which is what the first few lines of the function is doing.
- An AJAX call is made using
$.ajaxwhich is the jQuery utility for performing an AJAX call. - The
urlproperty is to be filled by that of your PHP script. - Since it is a file upload, specify the HTTP method as POST.
- The
dataproperty is the payload of the POST request, which is the content of the file you are trying to upload. - You can specify the success callback using the
successproperty, which is the function that will be called on completion of the file upload.
回答2:
You can make an ajax call instead to submit a form. You can use something like this as well:
https://blueimp.github.io/jQuery-File-Upload/
Although, you still need to have your php code in order to store the file in your server
来源:https://stackoverflow.com/questions/29791355/upload-image-using-jquery