Upload Image using javascript in php - javascript

------------------- uploadimage.php file ------------
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<title>Upload Images</title>
<script>
/////This Function Show The Details OF Selected File
function fileselected()
{
var file=document.getElementById("photo").files[0];
document.getElementById("filename").innerHTML=file.name;
document.getElementById("filesize").innerHTML=file.size;
document.getElementById("filetype").innerHTML=file.type;
}
////////When Upload the image upload.php file is call but $_FILES is Empty
function uploadImage()
{
var fd=new FormData();
fd.append("photo",document.getElementById("photo").files[0]);
var xmlhttp = new XMLHttpRequest();
xmlhttp.upload.addEventListener("progress", uploadProgress, false);
var url = "http://localhost/JSONProgram/upload.php";
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("result").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST", url);
xmlhttp.setRequestHeader('Content-Type', 'image/png');
xmlhttp.send(fd);
}
function uploadProgress(evt) {
if (evt.lengthComputable) {
var percentComplete = Math.round(evt.loaded * 100 / evt.total);
document.getElementById('progressNumber').innerHTML = percentComplete.toString() + '%';
document.getElementById('prog').value = percentComplete;
}
else {
document.getElementById('progressNumber').innerHTML = 'unable to compute';
}
}
</script>
</head>
<body>
<form>
<div class="col-md-8">
<div id="result">Result Here</div>
<label for="photo">Select Image</label>
<input type="file" id="photo" name="photo" onchange="fileselected()"/>
<input type="button" value="Upload" onclick="uploadImage()" value="Upload"/>
<div id="filename"></div>
<div id="filesize"></div>
<div id="filetype"></div>
<div id="progressNumber">
</div>
<progress id="prog" value="0" max="100.0"></progress>
</div>
</form>
</body>
</html>
but in upload.php has empty array of $_FILES
<?php
print_r($_FILES);
?>
How To get File for Upload?
Please Help

Add the enctype attribute to your form tag like this:
<form enctype="multipart/form-data">
See this link for more information about the enctype.

Related

Display image from backend on frontend (Flask on backend, JS frontend)

I have web application that getting image (BLOB file in SQL) and needs to show it on web page.
Here is full code of page. 1) form to submit request 2) JS to make request 3) JS code to catch response and show it in
<img id="image_data" src="">
here is info from developer mode so i see image there in preview (and nothing in response)
enter image description here
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="{{ url_for('static', filename= 'css/style.css') }}">
<link rel="shortcut icon" href="/favicon.ico" type="image/x-icon">
<title>Lazy board</title>
</head>
<script>
function addNavBar() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("navbar").innerHTML = this.responseText;
}
};
xhttp.open("GET", "navbar.html", true);
xhttp.send();
}
</script>
<body>
<div id="navbar"></div>
<script>
addNavBar();
</script>
<h1>Get picture</h1>
<form id="getPicture">
<label for="content_id">Content ID:</label>
<br><br>
<input type="text" id="content_id" name="content_id">
<br>
<img id="image_data" src="">
<br>
<input type="submit" class="button" value="Submit">
</form>
<script>
var form = document.getElementById('getPicture');
form.addEventListener('submit', function(event) {
event.preventDefault();
var contentId = document.getElementById('content_id').value;
var xhr = new XMLHttpRequest();
xhr.open('POST', '/getPicture');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.addEventListener('load', function() {
var response = xhr.response;
document.body.innerHTML += response;
document.getElementById('image_data').src = response;
});
var formData = new URLSearchParams();
formData.append('content_id', contentId);
xhr.send(formData);
});
</script>
</body>
</html>
Tried many things. backends response looks like that and yes, in DB is png file that i can view also
return Response(image_data, mimetype='image/png')

XHR based ajax unable to upload files

I've a pretty simple javascript function which tries to send formdata along with an attached file to a php script. Below is my html and javascript code:
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery AJAX Submit Form</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
</head>
<body>
<form id="form" enctype="multipart/form-data">
<input type="text" name="name" id="name">
<input type="file" name="file" id="file">
<input type="button" onclick="upload()" value="Upload">
</form><span id="msg"></span>
<div id="result"></div>
<script type="text/javascript">
function upload(){
var formData = new FormData();
formData.append("file", document.getElementById("file").files[0]);
var xhttp = new XMLHttpRequest();
document.getElementById("msg").innerHTML = document.getElementById('file').files[0];
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200){
document.getElementById("msg").innerHTML = this.responseText;
}
};
xhttp.open("POST", "https://localhost/2.php");
xhttp.setRequestHeader("Content-type", "multipart/form-data");
xhttp.send(formData);
}
</script>
</body>
</html>
And below is my php script "2.php":
<?php
error_reporting(E_ALL);
$myfile = fopen("newfile.txt", "w");
fwrite($myfile, $_POST['name'].$_FILES['file']['name']);
fclose($myfile);
echo 'file written';
move_uploaded_file($_FILES['file']['tmp_name'],$_FILES['file']['name']);
echo "success";
?>
The above php script doesn't has any problem because it is able to retrieve the input text as $_POST['name'] and save it in the text file created. Also the script is successfully able to retrieve the file submitted and save it, only when I submit the html form normally without any javascript.
I want to submit both the input field data and selected file via XHR api only and not through fetch api.

Upload image into Google Drive via Web App and save correspondent link on spreadsheet

This is my first approach with js and html coding, please be as much simple as possible!
I want to improve the form developed in my web App making possible to upload image. My goal is to:
Add input type file on my web App
Send the file to server side
Save the file in the G Drive, take the link and save it in Google Sheet
To do this I have already added in my html a file input area, but I'm not sure about how I may manage it in script section.
All the information added in the form are send to server in an object called measureInfo and I want to maintain this routine. When I try to add
measureInfo.media = document.getElementById('fileUpload').files
it doesn't run and console return `Failed due to illegal value in property: media.
Here I report some string of code that may help to answer. If you have some suggests about how manage file in server side with DriveApp please share!
<script>
measureInfo.media= document.getElementById('fileUpload').files
google.script.run.sendToDatabase(measureInfo);
</script>
<form action="#">
<!-- Upload File -->
<div class="file-field input-field">
<div class="btn-large blue darken-3">
<span>Media</span>
<input type="file" id= 'fileUpload' name ='fileUpload'>
</div>
<div class="file-path-wrapper">
<input class="file-path validate" type="text" placeholder = 'Upload Media'>
</div>
</div>
</form>
You could use FileReader.onload event to build an object that can be passed server-side:
const file = document.getElementById('fileUpload').files[0];
const fr = new FileReader();
fr.onload = (e) => {
const data = e.target.result.split(",");
measureInfo.media = {fileName: file.name, mimeType: file.type, data: data[1]};
google.script.run.sendToDatabase(measureInfo);
}
fr.readAsDataURL(file);
Reference:
FileReader.onload
Uploading Multiple Files From Local To Google Drive using Google Apps Script
Here's some code I use for saving receipts:
HTML with JS:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$(function(){
google.script.run
.withSuccessHandler(function(rObj){
$('#dt').val(rObj.date);
})
.initForm();
});
function fileUploadJs(frmData) {
var amt=$('#amt').val();
var vndr=$('#vndr').val();
var img=$('#img').val();
if(!amt){
window.alert('No amount provided');
$('#amt').focus();
return;
}
if(!vndr) {
window.alert('No vendor provided');
$('#vndr').focus();
return;
}
if(!img) {
window.alert('No image chosen');
$('#img').focus();
}
document.getElementById('status').style.display ='inline';
google.script.run
.withSuccessHandler(function(hl){
document.getElementById('status').innerHTML=hl;
})
.uploadTheForm(frmData)
}
console.log('My Code');
</script>
<style>
input,textarea{margin:5px 5px 5px 0;}
</style>
</head>
<body>
<h3 id="main-heading">Receipt Information</h3>
<div id="formDiv">
<form id="myForm">
<br /><input type="date" name="date" id="dt"/>
<br /><input type="number" name="amount" placeholder="Amount" id="amt" />
<br /><input type="text" name="vendor" placeholder="Vendor" id="vndr"/>
<br /><textarea name="notes" cols="40" rows="2" placeholder="NOTES"></textarea>
<br/>Receipt Image
<br /><input type="file" name="receipt" id="img" />
<br /><input type="button" value="Submit" onclick="fileUploadJs(this.parentNode)" />
</form>
</div>
<div id="status" style="display: none">
<!-- div will be filled with innerHTML after form submission. -->
Uploading. Please wait...
</div>
</body>
</html>
GS:
function uploadTheForm(theForm) {
var rObj={};
rObj['vendor']=theForm.vendor;
rObj['amount']=theForm.amount;
rObj['date']=theForm.date;
rObj['notes']=theForm.notes
var fileBlob=theForm.receipt;
var fldr = DriveApp.getFolderById(receiptImageFolderId);
rObj['file']=fldr.createFile(fileBlob);
rObj['filetype']=fileBlob.getContentType();
Logger.log(JSON.stringify(rObj));
var cObj=formatFileName(rObj);
Logger.log(JSON.stringify(cObj));
var ss=SpreadsheetApp.openById(SSID);
ss.getSheetByName('Receipt Information').appendRow([cObj.date,cObj.vendor,cObj.amount,cObj.notes,cObj.file.getUrl()]);
var html=Utilities.formatString('<br />FileName: %s',cObj.file.getName());
return html;
}
function formatFileName(rObj) {
if(rObj) {
Logger.log(JSON.stringify(rObj));
var mA=rObj.date.split('-');
var name=Utilities.formatString('%s_%s_%s.%s',Utilities.formatDate(new Date(mA[0],mA[1]-1,mA[2]),Session.getScriptTimeZone(),"yyyyMMdd"),rObj.vendor,rObj.amount,rObj.filetype.split('/')[1]);
rObj.file.setName(name);
}else{
throw('Invalid or No File in formatFileName() upload.gs');
}
return rObj;
}
function initForm() {
var datestring=Utilities.formatDate(new Date(),Session.getScriptTimeZone(), "yyyy-MM-dd");
return {date:datestring};
}
<script>
function preventFormSubmit(){
var forms=document.querySelectorAll('form');
for (var i=0;i<forms.length;i++){
forms[i].addEventListener('submit',function(event){
event.preventDefault();
});
}
}
window.addEventListener('load',preventFormSubmit);
function handleFormSubmit(formObject){
google.script.run.processForm(formObject);
document.getElementById("myForm").reset();
}
</script>
<script>
function uploadTheForm(theForm) {
var rObj={};
rObj['vendor']=theForm.vendor;
rObj['amount']=theForm.amount;
rObj['date']=theForm.date;
rObj['notes']=theForm.notes
var fileBlob=theForm.receipt;
var fldr = DriveApp.getFolderById(receiptImageFolderId);
rObj['file']=fldr.createFile(fileBlob);
rObj['filetype']=fileBlob.getContentType();
Logger.log(JSON.stringify(rObj));
var cObj=formatFileName(rObj);
Logger.log(JSON.stringify(cObj));
var ss=SpreadsheetApp.openById(SSID);
ss.getSheetByName('Receipt Information').appendRow([cObj.date,cObj.vendor,cObj.amount,cObj.notes,cObj.file.getUrl()]);
var html=Utilities.formatString('<br />FileName: %s',cObj.file.getName());
return html;
}
function formatFileName(rObj) {
if(rObj) {
Logger.log(JSON.stringify(rObj));
var mA=rObj.date.split('-');
var name=Utilities.formatString('%s_%s_%s.%s',Utilities.formatDate(new Date(mA[0],mA[1]-1,mA[2]),Session.getScriptTimeZone(),"yyyyMMdd"),rObj.vendor,rObj.amount,rObj.filetype.split('/')[1]);
rObj.file.setName(name);
}else{
throw('Invalid or No File in formatFileName() upload.gs');
}
return rObj;
}
function initForm() {
var datestring=Utilities.formatDate(new Date(),Session.getScriptTimeZone(), "yyyy-MM-dd");
return {date:datestring};
}
</script>
<!DOCTYPE html>
<html lang="en">
<head>
<base target="_top">
<?!= include('JavaScript'); ?>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<head>
<script>
$(function(){
google.script.run
.withSuccessHandler(function(rObj){
$('#dt').val(rObj.date);
})
.initForm();
});
function fileUploadJs(frmData) {
var amt=$('#amt').val();
var vndr=$('#vndr').val();
var img=$('#img').val();
if(!amt){
window.alert('No amount provided');
$('#amt').focus();
return;
}
if(!vndr) {
window.alert('No vendor provided');
$('#vndr').focus();
return;
}
if(!img) {
window.alert('No image chosen');
$('#img').focus();
}
document.getElementById('status').style.display ='inline';
google.script.run
.withSuccessHandler(function(hl){
document.getElementById('status').innerHTML=hl;
})
.uploadTheForm(frmData)
}
console.log('My Code');
</script>
</head
<body>
<div class="form-row">
<div class="form-group col-md-12">
<h5 style="text-align:center;">Upload Photo</h5>
<div class="form-row">
<div class="form-group col-md-4" style="word-wrap: break-word">
<p3 style="text-align:left; color:red">
Notice! Please doff eyewear & mask and avoid sunlight exposure when taking selfie!</p>
</div>
<div class="form-group col-md-6"><img id="output" width="200" height="200" src="https://www.citypng.com/public/uploads/small/116395943260tji5ordfujy44njydzhlidv8reqpmtun7ggx1oszpz1dcistzxnmag7do6vxkjxphlsgueuurkg9pkpbwgorvv9lratpxm38rp5.png" alt="photo" style="border:gray; border-width:2px; border-style:solid;"/></div>
<div class="form-group col-md-12">
<center>
&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp <input class="file-path validate" type="file" id="fileUpload" name="fileUpload" value='fileUpload' accept="image/*" onchange="loadFile(event)">
<script>
var loadFile = function(event) {
var output = document.getElementById('output');
output.src = URL.createObjectURL(event.target.files[0]);
output.onload = function() {
URL.revokeObjectURL(output.src) // free memory
}
};
</script>
</div>
</body>
</html>
[1]: https://i.stack.imgur.com/98vPf.png

Sending data from JavaScript to PHP via XMLHttpRequest

Good day.
I'm trying to send a simple piece of data from one php file (manage.php) to another (view.php).
I cannot send the data via a form, I want to send it via a JS script. Here's my attempt:
var read = function(id) {
xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "view.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("id=" + id);
}
In view.php, using $_POST["id"] causes an error stating that the index "id" is undefined.
What's the correct way to send the data? Thank you.
Your input is not complete. So I did the full example below that you can follow. I made a function, named readid(id), doing the same thing as you want. Then I call that function from html, when needed.
<!doctype html>
<html lang="fr">
<head>
<meta charset="iso-8859-1">
<title>Untitled Document</title>
<script type="text/javascript" charset="iso-8859-1">
function readid(id){
"use strict";
console.log("id=", id)
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "/cgi-bin/view.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.onreadystatechange = function() {
if (this.readyState === 4 || this.status === 200){
console.log(this.responseText); // echo from php
}
};
xmlhttp.send("id=" + id);
}
</script>
</head>
<body>
<p>This is a test</p>
<input type="button" name="Submit" value="Submit" id="formsubmit" onClick="readid(id)">
</body>
</html>
view.php
<?php
$logFile = "view.log";
$id = $_POST['id'];
file_put_contents($logFile, $id);
echo $id;
?>
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<form id="formoid" title="" method="post">
<div>
<label class="title">First Name</label>
<input type="text" id="name" name="name" >
</div>
<div>
<label class="title">Name</label>
<input type="text" id="name2" name="name2" >
</div>
<div>
<input type="submit" id="submitButton" name="submitButton" value="Submit">
</div>
</form>
<script type='text/javascript'>
/* attach a submit handler to the form */
$("#formoid").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
$.ajax({
type: 'POST',
data: id,
url: 'PATH_TO_VIEW.PHP',
success: function(data) {
//do something
},
error: function(data){
console.log('Something went wrong.');
}
});
});
</script>
</body>
</html>
Now the data in ajax can be collected numerous e.g. serialized and new FormData(form) to quickly name two.

How to Preview multiple images before uploading to server?

I have a program to upload multiple images to server. I am trying to preview the selected images before upload So that I could delete the unwanted image if necessary. I am stuck with the previewing part. Please help.
html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Upload Image</title>
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="files[]" id="fileToUpload" onChange="readURL(this)" multiple
accept="image/*" />
<input type="submit" value="Upload Image" name="submit">
<img id="preview2" src="#" alt="your image" width="100" height="100" />
<img id="preview" src="#" alt="your image" width="100" height="100" />
</form>
<script>
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
document.getElementById('preview').src=e.target.result;
}
reader.readAsDataURL(input.files[0]);
}
}
</script>
</body>
</html>
php
<?php
$valid_formats = array("jpg", "png", "gif");
$max_file_size = 1024*720; //100 kb
$path = "gallery/"; // Upload directory
$count = 0;
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST"){
// Loop $_FILES to exeicute all files
foreach ($_FILES['files']['name'] as $f => $name) {
if ($_FILES['files']['error'][$f] == 4) {
continue; // Skip file if any error found
}
else{ // No error found! Move uploaded files
if(move_uploaded_file($_FILES["files"]["tmp_name"][$f], $path.$name))
$count++; // Number of successfully uploaded file
}
}
}
?>
Try some thing similer to this
JS
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript">
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#test').attr('src', e.target.result);
//$("#test").css("display", "block");
$('#test').css({"display":"block","float":"right" });
}
reader.readAsDataURL(input.files[0]);
}
}
</script>
Html
<div style="width:350px;">
<form id="form1" enctype="multipart/form-data">
<input onchange="readURL(this);" type="file" />
<img alt="Image Display Here" id="test" src="#" height="100px" width="100px" />
</form>
</div>
Css
<style>
#test { display:none; }
</style>
Note: TESTED
Js Fiddle Preview
Assuming you do have html input array , so why are you working over id .. even you are passing the reference of element
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$(input).attr(src,e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
Use this code Its working for multiple upload, Download jquery-1.10.2.min.js and replace this path(xxxxx Your path to access JQUERY xxxxxxxxxxx/) to your actual path. (Its working)
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Upload Image</title>
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="files[]" id="fileToUpload" onChange="readURL(this)" multiple
accept="image/*" />
<input type="submit" value="Upload Image" name="submit">
<div class="preview-area"></div>
</form>
<script type="text/javascript" src="xxxxx Your path to access JQUERY xxxxxxxxxxx/jquery-1.10.2.min.js"></script>
<script>
var inputLocalFont = document.getElementById("fileToUpload");
inputLocalFont.addEventListener("change",previewImages,false); //bind the function to the input
function previewImages(){
var fileList = this.files;
var anyWindow = window.URL || window.webkitURL;
for(var i = 0; i < fileList.length; i++){
//get a blob to play with
var objectUrl = anyWindow.createObjectURL(fileList[i]);
// for the next line to work, you need something class="preview-area" in your html
$('.preview-area').append('<img src="' + objectUrl + '" width="100" height="100"/>');
// get rid of the blob
window.URL.revokeObjectURL(fileList[i]);
}
}
</script>
</body>
</html>

Categories

Resources