Uploading a file with a single button - html

All of the examples I've found so far to upload a file with PHP involve:
Choosing a file
Pressing a submit button to upload it (using post).
Here are a few:
Example 1 Example 2.
Is there a way to simply submit the file immediately after it's been chosen so the user doesn't have to click the "Upload" button? I know this is possible. Look at Dropbox's website, or Google Drive. I'm not sure if they use PHP, though.

You have 2 way :
user jquery :
<form id="frm" action="upload_file.php" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" /><br/>
</form>
<script type="text/javascript">
<!--
$(document).ready(function(){
$('#file').change(function(){
$('#frm').submit();
});
})
-->
</script>
use flash uploader.
i hope help you...

HTML File upload buttons are not scriptable for security reasons.

What you want is the File API that is part of HTML5 http://www.w3.org/TR/FileAPI/ which contains capabilities to upload data via AJAX requests, etc.
unfortunately browser support is still spotty, so while you may be able to implement a drag and drop UI like Dropbox on Chrome or Firefox. You will need to have a fallback for IE.
http://www.html5rocks.com/en/features/file_access

Below code will solve your issue regardless of browser incompatibility. I use this very often.
function startUpload() {
var file_button = document.createElement('input');
file_button.type = "file";
file_button.id = "file_button1";
file_button.style.display = "none";
file_button.style.position = "absolute";
file_button.onchange = function() {
var form_data = new FormData();
var file = jQuery(this).get(0).files[0];
form_data.append('file', file);
form_data.append('type', type);
form_data.append('name', 'fileToUpload');
setTimeout(function() {
jQuery.ajax({
url: "/uploadfile.php",
type: "POST",
cache: false,
contentType: false,
processData: false,
data: form_data,
xhr: function() {
var myXhr = jQuery.ajaxSettings.xhr();
if (myXhr.upload) {
myXhr.upload.addEventListener('progress', custom_progress, false);
}
return myXhr;
},
success: function(response) {
console.log(response);
}
});
}, 1000);
};
jQuery(document.body).append(file_button);
file_button.click();
jQuery("#file_button1").remove();
}
function custom_progress(e) {
if (e.lengthComputable) {
var x = (e.loaded / e.total) * 100;
jQuery("#progress").html(x + "%");
}
}
Your serverside code would look something like this
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file, PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
$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;
}
Found this solution here at Ajax file upload and progress

Related

Some HTML buttons aren't working

I have a small website and it is complete. I am just a senior and it is just for a project on learning how to code. Everything works to perfection on the source computer that it was all coded on. I then exported the files and tried on several other computers. The files open up and everything looks okay, but two out of the five HTML buttons won't work. Is there a common reason why this is happening?
This is the java function for the button
$('#createPassSubmit').click(function() {
var create = true;
var location = $('[name="reason"]').val();
var passnumber = $('#passnumber').val();
var note = $('[name="notes"]').val();
var student = $('#studentID').val();
var teacher = $('#teacherID').val();
var dataString = "CreatePass="+create+"&reason="+location+"&notes="+note+"&studentID="+student+"&teacherID="+teacher+"&passnumber="+passnumber;
$.ajax({
method: 'POST',
url: 'ajax.php',
data: dataString,
success: function(data) {
if(JSON.parse(data) === 'ERROR') {
alert("Pass " + passnumber + " is currently in use");
}
else {
$('#form input[type=text]').val('');
$("#form select").val('')
$('#sname').val('');
}
}
});
});
});
Then this is the HTML button its self
<input type="button" id="createPassSubmit" value="Create">

how to put a text file in a <textarea>

Is there any way to refrence a .txt file with a textarea? what I've tried so far dosen't work I do not want to use php or ajax, just bare html+css+javascript
<textarea rows="16" cols="100" name="textdata" href ="hokuco.com/home/livedoc/user.txt"></textarea><br/>
You can read the file with javascript (see link) and then add it to the textarea.
https://stackoverflow.com/a/14446538/2550732
EDIT:
Javascript:
function readTextFile(file)
{
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var allText = rawFile.responseText;
alert(allText);
}
}
}
rawFile.send(null);
}
Jquery:
$.ajax({
url : "helloworld.txt",
dataType: "text",
success : function (data) {
$(".text").html(data);
}
});
You can use JQuery and try like
$(".text").load("myText.txt");
Check the jQuery.load()

HTML 5 File API - Upload File to Server via JQuery

I have an ASP.NET MVC application. I'm trying to let the user upload files to the server. I need to use the HTML 5 File API. Currently, I have the following code:
<div><input id="filesToUpload" type="file" multiple="multiple" /></div>
<div><input type="button" value="upload" onclick="return uploadFiles();" /></div>
function uploadFiles() {
var files = null; // How do I get the files collection from "filesToUpload" here?
if ((files == null) || (files.length)) {
alert("Please choose at least one file to upload.");
return;
}
for (var i = 0, f; f = files[i]; i++) {
var reader = new FileReader();
reader.readAsBinaryString(f);
uploadFile(reader.result);
}
}
function uploadFile(f) {
// TODO: I'm not sure how to finish my actual AJAX request to post the file back to the server.
$.ajax({
url: "/uploadFile",
type: "PUT",
contentType: "application/json",
success: function (result) {
alert("File Uploaded!");
},
error: function (p1, p2, p3) {
alert("Upload Failed");
}
});
}
As you can see from the code, I have some knowledge gaps that I am trying to fill in.
How do I get the files collection from the "filesToUpload" HTML
element via JQuery? The reason I want this approach is because I do
not want to begin uploading until the user actually clicks the
"upload" button I've shown below.
What do I set as the "data" value in my $.ajax attempt?
What should the contentType be in my $.ajax attempt?
Thank you very much for your help!

upload image from local into tinyMCE

tinyMCE has an insert image button, but how to handle its functionality
pls give some code
I have upvoted the code written by #pavanastechie, but I ended up rewriting it quite a lot. Here's a version that is far shorter, which might have value to some people
tinymce.init({
toolbar : "imageupload",
setup: function(editor) {
var inp = $('<input id="tinymce-uploader" type="file" name="pic" accept="image/*" style="display:none">');
$(editor.getElement()).parent().append(inp);
inp.on("change",function(){
var input = inp.get(0);
var file = input.files[0];
var fr = new FileReader();
fr.onload = function() {
var img = new Image();
img.src = fr.result;
editor.insertContent('<img src="'+img.src+'"/>');
inp.val('');
}
fr.readAsDataURL(file);
});
editor.addButton( 'imageupload', {
text:"IMAGE",
icon: false,
onclick: function(e) {
inp.trigger('click');
}
});
}
});
NOTE: this relies on jquery, and won't work without it. Also, it assumes that the browser supports window.FileReader, and doesn't check for it.
I used pavanastechie's and Chris Lear's solutions, which worked perfectly for me, and wanted to share a complete example built on theirs that uploads the image to the server and embeds the image using the URL provided back by the server:
tinymce.init({
toolbar: 'imageupload',
setup: function(editor) {
initImageUpload(editor);
}
});
function initImageUpload(editor) {
// create input and insert in the DOM
var inp = $('<input id="tinymce-uploader" type="file" name="pic" accept="image/*" style="display:none">');
$(editor.getElement()).parent().append(inp);
// add the image upload button to the editor toolbar
editor.addButton('imageupload', {
text: '',
icon: 'image',
onclick: function(e) { // when toolbar button is clicked, open file select modal
inp.trigger('click');
}
});
// when a file is selected, upload it to the server
inp.on("change", function(e){
uploadFile($(this), editor);
});
}
function uploadFile(inp, editor) {
var input = inp.get(0);
var data = new FormData();
data.append('image[file]', input.files[0]);
$.ajax({
url: '/admin/images',
type: 'POST',
data: data,
processData: false, // Don't process the files
contentType: false, // Set content type to false as jQuery will tell the server its a query string request
success: function(data, textStatus, jqXHR) {
editor.insertContent('<img class="content-img" src="' + data.url + '"/>');
},
error: function(jqXHR, textStatus, errorThrown) {
if(jqXHR.responseText) {
errors = JSON.parse(jqXHR.responseText).errors
alert('Error uploading image: ' + errors.join(", ") + '. Make sure the file is an image and has extension jpg/jpeg/png.');
}
}
});
}
!!!!ENJOY!!! here is the solution to load directly from local computer
JSFIDDLE DEMO
<textarea name="content"></textarea>
<title>Local image loading in to tinymce</title>
<br/>
<b>Image size should be lessthan 500kb</b>
JAVA SCRIPT CODE
`
tinymce.init({
selector: "textarea",
toolbar: "mybutton",
setup: function(editor) {
editor.addButton('mybutton', {
text:"IMAGE",
icon: false,
onclick: function(e) {
console.log($(e.target));
if($(e.target).prop("tagName") == 'BUTTON'){
console.log($(e.target).parent().parent().find('input').attr('id'));
if($(e.target).parent().parent().find('input').attr('id') != 'tinymce-uploader') {
$(e.target).parent().parent().append('<input id="tinymce-uploader" type="file" name="pic" accept="image/*" style="display:none">');
}
$('#tinymce-uploader').trigger('click');
$('#tinymce-uploader').change(function(){
var input, file, fr, img;
if (typeof window.FileReader !== 'function') {
write("The file API isn't supported on this browser yet.");
return;
}
input = document.getElementById('tinymce-uploader');
if (!input) {
write("Um, couldn't find the imgfile element.");
} else if (!input.files) {
write("This browser doesn't seem to support the `files` property of file inputs.");
} else if (!input.files[0]) {
write("Please select a file before clicking 'Load'");
} else {
file = input.files[0];
fr = new FileReader();
fr.onload = createImage;
fr.readAsDataURL(file);
}
function createImage() {
img = new Image();
img.src = fr.result;
editor.insertContent('<img src="'+img.src+'"/>');
}
});
}
if($(e.target).prop("tagName") == 'DIV'){
if($(e.target).parent().find('input').attr('id') != 'tinymce-uploader') {
console.log($(e.target).parent().find('input').attr('id'));
$(e.target).parent().append('<input id="tinymce-uploader" type="file" name="pic" accept="image/*" style="display:none">');
}
$('#tinymce-uploader').trigger('click');
$('#tinymce-uploader').change(function(){
var input, file, fr, img;
if (typeof window.FileReader !== 'function') {
write("The file API isn't supported on this browser yet.");
return;
}
input = document.getElementById('tinymce-uploader');
if (!input) {
write("Um, couldn't find the imgfile element.");
} else if (!input.files) {
write("This browser doesn't seem to support the `files` property of file inputs.");
} else if (!input.files[0]) {
write("Please select a file before clicking 'Load'");
} else {
file = input.files[0];
fr = new FileReader();
fr.onload = createImage;
fr.readAsDataURL(file);
}
function createImage() {
img = new Image();
img.src = fr.result;
editor.insertContent('<img src="'+img.src+'"/>');
}
});
}
if($(e.target).prop("tagName") == 'I'){
console.log($(e.target).parent().parent().parent().find('input').attr('id')); if($(e.target).parent().parent().parent().find('input').attr('id') != 'tinymce-uploader') { $(e.target).parent().parent().parent().append('<input id="tinymce-uploader" type="file" name="pic" accept="image/*" style="display:none">');
}
$('#tinymce-uploader').trigger('click');
$('#tinymce-uploader').change(function(){
var input, file, fr, img;
if (typeof window.FileReader !== 'function') {
write("The file API isn't supported on this browser yet.");
return;
}
input = document.getElementById('tinymce-uploader');
if (!input) {
write("Um, couldn't find the imgfile element.");
} else if (!input.files) {
write("This browser doesn't seem to support the `files` property of file inputs.");
} else if (!input.files[0]) {
write("Please select a file before clicking 'Load'");
} else {
file = input.files[0];
fr = new FileReader();
fr.onload = createImage;
fr.readAsDataURL(file);
}
function createImage() {
img = new Image();
img.src = fr.result;
editor.insertContent('<img src="'+img.src+'"/>');
}
});
}
}
});
}
});
`
Din't try iManager but found tinyFCK good and easy to configure which gives CKEditor's filemanager integrated with TinyMCE
1.Download TinyFCK
2.replace filemanger folder in tinyFCK with filemanager folder of ur CKEditor
3.code :
-
tinyMCE.init({
theme : "advanced",
file_browser_callback : "fileBrowserCallBack",
});
function fileBrowserCallBack(field_name, url, type, win) {
var connector = "../../filemanager/browser.html?Connector=connectors/php/connector.php";
var enableAutoTypeSelection = true;
var cType;
tinyfck_field = field_name;
tinyfck = win;
switch (type) {
case "image":
cType = "Image";
break;
case "flash":
cType = "Flash";
break;
case "file":
cType = "File";
break;
}
if (enableAutoTypeSelection && cType) {
connector += "?Type=" + cType;
}
window.open(connector, "tinyfck", "modal,width=600,height=400");
}
I know this post is old, but maybe this will help someone trying to find a open source file manager for tinymce:
https://github.com/2b3ez/FileManager4TinyMCE
This worked great for me.
Based on #Chris Lear's answer, I have re-modified the script so that it supports multiple file uploads to server, and removed the data image for preview after content is posted and before table is updated with a little php script
tinymce.init({
selector: 'textarea',
setup: function(editor) {
var n = 0;
var form = $('#form_id'); // your form id
editor.addButton( 'imageupload', {
text:"IMAGE",
icon: false,
onclick: function(e) {
$(form).append('<input id="tinymce-uploader_'+n+'" class="tinymce-uploader" type="file" name="pic['+n+']" mutliple accept="image/*" style="display: none;">');
$('#tinymce-uploader_'+n).trigger('click');
n++;
$('.tinymce-uploader').on("change",function(){
var input = $(this).get(0);
var file = input.files[0];
var filename = file.name;
var fr = new FileReader();
fr.onload = function() {
var img = new Image();
img.src = fr.result;
editor.insertContent('<img data-name="'+filename+'" src="'+img.src+'"/>');
}
fr.readAsDataURL(file);
});
}
});
},
And on php side inside the upload php file:
function data2src($content, $img_path ='') {
preg_match('/data\-name="([^"]+)/i',$content, $data_name);
$tmp = preg_replace('/src=["]data([^"]+)["]/i', '', $content);
$content = preg_replace('/data\-name\=\"/i', 'src="'.$img_path, $tmp);
return $content;
}
I know it is an old question. However, I think this answer may help somebody who wants to upload multiple images by using tinyMCE 5.xx.
Based on #Chris Lear's and #stephen.hanson's answer, I modify some code to support multiple images uploading. Here is my code. Hope it could help somebody.
tinymce.init({
toolbar: 'imageupload',
setup: function(editor) {
initImageUpload(editor);
}
});
function initImageUpload(editor) {
// create input and insert in the DOM
var inp = $(`<input id='tinymce-uploader' type='file' name='pic' accept='image/*' style='display:none' multiple>`);
$(editor.getElement()).parent().append(inp);
// add the image upload button to the editor toolbar
editor.addButton('imageupload', {
text:'IMAGE',
onAction: function(_) {
// when toolbar button is clicked, open file select modal
inp.trigger('click');
}
});
// when a file is selected, upload it to the server
inp.on('change',function(){
for(let i=0;i<inp[0].files.length;i++){
let file = inp[0].files[i];
let data = new FormData();
data.append('multipartFile',file);
axios.post('/upload/image/url',
data,
{
headers: {
'Content-Type': 'multipart/form-data'
}
}).then(res => {
if (res.status = 200) {
editor.insertContent('<img class="content-img" src="' + data.url + '"/>');
// clear data to avoid uploading same data not working in the second time
inp.val('');
}
})
}
It works for image upload.Is this possible for file upload ? I want to add a custom file upload option from local into tinyMCE and want to show it by url .
Code is something like below which not working:
ed.addButton('mybutton2', {
text:"File",
icon: false,
onclick: function(e) {
console.log($(e.target));
if($(e.target).prop("tagName") == 'BUTTON'){
console.log($(e.target).parent().parent().find('input').attr('id'));
if($(e.target).parent().parent().find('input').attr('id') !=
'tinymce-uploader') {
$(e.target).parent().parent().append('<input id="tinymce-
uploader" type="file" name="pic" accept="*" height="100" weidth="100"
style="display:none">');
}
$('#tinymce-uploader').trigger('click');
$('#tinymce-uploader').change(function(){
var input, file, fr, img;
if (typeof window.FileReader !== 'function') {
write("The file API isn't supported on this browser yet.");
return;
}
input = document.getElementById('tinymce-uploader');
// var URL = document.my_form.my_field.value;
alert(input.files[0]);
if (!input) {
write("Um, couldn't find the imgfile element.");
} else if (!input.files) {
write("This browser doesn't seem to support the `files`
property of file inputs.");
} else if (!input.files[0]) {
write("Please select a file before clicking 'Load'");
alert( input.files[0]);
} else {
file = input.files[0];
fr = new FileReader();
fr.onload = createFile;
fr.readAsDataURL(file);
// alert(fr.result);
}
function createFile() {
//what should I write here?
ed.insertContent('<a href="'+img.src+'">download
file_name</a>');
}
});
}
}
});

how to preview an image before upload in various browsers

I want to show preview of an image before it is uploaded. I have found a partial solution that works for ie6 and firefox, and havent yet tested it in ie7 or ie8. But i want a solution that works in safari, ie7 and ie8 as well. Here is the solution obtained by combining the ie6 and firefox solution:
function preview(what) {
if(jQuery.browser.msie) {
document.getElementById("preview-photo").src=what.value;
return;
}
else if(jQuery.browser.safari) {
document.getElementById("preview-photo").src=what.value;
return;
}
document.getElementById("preview-photo").src=what.files[0].getAsDataURL();
// alert(jQuery("#preview-photo").height());
// alert(jQuery("#preview-photo").width());
var h = jQuery("#preview-photo").height();
var w = jQuery("#preview-photo").width();//assuming width is 68, and height is floating
if ((h > 68) || (w > 68)){
if (h > w){
jQuery("#preview-photo").css("height", "68px");
jQuery("#preview-photo").css("width", "auto");
}else {
jQuery("#preview-photo").css("width", "68px");
jQuery("#preview-photo").css("height", "auto");
}
}
}
The getAsDataURL() part works in firefox, and the "src=what.value" part works in ie6, but what would work in safari, and does "src=what.value" work in ie7 and ie8 as well? If not, is there some solution that also works there? I will be happy if i can make the image preview work in 5 or 6 browsers. If it doesn't then is the only option to have two forms with image upload part of another form?
You can use the following function. Tested on IE7+ and Firefox and chrome
function loadname(img, previewName){
var isIE = (navigator.appName=="Microsoft Internet Explorer");
var path = img.value;
var ext = path.substring(path.lastIndexOf('.') + 1).toLowerCase();
if(ext == "gif" || ext == "jpeg" || ext == "jpg" || ext == "png" )
{
if(isIE) {
$('#'+ previewName).attr('src', path);
}else{
if (img.files[0])
{
var reader = new FileReader();
reader.onload = function (e) {
$('#'+ previewName).attr('src', e.target.result);
}
reader.readAsDataURL(img.files[0]);
}
}
}else{
incorrect file type
}
}
<input type="file" name="image" onchange("loadname(this,'previewimg')") >
<img src="about:blank" name="previewimg" id="previewimg" alt="">
Work in firefox and chrome
<input type="file" id="file" />
<div id="div"></div>
<script type="text/javascript">
function view() {
var f = document.getElementById("file").files[0];
var reader = new FileReader();
reader.onload = (function(evt) { //evt get all value
document.getElementById('div').innerHTML =
"PIC :<img src=" +
evt.target.result + "/>" ;
});
reader.readAsDataURL(f);
}
</script>
This will be a serious security issue if done. You can't have a preview of a file in the users computer. You have to upload the file to the server and can show the preview of the file after it is successfully uploaded.
Link to the blob as you would link to any image, of course you have to update the src as soon as the images soon to be uploaded is given or changed, here is how I do it, I didn't have the time to test it in Windows Browsers (i.e IE).
This example also implements basic validation:
http://jsfiddle.net/J3GP7/
<style>
#image_preview {
display:none;
}
</style>
<form>
<p>
<label for="image">Image:</label><br />
<input type="file" name="image" id="image" />
</p>
</form>
<div id="image_preview">
<img src="#" /><br />
Remove
</div>
<script>
/**
onchange event handler for the file input field.
* It emplements very basic validation using the file extension.
* If the filename passes validation it will show the image
using it's blob URL and will hide the input field and show a delete
button to allow the user to remove the image
*/
jQuery('#image').on('change', function () {
ext = jQuery(this).val().split('.').pop().toLowerCase();
if (jQuery.inArray(ext, ['gif', 'png', 'jpg', 'jpeg']) == -1) {
resetFormElement(jQuery(this));
window.alert('Not an image!');
} else {
file = jQuery('#image').prop("files")[0];
blobURL = window.URL.createObjectURL(file);
jQuery('#image_preview img').attr('src', blobURL);
jQuery('#image_preview').slideDown();
jQuery(this).slideUp();
}
});
/**
onclick event handler for the delete button.
It removes the image, clears and unhides the file input field.
*/
jQuery('#image_preview a').bind('click', function () {
resetFormElement(jQuery('#image'));
jQuery('#image').slideDown();
jQuery(this).parent().slideUp();
return false;
});
/**
* Reset form element
*
* #param e jQuery object
*/
function resetFormElement(e) {
e.wrap('<form>').closest('form').get(0).reset();
e.unwrap();
}
</script>
jquery ajax file upload
$('[name="send"]').click(function(){
view();
v_data = {
news_header : $('[name="news_header"]').val(),
news_auth : $('[name="news_auth"]').val(),
news_image : image, //this var taking for view() function what i use before
news_news : $('[name="news_news"]').val()
};
$("#show").html(v_data.news_Header + " " + v_data.news_auth + " "+ v_data.news_image + " "+ v_data.news_news );
$.ajax({
type : "POST",
url : './insert_news_data.php',
enctype: 'multipart/form-data',
data : v_data,
success: function(data) {
alert(data);
}
});
});