Passing an image file is unsuccessful using AJAX [duplicate] - javascript

This question already has answers here:
Sending multipart/formdata with jQuery.ajax
(13 answers)
Closed 7 years ago.
I am facing an error where I am unable to pass the image file through AJAX when uploading a image file. Here are my codes
AJAX
var file = $("#thumbnail").get(0).files[0];
alert(file.name+" | "+file.size+" | "+file.type);
var formdata = new FormData();
formdata.append("file", file);
alert (formdata);
$.ajax({
url: "php/post-check.php",
type: "POST",
data: {
title: title,
thumbnail: formdata
},
success: function (data) {
$("div#postresult").removeClass("alert alert-danger");
$("div#postresult").html(data);
}
});
PHP
<?php
$target_dir = "../thumbnail-pictures/";
$target_file = $target_dir . basename($_FILES["thumbnail"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
if (file_exists($target_file)) {
echo "Sorry, thumbnail file already exists. <br>";
$uploadOk = 0;
}
if ($_FILES["thumbnail"]["size"] > 1000000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg") {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded, ";
} else {
if (move_uploaded_file($_FILES["thumbnail"]["tmp_name"], $target_file)) {
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
HTML
<form action="" method="post" enctype="multipart/form-data" id="newpost">
<div class="col-lg-12">
<div class="form-group">
<label>Title</label>
<input class="form-control" name="title" id="title" required>
</div>
<div class="form-group">
<label>Video Thumbnail **Only JPEG & PNG is accepted**</label>
<input type="file" name="thumbnail" id="thumbnail" accept="image/png, image/gif, image/jpeg" >
</div>
The PHP code itself is working fine so I assume that the problem lies within the AJAX section, however I am unsure of how to solve this. Thankful for any help given!

the problem should be on the parameter processData, please add the parameter processData: false,
to your ajax request and try to get your image on the php.
$.ajax({
url: formURL,
type: form.attr('method'),
dataType: 'json',
data: formData,//form.serialize(),
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
beforeSend: function(){},
success: function(data, textStatus, jqXHR) {},
error: function(jqXHR, textStatus, errorThrown)
{
alert(jqXHR+ textStatus+ errorThrown);
},
complete: function(){}
});
hope helps.good luck

Place your inputs properly in one form and use FormData() to send the form as a whole. I would suggest something like this :
<form method="post" enctype="multipart/formdata" id="myForm">
<input type="text" name="title" />
<input type="file" name="thumbnail" />
</form>
Build and send the data with js :
var form = document.getElementById('myForm');
var formData = new FormData(form);
alert (formdata);
$.ajax({
url: "php/post-check.php",
type: "POST",
data: formData,
success: function (data) {
$("div#postresult").removeClass("alert alert-danger");
$("div#postresult").html(data);
}
});
Now you can get the data in php like this way :
$title = $_POST['title'];
$thumb = $_FILES['thumbnail'];
$tmp_file_path = $thumb['tmp_name'];

You could just post the entire form in async using ajaxForm() like this:
$("#newpost").ajaxForm({
success: function(data) {
$("div#postresult").removeClass("alert alert-danger");
$("div#postresult").html(data);
},
error: function(a, textStatus, exception) {
}
});
AjaxForm is not part of core JQuery but you can find the source here and the documentation here

Related

posting formData to PHP script for file upload

Not sure why I am unable to send the formData over to my PHP script.
I have used this same code before with success.
Here is the HTML:
<form role="form" id="uploadForm" name="uploadForm" action="index.php" enctype="multipart/form-data" method="post">
<input type="file" id="file" name="file" />
<button type="button" id="uploadSubmit" class="btn btn-sm btn-flat btn-primary uploadSubmit">Upload Proforma</button>
</form>
Here is the JavaScript
$('#uploadSubmit').on('click', function(e){
e.preventDefault();
var formData = new FormData();
formData.append("file", document.getElementById('file').files[0]);
$.ajax({
url: 'api/uploadDoc.php',
method: "POST",
data: formData,
contentType: false,
cache: false,
processData: false,
success: function(data){
console.log(data);
},
error: function(jqHHR, textStatus, errorThrown){
console.log('fail: ' + errorThrown);
}
});
return false;
});
Here is the PHP uploadDoc.php script:
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Requested-With");
print_r($_POST);
?>
I just added the headers in the PHP script, as found here:
FormData not posting data to php backend script
Using print_r($_POST), I am only getting a blank array in the console that looks like the following:
Array
(
)
Not sure what I am doing wrong.
Why is the post showing a blank array and the file information or formData?
How do I correct this issue so that the PHP script can retrieve the file that I am uploading?
You need to get the files using the variable $_FILES instead of $_POST
You can make sure the uploaded file by using is_uploaded_file. But if you want to retrieve the file contents, simply you can use readfile as following:
if (!is_uploaded_file($_FILES['file']['tmp_name'])) {
die("Possible file upload attack: filename '". $_FILES['file']['tmp_name'] . "'.");
}
echo "File ". $_FILES['file']['name'] ." uploaded successfully.\n";
echo "Displaying contents\n";
readfile($_FILES['file']['tmp_name']);
I found my answer here:
jQuery AJAX file upload PHP
I updated my onClick event to read as follows:
$('#uploadProformaSubmit').on('click', function(e){
e.preventDefault();
var file_data = $('#file').prop('files')[0]; // <-- added this
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: 'api/uploadDoc.php',
method: "POST",
type: "post", // <-- added this
data: formData,
contentType: false,
cache: false,
processData: false,
success: function(data){
console.log(data);
},
error: function(jqHHR, textStatus, errorThrown){
console.log('fail: ' + errorThrown);
}
});
return false;
});
Over in the PHP script, I could do the following:
<?php
if(isset($_FILES['file'])){
$file = $_FILES['file']['tmp_name'];
$handle = fopen($file, "r");
$i = 0;
echo "this is the file " . $file;
?>
And now the file is posting.
Maybe because the site is using an older version of JQuery (1.8.2.min.js), though I cannot be certain.

Uncaught TypeError: Illegal invocation when trying to upload file via ajax? [duplicate]

I want to implement a simple file upload in my intranet-page, with the smallest setup possible.
This is my HTML part:
<input id="sortpicture" type="file" name="sortpic" />
<button id="upload">Upload</button>
and this is my JS jquery script:
$("#upload").on("click", function() {
var file_data = $("#sortpicture").prop("files")[0];
var form_data = new FormData();
form_data.append("file", file_data);
alert(form_data);
$.ajax({
url: "/uploads",
dataType: 'script',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(){
alert("works");
}
});
});
There is a folder named "uploads" in the root directory of the website, with change permissions for "users" and "IIS_users".
When I select a file with the file-form and press the upload button, the first alert returns "[object FormData]". the second alert doesn't get called and the"uploads" folder is empty too!?
Can someone help my finding out whats wrong?
Also the next step should be, to rename the file with a server side generated name. Maybe someone can give me a solution for this, too.
You need a script that runs on the server to move the file to the uploads directory. The jQuery ajax method (running on the client in the browser) sends the form data to the server, then a script running on the server handles the upload.
Your HTML is fine, but update your JS jQuery script to look like this:
(Look for comments after // <-- )
$('#upload').on('click', function() {
var file_data = $('#sortpicture').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
alert(form_data);
$.ajax({
url: 'upload.php', // <-- point to server-side PHP script
dataType: 'text', // <-- what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(php_script_response){
alert(php_script_response); // <-- display response from the PHP script, if any
}
});
});
And now for the server-side script, using PHP in this case.
upload.php: a PHP script that is located and runs on the server, and directs the file to the uploads directory:
<?php
if ( 0 < $_FILES['file']['error'] ) {
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
}
?>
Also, a couple things about the destination directory:
Make sure you have the correct server path, i.e., starting at the PHP script location what is the path to the uploads directory, and
Make sure it's writeable.
And a little bit about the PHP function move_uploaded_file, used in the upload.php script:
move_uploaded_file(
// this is where the file is temporarily stored on the server when uploaded
// do not change this
$_FILES['file']['tmp_name'],
// this is where you want to put the file and what you want to name it
// in this case we are putting in a directory called "uploads"
// and giving it the original filename
'uploads/' . $_FILES['file']['name']
);
$_FILES['file']['name'] is the name of the file as it is uploaded. You don't have to use that. You can give the file any name (server filesystem compatible) you want:
move_uploaded_file(
$_FILES['file']['tmp_name'],
'uploads/my_new_filename.whatever'
);
And finally, be aware of your PHP upload_max_filesize AND post_max_size configuration values, and be sure your test files do not exceed either. Here's some help how you check PHP configuration and how you set max filesize and post settings.
**1. index.php**
<body>
<span id="msg" style="color:red"></span><br/>
<input type="file" id="photo"><br/>
<script type="text/javascript" src="jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(document).on('change','#photo',function(){
var property = document.getElementById('photo').files[0];
var image_name = property.name;
var image_extension = image_name.split('.').pop().toLowerCase();
if(jQuery.inArray(image_extension,['gif','jpg','jpeg','']) == -1){
alert("Invalid image file");
}
var form_data = new FormData();
form_data.append("file",property);
$.ajax({
url:'upload.php',
method:'POST',
data:form_data,
contentType:false,
cache:false,
processData:false,
beforeSend:function(){
$('#msg').html('Loading......');
},
success:function(data){
console.log(data);
$('#msg').html(data);
}
});
});
});
</script>
</body>
**2.upload.php**
<?php
if($_FILES['file']['name'] != ''){
$test = explode('.', $_FILES['file']['name']);
$extension = end($test);
$name = rand(100,999).'.'.$extension;
$location = 'uploads/'.$name;
move_uploaded_file($_FILES['file']['tmp_name'], $location);
echo '<img src="'.$location.'" height="100" width="100" />';
}
Use pure js
async function saveFile()
{
let formData = new FormData();
formData.append("file", sortpicture.files[0]);
await fetch('/uploads', {method: "POST", body: formData});
alert('works');
}
<input id="sortpicture" type="file" name="sortpic" />
<button id="upload" onclick="saveFile()">Upload</button>
<br>Before click upload look on chrome>console>network (in this snipped we will see 404)
The filename is automatically included to request and server can read it, the 'content-type' is automatically set to 'multipart/form-data'. Here is more developed example with error handling and additional json sending
async function saveFile(inp)
{
let user = { name:'john', age:34 };
let formData = new FormData();
let photo = inp.files[0];
formData.append("photo", photo);
formData.append("user", JSON.stringify(user));
try {
let r = await fetch('/upload/image', {method: "POST", body: formData});
console.log('HTTP response code:',r.status);
alert('success');
} catch(e) {
console.log('Huston we have problem...:', e);
}
}
<input type="file" onchange="saveFile(this)" >
<br><br>
Before selecting the file Open chrome console > network tab to see the request details.
<br><br>
<small>Because in this example we send request to https://stacksnippets.net/upload/image the response code will be 404 ofcourse...</small>
var formData = new FormData($("#YOUR_FORM_ID")[0]);
$.ajax({
url: "upload.php",
type: "POST",
data : formData,
processData: false,
contentType: false,
beforeSend: function() {
},
success: function(data){
},
error: function(xhr, ajaxOptions, thrownError) {
console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});
and this is the php file to receive the uplaoded files
<?
$data = array();
//check with your logic
if (isset($_FILES)) {
$error = false;
$files = array();
$uploaddir = $target_dir;
foreach ($_FILES as $file) {
if (move_uploaded_file($file['tmp_name'], $uploaddir . basename( $file['name']))) {
$files[] = $uploaddir . $file['name'];
} else {
$error = true;
}
}
$data = ($error) ? array('error' => 'There was an error uploading your files') : array('files' => $files);
} else {
$data = array('success' => 'NO FILES ARE SENT','formData' => $_REQUEST);
}
echo json_encode($data);
?>

how to insert an image to database using ajax jquery

so i have a form update but my problem is i cant save my image into my database only the file path..
here is my code.
<form action="" id="update_profile" method="POST" enctype="multipart/form-data">
<div class="col-md-4">
<img class="img-responsive" id="profile_image" name="profile_image" src=""/>
<input class="btn-success" type="file" name="image" id="image" onchange="loadFile(event)">
</div>
<input type="text" id="users_lastname" name="users_lastname" class="form-control" value="">
</form>
from the form update i use ajax to display the data from my database to the form fields..
$.ajax({
url:'../ajax/getprofile.php',
type:'POST',
data:{userid:user},
dataType:'JSON',
success: function(result){
$('#profile_image').attr('src',result.profile_image);
$('#users_lastname').val(result.users_firstname);
},
error:function(status){
}
});
$('#update_profile').submit(function(){
var formData = new FormData($(this)[0]);
$.ajax({
url: '../ajax/update_profile.php',
type:'POST',
data: formData,
dataType: 'JSON',
contentType: false,
cache: false,
processData:false,
success:function(result){
console.log(result);
},
error:function(status){
// console.log(status.responseText);
}
});
});
and use another ajax for submitting the form so basically what happens is from the <img src="../assets/img/faces/avatar.jpg"> this is where i display my image from my db. and when i click the <input class="btn-success" type="file" name="image" id="image" onchange="loadFile(event)"> <img src="../assets/img/faces/koala.jpg"> will change its value...
if (isset($_POST)) {
$users_lastname = $_POST['users_lastname'];
$profile_image = $_POST['profile_image'];
$imgFile = $_FILES['image']['name'];
$tmp_dir = $_FILES['image']['tmp_name'];
$imgSize = $_FILES['image']['size'];
}
if($imgFile)
{
$upload_dir = '../assets/img/faces/'; // upload directory
$imgExt = strtolower(pathinfo($imgFile,PATHINFO_EXTENSION)); // get image extension
$valid_extensions = array('jpeg', 'jpg', 'png', 'gif'); // valid extensions
$userpic = rand(1000,1000000).".".$imgExt;
if(in_array($imgExt, $valid_extensions))
{
if($imgSize < 2000000)
{
// unlink($upload_dir.$_SESSION['image']);
move_uploaded_file($tmp_dir,$upload_dir.$userpic);
}
else
{
echo '<script>
alert("Sorry, your file is too large it should be less then 2MB");
</script>';
}
}
else
{
echo '<script>
alert("Sorry, only JPG, JPEG, PNG & GIF files are allowed.");
</script>';
}
}
else
{
$userpic = $imgs; // old image from database
$userpic = substr($userpic,20);
}
if(!isset($errMSG))
{
$path = '../assets/img/faces/'. $userpic;
$action= 'Updated his/her information';
$logs= $log->insertLogs($usernm,$action);
$res = $users->Userupdated($user,$users_firstname,$users_lastname,$users_email);
$data = $users->updateUserdetail($user,$path,$profile_contact,$profile_address,$profile_department,$profile_specialization,$profile_aboutme);
}
else{
$errMSG = "Sorry Data Could Not Updated !";
}
but when i tried to upload without replacing the image from the src. what happens is it only uploads the location path not the exact image. also when i replace the image it only uploads the location path.. i dont know if this is the correct approach for getting the src image any idea for this?
Try this, I used this in one of my proect:
var form = $("#update_profile").get(0);
e.preventDefault(); //keeps the form from behaving like a normal (non-ajax) html form
$.ajax({
url: '../ajax/update_profile.php',
type: 'POST',
data: new FormData(form),
dataType: 'json',
mimeType: 'multipart/form-data',
processData: false,
contentType: false,
success: function (response) {
},
error: function (data) {
}
});

Isset does not work with ajax call

I am making a simple page where user can upload a image without refreshing the whole page. But if(isset($_post[oneimgtxt])) is not working..
here is my serverSide Code that upload image :
<?php
$maxmum_size = 3145728; //3mb
$image_type_allowed = array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_BMP);
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if(isset($_POST["oneimgtxt"])){//<!------------------ this line is not working
if((!empty($_FILES[$_FILES['upimage']['tmp_name']])) && ($_FILES["upimage"]['error'] == 0)){
$file=$_FILES['upimage']['tmp_name'];
$image_count = count($_FILES['upimage']['tmp_name']);
if($image_count == 1){
$image_name = $_FILES["upimage"]["name"];
$image_type = $_FILES["upimage"]["type"];
$image_size = $_FILES["upimage"]["size"];
$image_error = $_FILES["upimage"]["error"];
if(file_exists($file)){//if file is uploaded on server in tmp folder (xampp) depends !!
$filetype =exif_imagetype($file); // 1st method to check if it is image, this read first binary data of image..
if (in_array($filetype, $image_type_allowed)) {
// second method to check valid image
if(verifyImage($filename)){// verifyImage is function created in fucrenzione file.. using getimagesize
if($ImageSizes < $maxmum_size){//3mb
$usr_dir = "folder/". $image_name;
move_uploaded_file($file, $usr_dir);
}else{
$error_container["1006"]=true;
}
}else{
$error_container["1005"]=true;
}
}else{
$error_container["1004"]=true;
}
}else{
$error_container["1003"]=true;
}
}else{
$error_container["1002"]=true;
}
}else{
$error_container["1007"]=true;
}
}else{//this else of image issset isset($_POST["oneimgtxt"])
$error_container["1001"]=true;//"Error during uploading image";
}
echo json_encode($error_container);
}
?>
in chrome inspect element i got this..
image
and this is my js code with ajax...
$(".sndbtn").click( function(e){
var form = $("#f12le")[0];
var formdata = new FormData(form)
$.ajax({
type:'POST',
//method:'post',
url: "pstrum/onphotx.php",
cache:false,
data: {oneimgtxt : formdata},
processData: false,
contentType: false,
success:function (e){console.log(e);}
});
});
Here is html code:
<form method="post" id="f12le" enctype="multipart/form-data">
<input type="file" name="upimage"/>
<label for="imgr">Choose an Image..</label>
<textarea placeholder="Write something about photo"></textarea>
<input type="button" name="addimagedata" value="Post" class="sndbtn"/>
</form>
Thanks for any help.
You should send your FormData as a whole data object not a part of another data object. So, it should be like this -
$(".sndbtn").click( function(e){
var form = $("#f12le")[0];
var formdata = new FormData(form)
$.ajax({
type:'POST',
//method:'post',
url: "pstrum/onphotx.php",
cache:false,
data: formdata,
processData: false,
contentType: false,
success:function (e){console.log(e);}
});
});
Now, you should be able to access the form as it is. For example if you have any input with name inputxt inside the form, you should be able to access it with $_POST['inputxt']. And if you have any input type="file" with the name upimage, you need to access through $_FILES['upimage']. So, if you want to do isset() for that. You can do like this :
if(isset($_FILES['upimage'])){
add enctype on form any time using file inputs
<form enctype="multipart/form-data" >
<input type=file />
...
</form>
and make sure it's always a POST request.
Good luck...!
I had headaches for this thing! you should use $_FILES['name_of_dom_element']; in your php code.

jQuery AJAX file upload PHP

I want to implement a simple file upload in my intranet-page, with the smallest setup possible.
This is my HTML part:
<input id="sortpicture" type="file" name="sortpic" />
<button id="upload">Upload</button>
and this is my JS jquery script:
$("#upload").on("click", function() {
var file_data = $("#sortpicture").prop("files")[0];
var form_data = new FormData();
form_data.append("file", file_data);
alert(form_data);
$.ajax({
url: "/uploads",
dataType: 'script',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(){
alert("works");
}
});
});
There is a folder named "uploads" in the root directory of the website, with change permissions for "users" and "IIS_users".
When I select a file with the file-form and press the upload button, the first alert returns "[object FormData]". the second alert doesn't get called and the"uploads" folder is empty too!?
Can someone help my finding out whats wrong?
Also the next step should be, to rename the file with a server side generated name. Maybe someone can give me a solution for this, too.
You need a script that runs on the server to move the file to the uploads directory. The jQuery ajax method (running on the client in the browser) sends the form data to the server, then a script running on the server handles the upload.
Your HTML is fine, but update your JS jQuery script to look like this:
(Look for comments after // <-- )
$('#upload').on('click', function() {
var file_data = $('#sortpicture').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
alert(form_data);
$.ajax({
url: 'upload.php', // <-- point to server-side PHP script
dataType: 'text', // <-- what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(php_script_response){
alert(php_script_response); // <-- display response from the PHP script, if any
}
});
});
And now for the server-side script, using PHP in this case.
upload.php: a PHP script that is located and runs on the server, and directs the file to the uploads directory:
<?php
if ( 0 < $_FILES['file']['error'] ) {
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
}
?>
Also, a couple things about the destination directory:
Make sure you have the correct server path, i.e., starting at the PHP script location what is the path to the uploads directory, and
Make sure it's writeable.
And a little bit about the PHP function move_uploaded_file, used in the upload.php script:
move_uploaded_file(
// this is where the file is temporarily stored on the server when uploaded
// do not change this
$_FILES['file']['tmp_name'],
// this is where you want to put the file and what you want to name it
// in this case we are putting in a directory called "uploads"
// and giving it the original filename
'uploads/' . $_FILES['file']['name']
);
$_FILES['file']['name'] is the name of the file as it is uploaded. You don't have to use that. You can give the file any name (server filesystem compatible) you want:
move_uploaded_file(
$_FILES['file']['tmp_name'],
'uploads/my_new_filename.whatever'
);
And finally, be aware of your PHP upload_max_filesize AND post_max_size configuration values, and be sure your test files do not exceed either. Here's some help how you check PHP configuration and how you set max filesize and post settings.
**1. index.php**
<body>
<span id="msg" style="color:red"></span><br/>
<input type="file" id="photo"><br/>
<script type="text/javascript" src="jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(document).on('change','#photo',function(){
var property = document.getElementById('photo').files[0];
var image_name = property.name;
var image_extension = image_name.split('.').pop().toLowerCase();
if(jQuery.inArray(image_extension,['gif','jpg','jpeg','']) == -1){
alert("Invalid image file");
}
var form_data = new FormData();
form_data.append("file",property);
$.ajax({
url:'upload.php',
method:'POST',
data:form_data,
contentType:false,
cache:false,
processData:false,
beforeSend:function(){
$('#msg').html('Loading......');
},
success:function(data){
console.log(data);
$('#msg').html(data);
}
});
});
});
</script>
</body>
**2.upload.php**
<?php
if($_FILES['file']['name'] != ''){
$test = explode('.', $_FILES['file']['name']);
$extension = end($test);
$name = rand(100,999).'.'.$extension;
$location = 'uploads/'.$name;
move_uploaded_file($_FILES['file']['tmp_name'], $location);
echo '<img src="'.$location.'" height="100" width="100" />';
}
Use pure js
async function saveFile()
{
let formData = new FormData();
formData.append("file", sortpicture.files[0]);
await fetch('/uploads', {method: "POST", body: formData});
alert('works');
}
<input id="sortpicture" type="file" name="sortpic" />
<button id="upload" onclick="saveFile()">Upload</button>
<br>Before click upload look on chrome>console>network (in this snipped we will see 404)
The filename is automatically included to request and server can read it, the 'content-type' is automatically set to 'multipart/form-data'. Here is more developed example with error handling and additional json sending
async function saveFile(inp)
{
let user = { name:'john', age:34 };
let formData = new FormData();
let photo = inp.files[0];
formData.append("photo", photo);
formData.append("user", JSON.stringify(user));
try {
let r = await fetch('/upload/image', {method: "POST", body: formData});
console.log('HTTP response code:',r.status);
alert('success');
} catch(e) {
console.log('Huston we have problem...:', e);
}
}
<input type="file" onchange="saveFile(this)" >
<br><br>
Before selecting the file Open chrome console > network tab to see the request details.
<br><br>
<small>Because in this example we send request to https://stacksnippets.net/upload/image the response code will be 404 ofcourse...</small>
var formData = new FormData($("#YOUR_FORM_ID")[0]);
$.ajax({
url: "upload.php",
type: "POST",
data : formData,
processData: false,
contentType: false,
beforeSend: function() {
},
success: function(data){
},
error: function(xhr, ajaxOptions, thrownError) {
console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});
and this is the php file to receive the uplaoded files
<?
$data = array();
//check with your logic
if (isset($_FILES)) {
$error = false;
$files = array();
$uploaddir = $target_dir;
foreach ($_FILES as $file) {
if (move_uploaded_file($file['tmp_name'], $uploaddir . basename( $file['name']))) {
$files[] = $uploaddir . $file['name'];
} else {
$error = true;
}
}
$data = ($error) ? array('error' => 'There was an error uploading your files') : array('files' => $files);
} else {
$data = array('success' => 'NO FILES ARE SENT','formData' => $_REQUEST);
}
echo json_encode($data);
?>

Categories

Resources