rename an file on local disk using PHP or Javascript - php

I have a scenario in which user is prompted for selecting a file from local disk (an image). Upon selection, this image is shown in browser (without uploading). After seeing the image user inputs a number in CN No field. Upon submit I want to rename the file on local disk with the number input by user. Is there some way to do this in code using PHP or Javascript?
<html>
<head>
<script type='text/javascript'>
function preview_image(event)
{
var reader = new FileReader();
reader.onload = function()
{
var output = document.getElementById('output_image');
output.src = reader.result;
}
reader.readAsDataURL(event.target.files[0]);
}
</script>
</head>
<body>
<form>
Select File: <input type="file" accept="image/*" onchange="preview_image(event)"> <br>
Enter CN No. <input type="number" id="cnno" name="cnno"> <br>
<input id="sbt" type="submit" name="submit" value="Submit" accesskey="u"> <br>
</form>
<img id="output_image" style="width: 400px"/>
</body>
</html>

You could do this, presuming downloading the file is ok.
<html>
<head>
<script type='text/javascript'>
var img;
function preview_image(elm) {
var reader = new FileReader();
reader.onload = function(event) {
img = event.target.result
document.getElementById("image_preview").src = img;
};
reader.readAsDataURL(elm.files[0]);
}
function download() {
var element = document.createElement('a');
element.setAttribute('href', img)
element.setAttribute('download', document.getElementById("cnno").value+'.png');
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
</script>
</head>
<body>
Select File: <input type="file" accept="image/*" onchange="preview_image(this)"> <br>
Enter CN No. <input type="number" id="cnno" name="cnno"> <br>
<input id="sbt" type="submit" name="submit" value="Submit" accesskey="u" onclick="download()"><br>
<img id="image_preview" style="width: 400px"/>
</body>
</html>

try this:
var file = document.GetElementById('fileupload1');
var blob = file.files[0].slice(0, -1, 'image/png');
newFile = new File([blob], 'name.png', {type: 'image/png'});
But its only for image rename.

Related

how to send data onClick() to another php for processing using post or get?

I want to send data using GET or POST to another php file on a button's(NOT Submit button) onClick() Event.
Please help me.
Let I give you simple HTML with post method using AJAX
Test.php
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
$(function() {
$("#Submit").click(function() {
var value = jQuery("#txt").val();
var data=jQuery('#myform_new').serializeArray();
$.post('test1.php', { myform: data});
return false;
});
});
</script>
</head>
<body>
<form id="myform_new">
<input type="text" name="abc" value="abc" id="txt"/>
<input type="text" name="abc1" value="abc1" id="txt1"/>
<input type="button" name="Submit" id="Submit" value="Submit" />
</form>
</body>
</html>
Test1.php(ajax calling file)
<?php
echo "<pre>";print_r($_POST);
?>
Let i give you some of the ajax posting method
(1)
<script>
$(function() {
$("#Submit").click(function() {
var value = jQuery("#txt").val();
var data=jQuery('#myform_new').serializeArray();
$.post('test1.php', { myform: data});
return false;
});
});
</script>
(2)
<script type="text/javascript"> $(function() { $("#Submit").click(function()
{
var txt = jQuery("#txt").val();
var txt1 = jQuery("#txt").val();
$.post('test1.php', { txt: txt,txt1:txt1 }); return false; }); });
</script>
(3)
<script type="text/javascript"> $(function() { $("#Submit").click(function() {
var txt = jQuery("#txt").val();
var txt1 = jQuery("#txt").val();
$.post('test1.php', { data: "txt="+txt+"&txt1="+txt1}); return false; }); });
</script>
Hello in there i have explain both ajax and get/post method, Please have look below link for get/post method for submit a form in php.
http://www.tutorialspoint.com/php/php_get_post.htm
This below code is used for submit form using ajax
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<form id="formoid" action="studentFormInsert.php" 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();
/* get some values from elements on the page: */
var $form = $( this ),
url = $form.attr( 'action' );
/* Send the data using post */
var posting = $.post( url, { name: $('#name').val(), name2: $('#name2').val() } );
/* Alerts the results */
posting.done(function( data ) {
alert('success');
});
});
</script>
</body>
</html>

Changes to text file with php and ajax-driven form

i have created a simple html form with one field and it post to the server side php and the value of the field is saved to a text file.
This is the parts of the code:
Html:
<form action="videorefresh.php" method="POST">
<input name="videolink" type="text" size="70" />
<input type="submit" name="submit" value="Save Data">
</form>
php:
<?php
$open = fopen("video.txt","w+");
$txt = "video.txt";
if (isset($_POST['videolink'])) { // check if both fields are set
$fh = fopen($txt, 'a');
$txt=$_POST['videolink'];
fwrite($fh,$txt); // Write information to the file
fclose($fh); // Close the file
}
?>
here everythink works fine!
I want to drive all this through Ajax so the main html form wont refresh.
so here is the html:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="./JS/videolink.js"></script>
</head>
<body>
<div id="mainform">
<div id="form">
<div>
<input name="videolink" type="text" id="videolink" size="70">
<input id="submit" type="button" value="Submit">
</div>
</div>
</div>
</body>
</html>
And here is the js:
$(document).ready(function(){
$("#submit").click(function(){
var name = $("#videolink").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'videolink1='+ videolink ;
if(videolink=='')
{
alert("Please Fill All Fields");
}
else
{
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "./videorefresh.php",
data: dataString,
cache: false,
success: function(result){
alert(result);
}
});
}
return false;
});
});
What i do wrong here and it doesnt work?
Please help
I think you want to do is:
var dataString = '?videolink='+ name;//typo videolink
// or better put an id on the form and use serialize()
// var dataString = $('#myform).serialize();
NOT
var dataString = 'videolink1='+ videolink ;
You have the value of the input in name, videolink is undefined

JQuery/PHP multiple files one at a time with only one input field

I search through the net but didn't find much things on my problem. Hope someone here can help!
As i write in the title I want to upload mutliple files, one at a time, with only one input.
I tried to do this using JQuery as you can see below, but obviously it doesn't work!
Anyone can help, please?
<!doctype html>
<html>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<head>
<script>
$(document).ready(function() {
$(document).on('change', '.file',function(){
$('<input type="file" name="file[]" class="file" size="60" />').appendTo($("#divAjout"));
$("div input:first-child").remove();
return false;
});
});
</script>
<title>test input file unique pour plusieurs fichiers</title>
</head>
<body>
<form action="" method="post" enctype='multipart/form-data'>
<div id="divAjout">
<input type="file" name="file[]" class="file" id='file' size="60" />
</div>
<input name="submit" type="submit">
</form>
<?php if(isset($_POST['submit'])){echo'<pre>'; print_r($_FILES);echo'<pre>';} ?>
</body>
</html>
You can clone input file with incrementing name attribute, like file[0], file[1], file[2], etc.
function readURL(input) {
var index = ($(input).data('index'));
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$(input).parent().children('.newImage')
.attr('src', e.target.result)
.height(120);
};
reader.readAsDataURL(input.files[0]);
$('.addPh').show();
$('.addPh').last().clone().insertBefore($('#addPhoto')).hide();
++index;
$('.addPh').last().children('.photo_new').data('index', index).attr('name', 'photo_new['+index+']');
}
}
$(document).ready(function () {
$('#addPhoto').click(function () {
$('.photo_new').last().click();
});
});
See this example: https://jsfiddle.net/w0cd3Ls4/3/

How to preview an image before and after upload?

I am going to preview an image or photo in a form, but it doesn't work and the HTML code looks like this as below:
<form action="" method="post" enctype="multipart/form-data" name="personal_image" id="newHotnessForm">
<p><label for="image">Upload Image:</label>
<input type="file" id="imageUpload"/></p>
<p><button type="submit" class="button">Save</button></p>
<div id="preview">
<img width="160px" height="120px" src="profile pic.jpg" id="thumb" />
</div>
</form>
and incorporated JS code/script below:
<script type="text/jaavascript">
$(document).ready(function(){
var thumb=$('#thumb');
new AjaxUpload('imageUpload',{
action:$('newHotnessForm').attr('action'),
name:'image',
onSubmit:function(file,extension){
$('#preview').addClass('loading');
},
onComplete:function(file,response){
thumb.load(function(){
$('#preview').removeClass('loading');
thumb.unbind();
});
thumb.attr('src',response);
}
});
});
There are 2 main questions on my form:
1. Why doesn't the preview of the image or picture work?
2. How to paste the photo from the form when the save button is clicked, it will go/link to another PHP or PHP page that I created?
Try this: (For Preview)
<script type="text/javascript">
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
</script>
<body>
<form id="form1" runat="server">
<input type="file" onchange="readURL(this);" />
<img id="blah" src="#" alt="your image" />
</form>
</body>
Working Demo here>
meVeekay's answer was good and am just making it more improvised by doing 2 things.
Check whether browser supports HTML5 FileReader() or not.
Allow only image file to be upload by checking its extension.
HTML :
<div id="wrapper">
<input id="fileUpload" type="file" />
<br />
<div id="image-holder"></div>
</div>
jQuery :
$("#fileUpload").on('change', function () {
var imgPath = $(this)[0].value;
var extn = imgPath.substring(imgPath.lastIndexOf('.') + 1).toLowerCase();
if (extn == "gif" || extn == "png" || extn == "jpg" || extn == "jpeg") {
if (typeof (FileReader) != "undefined") {
var image_holder = $("#image-holder");
image_holder.empty();
var reader = new FileReader();
reader.onload = function (e) {
$("<img />", {
"src": e.target.result,
"class": "thumb-image"
}).appendTo(image_holder);
}
image_holder.show();
reader.readAsDataURL($(this)[0].files[0]);
} else {
alert("This browser does not support FileReader.");
}
} else {
alert("Pls select only images");
}
});
On input type=file add an event onchange="preview()"
For the function preview() type:
thumb.src=URL.createObjectURL(event.target.files[0]);
Live example:
function preview() {
thumb.src=URL.createObjectURL(event.target.files[0]);
}
<form>
<input type="file" onchange="preview()">
<img id="thumb" src="" width="150px"/>
</form>
#######################
### the img page ###
#######################
<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="https://malsup.github.com/jquery.form.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#f').live('change' ,function(){
$('#fo').ajaxForm({target: '#d'}).submit();
});
});
</script>
<form id="fo" name="fo" action="nextimg.php" enctype="multipart/form-data" method="post">
<input type="file" name="f" id="f" value="start upload" />
<input type="submit" name="sub" value="upload" />
</form>
<div id="d"></div>
#############################
### the nextimg page ###
#############################
<?php
$name=$_FILES['f']['name'];
$tmp=$_FILES['f']['tmp_name'];
$new=time().$name;
$new="upload/".$new;
move_uploaded_file($tmp,$new);
if($_FILES['f']['error']==0)
{
?>
<h1>PREVIEW</h1><br /><img src="<?php echo $new;?>" width="100" height="100" />
<?php
}
?>
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$('#ImdID').attr('src', e.target.result);
};
reader.readAsDataURL(input.files[0]);
}
}
img {
max-width: 180px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type='file' onchange="readURL(this);" />
<img id="ImdID" src="" alt="Image" />

PHP file-upload using jquery post

Let me know if anyone know what is the issue with this code.
Basically i want to upload a file using jQuery
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function(event) {
$('#form1').submit(function(event) {
event.preventDefault();
$.post('post.php',function(data){
$('#result').html(data);
});
});
});
</script>
</head>
<body>
<form id="form1">
<h3>Please input the XML:</h3>
<input id="file" type="file" name="file" /><br/>
<input id="submit" type="submit" value="Upload File"/>
</form>
<div id="result">call back result will appear here</div>
</body>
</html>
and my php 'post.php'
<?php
echo $file['tmp_name'];
?>
Uploaded File name is not returned back. Issue is i couldn't access the uploaded file.
Thanks in advance!
Shiv
Basically i want to upload a file using jQuery
You cannot upload files using AJAX. You could use the jquery.form plugin which uses a hidden iframe:
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script type="text/javascript">
$(document).ready(function(event) {
$('#form1').ajaxForm(function(data) {
$('#result').html(data);
});
});
</script>
</head>
<body>
<form id="form1" action="post.php" method="post" enctype="multipart/form-data">
<h3>Please input the XML:</h3>
<input id="file" type="file" name="file" /><br/>
<input id="submit" type="submit" value="Upload File"/>
</form>
<div id="result">call back result will appear here</div>
</body>
</html>
Also notice the enctype="multipart/form-data" on the form.
Another possibility is to use the HTML5 File API which allows you to achieve that assuming the client browser supports it.
It's not possible to upload files with jQuery $.post, neverthless, with the file API and XMLHttpRequest, it's perfectly possible to upload a file in AJAX, and you can even know how much data have been uploaded yet…
$('input').change(function()
{
var fileInput = document.querySelector('#file');
var xhr = new XMLHttpRequest();
xhr.open('POST', '/upload/');
xhr.upload.onprogress = function(e)
{
/*
* values that indicate the progression
* e.loaded
* e.total
*/
};
xhr.onload = function()
{
alert('upload complete');
};
// upload success
if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 0))
{
// if your server sends a message on upload sucess,
// get it with xhr.responseText
alert(xhr.responseText);
}
var form = new FormData();
form.append('title', this.files[0].name);
form.append('pict', fileInput.files[0]);
xhr.send(form);
}
No no no, you should use a jQuery form plugin for async uploading files. You can't upload file with jQuery $.post method. The file will be uploaded with hidden iframe
Another way is to use HTML5 uploading with FileAPI/BlobApi
Your upload.php has some error.
you should change your this part.
echo $file['tmp_name'];
to:-
echo $_FILES['file']['tmp_name'];
Try uploading with an iframe because you can't send a file with $.post method.
You could also try jquery uploadify - http://www.uploadify.com/

Categories