Getting file out of url with php - php

So I give my users the possibility to upload a xml file of their iTunes playlist. Once they've uploaded their xml-file, i need to read out that xml file. I tried it first with just an ajax call and a local xml file and it worked fine, but now i need to get acces to the uploaded xml file.
This is my upload form
<form id="formulier" action="playlist.php" method="post" enctype="multipart/form-data">
<fieldset>
<legend>Upload your playlist</legend>
</br>
<label>
<input type="file" name="bestand">
</label>
</br>
</br>
<input type="submit" value="Generate">
</fieldset>
this is my playlist.php file:
<?php
$path = "playlists/" . ($_FILES['bestand']['name']);
if(move_uploaded_file($_FILES['bestand']['tmp_name'], $path)){
}
header("Location:index.html?url=".$path);
?>
this is my ajax call that i previously used:
var my_fn = function(callback) { // <-- this is callback to be called later
var jax = [];
$.ajax({
url: "",
dataType: "xml",
success: function (data) {
var song = $(data).find('key').filter(function () {
return $(this).text().indexOf('Name') != -1;
}).each(function() {
var content = $(this).next('string').text();
jax.push(content);
});
callback(jax);
}
});
};
How do I get to read out the xml file that is uploaded by the user? I really do not have a clue...

Related

HTML prevent from redirect upload php

I need to prevent the page redirected to the upload php when click upload button.
How can I do this in below code.
<form id="myForm" action="http://example/DB_1/AccessWeb/file_upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload1">
</form>
<button onclick="myFunction()"> Upload
</button>
<script>
function myFunction(){
document.getElementById("myForm").submit();
}
</script>
A very basic, quickly written example of how to send a file - using ajax to the same page so that the user doesn't get redirected. This is plain vanilla javascript rather than jQuery.
The callback function can do more than print the response - it could, for instance, be used to update the DOM with new content based upon the success/failure of the upload.
<?php
$field='fileToUpload';
if( $_SERVER['REQUEST_METHOD']=='POST' && !empty( $_FILES ) ){
$obj=(object)$_FILES[ $field ];
$name=$obj->name;
$tmp=$obj->tmp_name;
$size=$obj->size;
$error=$obj->error;
$type=$obj->type;
if( $error==UPLOAD_ERR_OK ){
/*
This is where you would process the uploaded file
with various tests to ensure the file is OK before
saving to disk.
What you send back to the user is up to you - it could
be json,text,html etc etc but here the ajax callback
function simply receives the name of the file chosen.
*/
echo $name;
} else {
echo "bad foo!";
}
exit();
}
?>
<!doctype html>
<html>
<head>
<title>File Upload - using ajax</title>
<script>
document.addEventListener('DOMContentLoaded',function(e){
var bttn=document.getElementById('bttn');
bttn.onclick=function(e){
/* Assign a new FormData object using the buttons parent ( the form ) as the argument */
var data=new FormData( e.target.parentNode );
var xhr=new XMLHttpRequest();
xhr.onload=function(e){
document.getElementById('status').innerHTML=this.response;
}
xhr.onerror=function(e){
alert(e);
}
xhr.open('POST',location.href,true);
xhr.send(data);
};
},false);
</script>
</head>
<body>
<form method='post' enctype='multipart/form-data'>
Select image to upload:
<input type='file' name='fileToUpload'>
<input type='button' id='bttn' value='Upload' />
</form><div id='status'></div>
</body>
</html>
Using JQuery AJAX methods will allow you to send and receive information to a specified url without the need to refresh your page.
You will need to include the JQuery library in your HTML page aswell. You can either download it and put it in your project folder or include an online library here, like so:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
So your form will now look like this:
<form id="myForm" method="post" >
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload1">
<input type="submit">
</form>
Then you can use this code to simply upload your image to your file upload page (tested and working for myself):
<script>
$(document).ready(function ()
{
$("#myForm").submit(function (e)
{
//Stops submit button from refreshing page.
e.preventDefault();
var form_data = new FormData(this);
$.ajax({
url: 'http://example/DB_1/AccessWeb/file_upload.php', //location of where you want to send image
dataType: 'json', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function (response)
{
alert('success');
},
error: function ()
{
alert('failure');
}
});
});
});
</script>
use AJAX With jQuery
$("#myForm").submit(function()
{
var formData = new FormData(this);
$.post($(this).attr("action"), formData, function(response) {
//Handle the response here
});
return false;
});

posting text file thru jQuery ajax in php and download the response file

Requirement:
I have to submit a form in a PHP file which has a file type input. I need jQuery ajax to post this text file to lets say processFile.php
processFile.php will take this text file as input and after processing will return a csv file which I want to download at the client.
I have seen many posts but nothing is helping me out.
HTML:
<form id="utilityForm" class="utilityForm4" method="POST" enctype="multipart/form-data" style="margin-top:25px">
<input type="file" name="image" id="image"/>
<br/><input type="submit" name="download" class="submit" value="Submit"/>
</form>
jQuery:
$(document).ready(function(){
$(".submit").click(function(e){
var urlstring = "processFile.php"
var form_data = new FormData($(this)[0]);
$.ajax({
url : urlstring,
type: "POST",
data : postData,
success:function(result){
var uri = 'data:application/csv;charset=UTF-8,' + encodeURIComponent(result);
window.open(uri, 'result.csv');
},
error: function(jqXHR, textStatus, errorThrown)
{
alert('failed');
echo (errorThrown);
}
});
});
});
I have tried hundreds of solutions given on the net but none is working.
Here I am providing complete working example:
HTML File:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function (e) {
$("#uploadimage").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "ajax_php_file.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function(result) // A function to be called if request succeeds
{
e.preventDefault(); //stop the browser from following
window.location.href = 'upload/'+result;
}
});
}));
// Function to preview image after validation
});
</script>
</head>
<body>
<form id="uploadimage" action="" method="post" enctype="multipart/form-data">
Download
<input type="file" name="file" id="file" required />
<input type="submit" value="Upload" class="submit" />
</form>
</body>
PHP File:
<?php
if(isset($_FILES["file"]["type"]))
{
$temporary = explode(".", $_FILES["file"]["name"]);
$file_extension = end($temporary);
if (file_exists("upload/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " <span id='invalid'><b>already exists.</b></span> ";
}
else
{
$sourcePath = $_FILES['file']['tmp_name']; // Storing source path of the file in a variable
$targetPath = "upload/".$_FILES['file']['name']; // Target path where file is to be stored
move_uploaded_file($sourcePath,$targetPath) ; // Moving Uploaded file
echo $_FILES["file"]["name"];
}
}
else
{
echo "<span id='invalid'>***Invalid file Size or Type***<span>";
}
?>
Try to upload any file.
Is this useful for you?

Ajax large-ish file upload with FormData and jQuery fails to post the data

I am trying to upload files via AJAX using FormData. If I submit the AJAX call without selecting any files to upload, the post works fine, and other fields (that are not file uploads) are received on the server OK. If I select a file to upload though, the call arrives at the server with no data whatsoever (in PHP, the $_POST and $_FILES arrays are both completely empty). I understand this can happen if you fail to tell jQuery not to set the contentType, but I am setting contentType and processData to false and it still won't send the data.
Here is my code:
function AddComment(taskid) {
var newnote = $('#newnote_'+taskid).val();
if(newnote != '') {
$('#tasklist *').css('cursor', 'progress');
var formData = new FormData();
$('.upload-' + taskid).each(function() {
if (this.files[0]) {
formData.append($(this).attr('name'), this.files[0]);
}
});
formData.append("taskid", taskid);
formData.append("newnote", newnote);
$.ajax({
url: '/modules/task/ajax/ajaxAddComment.php',
data: formData,
processData: false,
contentType: false,
type: 'post',
success: function(data){
alert(data);
}
});
}
}
I'm sure I'm doing something stupid, but I can't see what...?
Edit: Here is the HTML:
<form id="frmNewComment544" enctype="multipart/form-data" method="post" action="">
<div>
<textarea style="width:100%;" cols="30" rows="5" id="newnote_544"></textarea>
</div>
<div>
<input type="button" onclick="AddComment(544)" value="Append Comment">
</div>
<div class="attachment-browsers" id="attachmentBrowsers544" style="display: block;">Attachments will be uploaded when you append a comment.
<div>
<input type="file" id="upload_544_151ab3cfe69" name="upload_544_151ab3cfe69" class="upload-544">
</div>
<div>
<input type="file" id="upload_544_3y4afe6eg7a" name="upload_544_3y4afe6eg7a" class="upload-544">
</div>
</div>
</form>
Edit 2: OK, the problem only occurs when uploading relatively large files (not massive - in this case it was 10MB). Small files upload OK. So now the question is why I cannot upload large files using this method?
I knew it would be something stupid!
My php.ini had the default 2MB limit for file uploads. D'oh.
I don't see any reference to your form.
May be you would do it like this:
.....
var form = $('form#frmNewComment544');
var formdata = false;
if (window.FormData){
formdata = new FormData(form[0]);
}
var formAction = form.attr('action');
$.ajax({
url: formAction,
data : formdata ? formdata : form.serialize(),
....

jQuery Fileupload and writing filename do MySQL database

I'm trying to create a file uploader with jQuery, that uploads a file, renames it with a timestamp and registers it into a DB. Basically it it sends the file with a form to the server where a second script renames it and moves the file to the right directory. This works without any problem. The problem is, that I want to send also the table name where this DB Entry should be made.
So index.php contains the form:
<div id="uploaderMain">
<p>Upload Your Files</p>
<form method="post" enctype="multipart/form-data" action="./upload.php">
<input type="file" name="images" id="images" />
<input type="hidden" name="List" id="List" value="<?php echo $DBTable; ?>" />
<button type="submit" id="btn">Upload Files!</button>
</form>
<div id="response"></div>
<ul id="image-list">
</ul>
</div>
The jQuery Code looks like this:
$.ajax({
url: "./uploader/upload.php",
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function (res) {
document.getElementById("response").innerHTML = res;
}
});
The upload.php looks like this:
<?php
//include db configuration file
include_once('../../db.php');
$List = $_POST['List'];
// get the time stamp for the uploaded file
date_default_timezone_set('EST');
$date = new DateTime();
$date = $date->getTimestamp();
// echo $date;
foreach ($_FILES["images"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$name = $_FILES["images"]["name"][$key];
// store the file name and the file ending in 2 variables
$fileEnding = substr($name, -4,4);
$fileName = substr($name, 0, (strlen($name)-4));
$uploadName = $fileName."_".$date.$fileEnding;
move_uploaded_file( $_FILES["images"]["tmp_name"][$key], "./uploads/" . $uploadName);
}
}
after that I want to write to the DB. The problem is, that the $_POST['LIST'] statement doesn't provide my DBTable-name.
Can anyone give me a hint?
Cheers
Dan
I think you need to add this to your jQuery code:
formdata.append('List', '[your value]');
Please note: in PHP everything that is a file will go into $_FILES. Everything else will go into $_POST.
If this does not work, make sure you also have the following code:
var formdata = new FormData();
jQuery.each($('input[type="file"]')[0].files, function(i, file) {
formdata.append(i, file);
});
Can you check the source from browser if the List control has any value.

Uploading image via AJAX along with username and email address

I am having some trouble with my file upload script. The HTML is as follows:
<form method="post" name="imgsubmit" id="contact_form" action="PHP/imgupload.php" enctype="multipart/form-data">
<label id="namelabel" for="username">Your name:</label><input id="username" type="text" name="username" rel="req">
<label id="labelemail" for="imgemail">E-mail:</label><input id="imgemail" type="email" name="imgemail" rel="req">
<label id="filelabel" for="file">Your photo:</label><input id="file" type="file" name="file">
<input id="imgsubmit" type="submit" name="submit" value="SUBMIT"></form>
I have a jquery validation script as which checks the username and email fields to see if they are valid, and returns a white border around them if they are not entered:
$(function () {
$('#contact_form').submit(function (e) {
e.preventDefault();
var form = $('#contact_form');
var post_url = form.attr('action');
var post_data = form.serialize();
var submit_form = false;
var req_fields = $('input[rel=req]');
var field, pcount = 0;
req_fields.each(function () {
field = $(this).val();
if (field == '' || field == 'Required') {
$(this).css('border', '1px solid white').val('');
pcount += 1;
} else {}
});
if (pcount == 0) {
submit_form = true;
}
if (submit_form) {
$.ajax({
type: 'POST',
url: post_url,
data: post_data,
success: function (msg) {
$(form).fadeOut;
form.html(msg).fadeIn();
}
});
}
});
});
The problem is that the username gets submitted to the php script, the email gets submitted to the php script, but the image doesn't get uploaded. I'm aware that AJAX now supports image uploading and that the form.serialize() is likely the root cause of the problem, but have not been able to edit this code correctly to support the image submission.
How can I adjust this code to include the image to be submitted to the php?
`if (window.FormData)`
check this and file must be `
file = $('#elemet').files.
and ajax option should be data: FormData,
where formdata = new FormData();
I like to use the jQuery Form Plugin for this kind of stuff, you just need to bind your form submittal when the DOM is ready for it to work. The example bellow is providing a success callback, but there are other events you could use, like error, beforeSubmit, and so forth:
$('#contact_form').ajaxForm(function() {
alert("Thank you for your data!");
});
It supports both regular input values and also file uploads (in older browsers it will fake an ajax file upload using iframes), and if your browser can handle it you can even display a progress bar.

Categories