jQuery-File-Upload
Upload script:
$('#fileupload').fileupload({
url: 'api/combox_upload.php',
type: 'POST',
dataType: 'json',
dropZone: $dropZone,
singleFileUploads: true,
done: function (e, data) {
attachments = attachments.concat(data.result);
refreshAttachments();
},
add: function(e, data) {
var file = data.files[0];
data.context =
$('<li>',{'class':'file-upload-item'})
.append($('<span>').text(file.name))
.append(
$('<div>',{'class':'progressbar'})
.append($('<div>',{'class':'progress'}))
).appendTo($fileUploads);
data.submit(); // start upload immediately
},
progress: function(e, data) {
var progress = data.loaded / data.total;
data.context.find('.progress').stop().animate({'width':(progress*100)+'%'},100,'linear');
//data.context.find('.progress').css({'width':(progress*100)+'%'});
}
});
In my api/combox_upload.php script I echo json_encode($_FILES) and half the time it comes back blank (I'm watching the XHR request responses in Chrome developer toolbar).
Why is that? How do I fix it so it always submits the file?
Edit: It seems to happen more frequently with larger files.
Could it be an issue with PHP not handling multipart data correctly? I noticed the XHR request comes in immediately, as soon as the file upload begins, but PHP obviously hasn't gotten the whole file yet... so what does it do? Does it block when I try to access the $_FILES object or does it just give me an empty array? Do I have to something special?
Through trial and error I discovered that this problem only occurs with files larger than about 23 MiB. I'm not sure if that's a universal constant or specific to how my server is configured.
Nevertheless, I figured out how to get around this limitation. You need to set singleFileUploads to true and multipart to false, e.g.
$('#fileupload').fileupload({
url: 'api/upload.php',
type: 'POST',
dataType: 'json',
singleFileUploads: true,
multipart: false,
...
And then in your php script you can read in the data like this:
$handle = fopen('php://input', 'r');
$file_data = '';
while(($buffer = fgets($handle, 4096)) !== false) {
$file_data .= $buffer;
}
fclose($handle);
The $_FILES array will still be empty, so you can't get the filename out of there, but it seems to be set in the Content-Disposition header. I wrote a regex to pull it out:
$headers = getallheaders();
$filesize = strlen($file_data);
if(isset($headers['Content-Disposition']) && preg_match('`\bfilename="((?:\\.|[^"])*)"`',$headers['Content-Disposition'], $m)) {
$filename = urldecode($m[1]);
} else {
$filename = 'unknown';
}
Related
First of all, I have already read this answer, which is to do the Cross-Domain Ajax GET request with php proxy. But what I need is a Ajax POST request.
So in my project, long time ago. Someone wrote this php file and together the ajax call in JavaScript, those are mean to solve the cross origin problem and which works really good! So I never think about to understand this, because I basiclly just need to change the url in the JavaScript and don't need to understand how this Ajax call works together with php.
PHP:
<?php
$nix="";
$type=$_GET['requrl'];
if ($_GET['requrl'] != $nix) {
$file = file_get_contents($_GET['requrl']);
}
elseif ($_POST['requrl'] != $nix) {
$file = file_get_contents($_POST['requrl'], false, $_POST['data']);
}
else {
$file = "false type";
}
echo $file;
?>
JavaScript:
var url = "https://XXXXXXXXXXXXXX";
url = encodeURI(url);
var useProxyPhp = true;
var data = (useProxyPhp) ? {requrl: url} : "";
var ajaxUrl = (useProxyPhp) ? "proxy.php" : url;
var ajaxProperties = {
type: 'GET',
data: data,
url: ajaxUrl,
cache: false
};
res = jQuery.ajax(ajaxProperties).done(function(res) {
// do something with the result here
})
So what I need to do is just take the same ajax GET request (copy and paste in JS) and just replace the url every time ==> job done!
Now, the first time I need to do a ajax POST request to send a xml file to the server, the server will do some calculate on it and give me a response.
I tested first with the POSTMAN and everything works fine, but when I switch to my real project. I become the Cross origin problem. So I think If I could do something to the already existing php and js, so I can solve the cross origin problem.
I tried this in my JavaScript but I got only the "false type" as antwort
function sendWPSRequest(xml) {
var url = "https://XXX.XXX.XXX.XXX:XXXX/wps";
useProxyPhp = true;
var data = (useProxyPhp) ? {requrl: url, data: xml} : "";
var ajaxUrl = (useProxyPhp) ? "proxy.php" : url;
$.ajax({
type: "POST",
url: ajaxUrl,
dataType: "text",
contentType: "application/xml",
data: data,
success:function (response) {
console.log('POST success: ', response);
},
error: function (jqXHR, textStatus, errorThrown) {
alert("POST", textStatus, errorThrown);
}
});
}
Can someone help me a little bit to understand what the php is doing here and what should I do to modify the php and JS.
I am trying to implement Dropzone JS to help with uploading files to the server. I'm using a generic implementation of Dropzone on the client side with my html looking like this:
<form id='portfolioupload' action='PortfolioUpload.php' class='dropzone'>
<div class='fallback'>
<input name='file' type='file' />
</div>
</form>
In the server, I do some checks and, in the end, I rename the file and move it into it's final place:
$newname = substr(GetGUID(false), -7) . '.' . $ext;
move_uploaded_file($_FILES['file']['tmp_name'], PortfolioPath() . $newname)
I pass this information back using json, as suggested in Dropzone.js- How to delete files from server?:
header_status(200); // output header, error 200
echo json_encode(array("Filename" => $newname));
The code sample there looks like it adds it to an array that can be passed to the server for deletion. So close, but not quite what I'm looking for.
I then stumble on the question, how to upload and delete files from dropzone.js, and see that I can listen to the removedfile event. So I implement the code there like so:
Dropzone.options.portfolioupload = {
acceptedFiles: '.png, .jpg, .gif',
addRemoveLinks: true,
maxFiles: 25,
maxFilesize: 500000,
removedfile: function(file) {
alert('Deleting ' + file.name);
var name = file;
$.ajax({
type: 'POST',
url: 'app/assets/PortfolioUpload.php',
data: "f=delete&fn="+name,
dataType: 'html'
});
var _ref;
return (_ref = file.previewElement) != null ? _ref.parentNode.removeChild(file.previewElement) : void 0;
}
};
The request is sent to the server successfully except that the filename is that of the original, not the server's renamed filename.
After scouring the net today I feel like I can't figure out how to tie the two items together. For example, if I uploaded foo.jpg and rename it in the server to dk03p7b.jpg, how do I tell Dropzone that foo.jpg = dk03p7b.jpg so that when the user clicks Remove file, it's also removed in the server?
I solved this myself by, first, taking the json from the success response and saving it to the element file.previewElement.id like this:
success: function( file, response ) {
obj = JSON.parse(response);
file.previewElement.id = obj.filename;
}
Then I use that value when doing the delete ajax call in the removedfile event:
removedfile: function(file) {
var name = file.previewElement.id;
$.ajax({
type: 'POST',
url: 'deletefile.php',
data: "fn="+name,
dataType: 'html'
});
var _ref;
return (_ref = file.previewElement) != null ? _ref.parentNode.removeChild(file.previewElement) : void 0;
},
This also worked for me
// "myAwesomeDropzone" is the camelized version of the HTML element's ID
var myDropzone = new Dropzone("#myAwesomeDropzone", {
/*
* This step isn't required.
success: function(file, response) {
file.previewElement.id = response.id;
}
*/
});
myDropzone.on('removedfile', function(file) {
var id = jQuery(file.previewElement).find('.dz-filename span').html();
// directly access the removing preview element and get image name to delete it from server.
// var id = file.previewElement.id;
$.ajax({
type: 'POST',
url: '<?php echo base_url('seller/deleteImagegalleryById'); ?>',
data: {id: id, '<?php echo $this->security->get_csrf_token_name(); ?>': '<?php echo $this->security->get_csrf_hash(); ?>'},
dataType: 'html'
});
var _ref;
return (_ref = file.previewElement) != null ? _ref.parentNode.removeChild(file.previewElement) : void 0;
});
I have looked into the best way to do this and keep getting conflicting information and advice on the various demonstrations.
My code is as follows...
html
<img src="http://www.gravatar.com/avatar/205e460b479e2e5b48aec07710c08d50?s=265&d=identicon&r=PG" style="border: thin solid #999999;"/>
<p>Change<span class="pull-right">Powered by Gravatar</span></p>
<input type="file" name="avatar-uploader" id="avatar-uploader" style="display: none;" />
javascript
$('input[type=file]').on('change', function(){
$.ajax({
url: "/ajax/upload-new-avatar.ajax.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(data) // A function to be called if request succeeds
{
alert("Success");
}
});
});
PHP: /ajax/upload-new-avatar.ajax.php
error_reporting(E_ALL);
ini_set('display_errors', 1);
session_start();
$sourcePath = $_FILES['avatar-uploader']['tmp_name']; // Storing source path of the file in a variable
$targetPath = "".$_FILES['avatar-uploader']['name']; // Target path where file is to be stored
move_uploaded_file($sourcePath,$targetPath) ; // Moving Uploaded file
I'm sure there is something simple that I am missing here and i'm going to feel pretty stupid afterwards but could someone explain to me why the image isn't being uploaded to the server and saved in the AJAX directory for further processing.
What I need it to do is when the user clicks on the "change" hyperlink below the image it opens a file upload dialog (working), once an image has been selected it automatically uploads to the server over an AJAX connection (possibly working, logging shows the PHP file is being triggered), and then the image file needs to be saved in the AJAX directory to be further processed later in the code for it to be uploaded to the avatar service.
Thanks in advance.
Have managed to get it working...
Here is my amended code...
Javascript
$('input[type=file]').on('change', function(event){
files = event.target.files;
event.stopPropagation(); // Stop stuff happening
event.preventDefault(); // Totally stop stuff happening
$("#avatar-status").text("Loading new avatar...");
$("#avatar").css("opacity", "0.4");
$("#avatar").css("filter", "alpha(opacity=40);");
//Create a formdata object and add the files
var data = new FormData();
$.each(files, function(key, value) {
data.append(key, value);
});
$.ajax({
url: '/ajax/upload-new-avatar.ajax.php?files',
type: 'POST',
data: data,
cache: false,
dataType: 'json',
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) {
if(typeof data.error === 'undefined') {
//Success so call function to process the form
//submitForm(event, data);
$("#avatar-status").text("Powered by Gravatar");
$("#avatar").css("opacity", "");
$("#avatar").css("filter", "");
} else {
//Handle errors here
alert('ERRORS: ' + textStatus);
}
},
error: function(jqXHR, textStatus, errorThrown) {
//Handle errors here
alert('ERRORS: ' + textStatus);
}
});
});
PHP
session_start();
require_once("../libraries/logging.lib.php");
new LogEntry("AJAX Upload Started - UploadNewAvatar", Log::DEBUG, "AvatarUpload");
sleep(3);
$data = array();
if(isset($_GET['files'])) {
$error = false;
$files = array();
$uploaddir = '../tmp/';
foreach($_FILES as $file) {
if(move_uploaded_file($file['tmp_name'], $uploaddir .basename($file['name']))) {
$files[] = $uploaddir .$file['name'];
new LogEntry("UploadNewAvatar - Upload Successful", Log::DEBUG, "AvatarUpload");
} else {
$error = true;
new LogEntry("UploadNewAvatar - Errors Occured", Log::ERROR, "AvatarUpload");
}
}
$data = ($error) ? array('error' => 'There was an error uploading your files') : array('files' => $files);
} else {
$data = array('success' => 'Form was submitted', 'formData' => $_POST);
new LogEntry("UploadNewAvatar - Form was submitted successfully", Log::DEBUG, "AvatarUpload");
}
echo json_encode($data);
HTML
<img id="avatar" src="http://www.gravatar.com/avatar/205e460b479e2e5b48aec07710c08d50?s=265&d=identicon&r=PG" style="border: thin solid #999999;"/>
<p>Change<span id="avatar-status" class="pull-right">Powered by Gravatar</span></p>
<input type="file" name="upfile" id="upfile" style="display: none;" />
When I want to printout the output of jQuery AJAX, which has been recived from server. It doesn't show the right charset. What I want exactly is to get š instead I am getting ? or without using utf8_decode() when sending data from server, I get ĹĄ. All files script.js and server php proceed.php are saved in UTF-8 and set in UTF-8. Database is set to UTF-8 as well. All other request from database give the right charset. I've tried most of the things.
In .js file for AJAX:
$.ajaxSetup({
url: "proceed.php", //file to procces data
ContentType : 'charset=UTF-8', // tried here
global: false,
type: "POST",
dataType: "html" // change to text/html, application/text doesnt work at all
});
In .php file:
mysql_query("SET NAMES utf8");
$output = utf8_decode($sql_result);
All possible combinations.
CODE:
PHP
if(!empty($_POST['select_had'])){
$zem = $_POST['select_had'];
$vysledek = mysql_query("SELECT typ_hadanky, jazyk FROM hlavolam RIGHT JOIN hadanka ON hlavolam.id_hlavolamu=hadanka.id_hlavolamu WHERE zeme_puvodu='$zem'");
$out = "";
while ($zaznam = mysql_fetch_array($vysledek)) {
$zaz = $zaznam['jazyk'];
$out .= "<option>".$zaz."</option>";
}
$vys = utf8_decode($out);
echo $vys;
}
jQuery:
$("#sel_had_zem").change(function(){
var select_had = $("#sel_had_zem option:selected").text();
$.ajax({
data:{'select_had':select_had},
success: function(data){
$("#sel_had_jaz option").nextAll().remove();
$("#sel_had_jaz").append(data);
},
error: function(){
alert('No server response');
}
});
});
I'm using an audio recorder from this place
http://webaudiodemos.appspot.com/AudioRecorder/index.html,
but I instead of saving the file locally I would like to upload it back to the server. My best shot was to try to modify the Recorder.setupDownload function in recording.js script to pass the blob it creates to a simple upload PHP script I found here:
<?php
if(isset($_FILES['image'])){
$errors= array();
$file_name = $_FILES['recording']['name'];
$file_size =$_FILES['recording']['size'];
$file_tmp =$_FILES['recording']['tmp_name'];
$file_type=$_FILES['recording']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['image']['name'])));
$extensions = array("wav");
if(in_array($file_ext,$extensions )=== false){
$errors[]="extension not allowed, please choose wav file."
}
if($file_size > 2097152){
$errors[]='File size under 20MB';
}
if(empty($errors)==true){
move_uploaded_file($file_tmp,"images/".$file_name);
echo "Success";
}else{
print_r($errors);
}
}
?>
And I'm tring it using a jquery call,
$.ajax({
type: "POST",
url: "../scripts/Single-File-Upload-With-PHP.php",
data: blob
});
But I'm obviously doing something wrong. The original PHP script has a form in it
used for input, which I commented out trying to call the php code directly.
So my questions would be;
how to modify the Recorder.setupDownload to upload the file to a
designated folder?
how to report back when something goes wrong?
Or alternatively, is there a more elegant solution?
Edit: Regarding what's in the blob
This is how the blob is being defined in recorder.js:
worker.onmessage = function(e){
var blob = e.data;
currCallback(blob);
}
As to my understanding it is created with methods listed in recorderWorker.js (link in comments), and it should contain simply a wav file.
I dont think you should create the blob in the worker, but I had a similar setup (actually based on the same example) where I retrieved the samplebuffers from the worker and save them into the m_data fields of an AudioMixer class that did some stuff to the recording, then:
//! create a wav file as blob
WTS.AudioMixer.prototype.createAudioBlob = function( compress ){
// the m_data fields are simple arrays with the sampledata
var dataview = WTS.AudioMixer.createDataView( this.m_data[ 0 ], this.m_data[ 1 ], this.m_sampleRate );
return( new Blob( [ dataview ], { type:'audio/wav' } ) );
}
WTS.AudioMixer.createDataView = function( buffer1, buffer2, sampleRate ){
var interleaved = WTS.AudioMixer.interleave( buffer1, buffer2 );
// here I create a Wav from the samplebuffers and return a dataview on it
// the encodeWAV is not provided..
return( WTS.AudioMixer.encodeWAV( interleaved, false, sampleRate ) );
}
then to send it to the server
var blob = this.m_projectView.getAudioEditView().getAudioMixer().createAudioBlob();
if( blob ){
//! create formdata (as we don't have an input in a DOM form)
var fd = new FormData();
fd.append( 'data', blob );
//! and post the whole thing #TODO open progress bar
$.ajax({
type: 'POST',
url: WTS.getBaseURI() + 'mixMovie',
data: fd,
processData: false,
contentType: false
} );
}
and I had a node server running where the blob was sent to and could be picked up directly as a wav file, using the express node module:
var express = require( 'express' );
// we use express as app framework
var app = express();
/** mixMovie expects a post with the following parameters:
* #param 'data' the wav file to mux together with the movie
*/
app.post( '/mixMovie', function( request, response ){
var audioFile = request.files.data.path;
....
} );
hope this helps..
Jonathan
In the end this worked nicely for me:
recorder.js:
$.ajax(
{
url: "./scripts/upload.php?id=" + Math.random(),
type: "POST",
data: fd,
processData: false,
contentType: false,
success: function(data){
alert('Your message has been saved. \n Thank you :-)');
}
});
And the upload script itself:
<?php
if(isset($_FILES['data']))
{
echo $_FILES['data']["size"];
echo $_FILES['data']["type"];
echo $_FILES['data']["tmp_name"];
$name = date(YmdHis) . '.wav';
move_uploaded_file($_FILES['data']["tmp_name"],"../DEST_FOLDER/" . $name);
}
?>