PHP+JS: How to do Fileuploads in HTML Form as Content-Type Multipart (via JS)?
You can use a FormData object to get the values of your form, and then append a blob version of your canvas into the FormData.
This blob will be seen as a file by the server.
Unfortunately, all browsers still don't support the native canvas.toBlob()
method, and even worth, all implementations are not the same.
All major browsers now support the toBlob method, and you can find a polyfill on mdn for older browsers.
// the function to create and send our FormData
var send = function(form, url, canvas, filename, type, quality, callback) {
canvas.toBlob(function(blob){
var formData = form ? new FormData(form) : new FormData();
formData.append('file', blob, filename);
var xhr = new XMLHttpRequest();
xhr.onload = callback;
xhr.open('POST', url);
xhr.send(formData);
}, type, quality);
};
// How to use it //
var form = document.querySelector('form'), // the form to construct the FormData, can be null or undefined to send only the image
url = 'http://example.com/upload.php', // required, the url where we'll send it
canvas = document.querySelector('canvas'), // required, the canvas to send
filename = (new Date()).getTime() + '.jpg',// required, a filename
type = 'image/jpeg', // optional, the algorithm to encode the canvas. If omitted defaults to 'image/png'
quality = .5, // optional, if the type is set to jpeg, 0-1 parameter that sets the quality of the encoding
callback = function(e) {console.log(this.response);}; // optional, a callback once the xhr finished
send(form, url, canvas, filename, type, quality, callback);
PHP side would then be :
if ( isset( $_FILES["file"] ) ){
$dir = 'some/dir/';
$blob = file_get_contents($_FILES["file"]['tmp_name']);
file_put_contents($dir.$_FILES["file"]["name"], $blob);
}
File Upload form using php
Some problems with your code...
onsubmit="event.preventDefault(); ...
...prevents the form from submitting the file provided by <input type="file" ...
to the form action
target: upload.php conventionally, such as clicking the submit
button.
~
echo "..." . basename( $_FILES['uploadedFile']['name']) . "...";
echo "<script>document.write(readfile(\"".$target_path."\"));</script>";
$stringPath = $target_path; //PASSING NAME PARAM
printf($stringPath);
...your upload.php file simply writes a string that, if properly called for, gets sent from the server to the browser by way of HTTP.
NO Javascript is executed at this point.
If the browser calls upload.php by loading the page, you leave the current page and only load that string in the browser. If the browser calls upload.php by way of XHR, or Fetch, the page remains but you need to use Javascript to capture the STRING and do something with it.
~
echo "<script>document.write(readfile(\"".$target_path."\"));</script>";
In the PHP file, on the server, you are writing a string of Javascript code, which is sent as text to the browser to be executed there later. The browsers gets something like:
<script>document.write(readfile("uploads/filename.png"));</script>
It's okay to use PHP to send a Javascript string to the browser—however the problem is you're providing a file path on the server. Once the Javascript string gets to the browser and evaluated it does not have access to the server file and directory structure, such as: uploads/filename.png
Since you're attempting to execute a Javascript function named readfile(...)
it appears you're trying to use Javascript FileReader to access the file uploaded to the server, but FileReader only handles files on the client, and provided through a Javascript File or Blob object, or an input type="file"
element, or a drag and drop process.
Keep in mind that PHP executes on the server, and only text gets sent to the browser. The browser then receives the text from the server and processes and renders it.
The PHP context on the server cannot execute Javascript, and the browser context (Javascript/DOM events) on the client cannot execute PHP.
You only have a text channel between the two. And the text channel is only invoked by a page load, or without a page load by using XHR, or Fetch. If you use XHR or Fetch you then need to use Javascript to handle the text received back from the server.
To take a photo, upload it to the server, and display the photo on the page, without reloading the page:
camera.html
<input type="file" id="campic" accept="image/*" capture="camera">
<script>
var campic = document.querySelector("#campic");
campic.onchange = function () {
var file = campic.files[0];
upload(file);
displayAsImage(file);
};
function upload (file) {
var form = new FormData(),
xhr = new XMLHttpRequest();
form.append('image', file);
xhr.open('post', 'upload.php', true);
xhr.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
}
}
xhr.send(form);
}
function displayAsImage (file) {
var imgURL = URL.createObjectURL(file),
img = document.createElement('img');
img.onload = function () {
URL.revokeObjectURL(imgURL);
};
img.src = imgURL;
document.body.appendChild(img);
}
</script>
upload.php
<?php
$target_path = "uploads/";
$target_path = $target_path . basename( $_FILES['uploadedFile']['name']);
if ( move_uploaded_file($_FILES['uploadedFile']['tmp_name'], $target_path) ) {
echo "File uploaded.";
}
else {
echo "Error uploading the file.";
}
?>
Get more information on this approach here: How to use HTML5 to capture a camera image .
How to upload file using pure vanilla javascript and php?
You are using FormData
which works very much the same way a normal form does.
First of all, in PHP files will not be in $_POST
but instead in $_FILES
, see the documentation.
What that documentation does mention, along with the $_FILES
buffer, is that you need to use the multipart/form-data
encoding, any FormData
transferred through an XMLHttpRequest
will have this set by default, though you may want to check it if the $_FILES
remain empty.
You should remove the xhr.setRequestHeader("Content-type","image");
and let the XHR
object handle it, of - if that doesn't work - add
xhr.setRequestHeader("Content-type","multipart/form-data");
There is a pretty nice example right here at stackoverflow
How to insert images and videos into databases
Configure The "php.ini" File
First, ensure that PHP is configured to allow file uploads.
In your "php.ini" file, search for the file_uploads directive, and set it to On:
file_uploads = On
Create The HTML Form
Next, create an HTML form that allow users to choose the image file they want to upload:
<!DOCTYPE html>
<html>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
Some rules to follow for the HTML form above:
Make sure that the form uses method="post"
. The form also needs the following attribute: enctype="multipart/form-data"
. It specifies which content-type to use when submitting the form
Without the requirements above, the file upload will not work.
Other things to notice:
The type="file"
attribute of the <input>
tag shows the input field as a file-select control, with a "Browse" button next to the input control
The form above sends data to a file called "upload.php", which we will create next.
Create The Upload File PHP Script
The "upload.php" file contains the code for uploading a file:
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
?>
more info :
https://www.w3schools.com/php/php_file_upload.asp
https://sites.google.com/site/prgimr/how-to-upload-image-or-files-into-database-using-php-and-mysql
https://www.youtube.com/watch?v=3OUTgnaezNY
Uploading image created from canvas
Instead on making it an image just convert the canvas to base64
:
var canvas = document.getElementById('myCanvas');
var dataURL = canvas.toDataURL();
Now send it:
$.ajax({
type: "POST",
url: "pro01.php",
data: {
imgBase64: dataURL
}
To receive it in php (pro01.php):
Get it from the post request, remove the start and call base64_decode()
on the posted value:
$img = $_POST['imgBase64'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$fileData = base64_decode($img);
//saving
$fileName = 'photo.png';
file_put_contents($fileName, $fileData);
Upload files with HTML/PHP/AJAX and especially SweetAlert2/jquery_file_upload
The solution is to open swal function
swal({
title: "Input title",
html: '<input id="fileupload" type="file" name="files[]" multiple>'
}).then(function() {
(...)
}
And after load scripts with jquery function for fileupload at the same level like swal. In this script it's necessary to call the php code for upload files
$.getScript("script/jquery_file_upload/js/vendor/jquery.ui.widget.js");
$.getScript("script/jquery_file_upload/js/jquery.iframe-transport.js");
$.getScript("script/jquery_file_upload/js/jquery.fileupload.js", function(){
$("#fileupload").fileupload({
url:"script/php/myuploadphp.php",
dataType: 'json',
add: function (e, data) {
data.context = $('#fileuploadname').text('Uploading...').appendTo(document.body);
data.submit();
},
done: function (e, data) {
data.context.text('Upload finished.');
}
});
});
And in PHP write that
$tmpFilePath = $_FILES['files']['tmp_name'][0];
if ($tmpFilePath != ""){
$newFilePath = "destination_folder" . $_FILES['files']['name'][0];
}
And that's work !
Uploading both data and files in one form using Ajax?
The problem I had was using the wrong jQuery identifier.
You can upload data and files with one form using ajax.
PHP + HTML
<?php
print_r($_POST);
print_r($_FILES);
?>
<form id="data" method="post" enctype="multipart/form-data">
<input type="text" name="first" value="Bob" />
<input type="text" name="middle" value="James" />
<input type="text" name="last" value="Smith" />
<input name="image" type="file" />
<button>Submit</button>
</form>
jQuery + Ajax
$("form#data").submit(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
url: window.location.pathname,
type: 'POST',
data: formData,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
});
Short Version
$("form#data").submit(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.post($(this).attr("action"), formData, function(data) {
alert(data);
});
});
How to post a file from a form with Axios
Add the file to a formData
object, and set the Content-Type
header to multipart/form-data
.
var formData = new FormData();
var imagefile = document.querySelector('#file');
formData.append("image", imagefile.files[0]);
axios.post('upload_file', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
Related Topics
Sound Effects in JavaScript/Html5
How to Call a Rest Web Service API from JavaScript
How to Disable Scroll Without Hiding It
Removing an Item from a Select Box
Html Form Action and Onsubmit Issues
Find HTML Label Associated With a Given Input
How to Load an Entire HTML Document into a Document Fragment in Internet Explorer
What Is Innerhtml on Input Elements
Use a Content Script to Access the Page Context Variables and Functions
Self-References in Object Literals/Initializers
Sort Array of Objects by String Property Value
How to Redirect to Another Webpage
How to Find Documentation on Formatting a Date in JavaScript
How Does Access-Control-Allow-Origin Header Work
How to Replace All Occurrences of a String in JavaScript
How to Remove a Specific Item from an Array