I'm trying to code my own php uploader so I can learn and understand how it all works. Trying not to use any libraries/plugins/API's. So basically I have the javascript stuff doin what it's supposed to be (i hope..). Now I'm stuck on the PHP. I want it to upload and save it as img/1.png. (not using any variables just to test it...). Here are my scripts. Keeping it very simple without any error checks just to get basic uploading working. Would this work for multiple files? May somebody guide me on what my PHP file should look like just for very basic (multi)file upload? Thanks!
album_create.js
$(document).ready(function() {
$('#album_create').submit(function() {
var file = document.getElementById('album-files').files[0]; //Files[0] = 1st file
var reader = new FileReader();
reader.onload = function(f) {shipOff(f);};
reader.onerror = function(event) {
console.error("File could not be read! Code " + event.target.error.code);
};
reader.readAsText(file, 'UTF-8');
return false;
});
});
function shipOff(event) {
var result = event.target.result;
var fileName = document.getElementById('album-files').files[0].name; //Should be 'picture.jpg'
console.log(fileName);
$.post('ajax/album_create.php', { data: result, name: fileName }, function(data){console.log(data);});
return false;
}
ajax/album_create.php
$data = $_POST['data'];
move_uploaded_file($data[0], 'img/1.png');
you are posting:
data: result, name: fileName
but album_create.php expecting:
$data = $_POST['data'];
$fileName = $_POST['fileName'];
$fileName = $_POST['fileName']; should be: $fileName = $_POST['name'];
Related
I'm trying to add a feature where I can attach an image in the form using Codeigniter, Ajax, jQuery. The form submits and when I check the database for the image file, it seems that it doesnt have anything on it. Usually they use FormData but, I already started using this method. I was wondering if there is anyway I could do it this way.
Here are my codes.
jQuery
$('#addForm').submit(function(event){
var emp_id = $("#agentNames").val();
var campaign = $("#addCampaign").val();
var k_type = $("#addKudosType").val();
var c_name = $("#addCustomerName").val();
var p_number = $("#addPhoneNumber").val();
var e_add = $("#addEmailAdd").val();
var comment = $("#addCustomerComment").val();
var supervisor = $("#addSupervisor").val();
var file = $("#addFile").val();
var p_reward = $("#addPrefReward").val();
var pfrd = $("#addProofreading").val();
var k_card = $("#addKudosCard").val();
var r_status = $("#addRewardStatus").val();
dataString = "emp_id="+emp_id+"&campaign="+campaign+"&k_type="+k_type+"&c_name="+c_name+"&p_number="+p_number+"&e_add="+e_add+"&comment="+comment+"&supervisor="+supervisor+"&file="+file+"&p_reward="+p_reward+"&pfrd="+pfrd+"&k_card="+k_card+"&r_status="+r_status;
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>index.php/Kudos/addKudos/",
data: dataString,
cache: false,
success: function(html)
{
alert("Succesfully Added!");
location.reload();
}
});
event.preventDefault();
});
Controller
public function addKudos()
{
$emp_id= $this->input->post('emp_id');
$campaign= $this->input->post('campaign');
$k_type= $this->input->post('k_type');
$c_name= $this->input->post('c_name');
$p_number= $this->input->post('p_number');
$e_add= $this->input->post('e_add');
$comment= $this->input->post('comment');
$supervisor= $this->input->post('supervisor');
$file= $this->input->post('file');
$config['upload_path'] = "uploads/images/";
$config['allowed_types'] = "jpg|png";
$config['file_name'] = $_FILES['addFile']['name'];
$this->load->library('upload', $config);
$this->load->initialize($config);
if($this->upload->do_upload('addFile')){
$uploadData = $this->upload->data();
$picture = $uploadData['file_name'];
} else {
$picture = '';
}
$p_reward= $this->input->post('p_reward');
$pfrd= $this->input->post('pfrd');
$k_card= $this->input->post('k_card');
$r_status= $this->input->post('r_status');
$this->KudosModel->add_kudos($emp_id,$campaign,$k_type,$c_name,$p_number,$e_add,$comment,$supervisor,$picture,$p_reward,$pfrd,$k_card,$r_status);
}
Model
function add_kudos($emp_id,$campaign,$k_type,$c_name,$p_number,$e_add,$comment,$supervisor,$picture,$p_reward,$pfrd,$k_card,$r_status)
{
$emp_id1 =mysqli_real_escape_string($this->db->conn_id,trim($emp_id));
$campaign1 =mysqli_real_escape_string($this->db->conn_id,trim($campaign));
$k_type1 =mysqli_real_escape_string($this->db->conn_id,trim($k_type));
$c_name1 =mysqli_real_escape_string($this->db->conn_id,trim($c_name));
$p_number1 =mysqli_real_escape_string($this->db->conn_id,trim($p_number));
$e_add1 =mysqli_real_escape_string($this->db->conn_id,trim($e_add));
$comment1 =mysqli_real_escape_string($this->db->conn_id,trim($comment));
$supervisor1 =mysqli_real_escape_string($this->db->conn_id,trim($supervisor));
$file1 =mysqli_real_escape_string($this->db->conn_id,trim($picture));
$p_reward1 =mysqli_real_escape_string($this->db->conn_id,trim($p_reward));
$pfrd1 =mysqli_real_escape_string($this->db->conn_id,trim($pfrd));
$k_card1 =mysqli_real_escape_string($this->db->conn_id,trim($k_card));
$r_status1 =mysqli_real_escape_string($this->db->conn_id,trim($r_status));
$query = $this->db->query("insert into tbl_kudos(emp_id,acc_id,kudos_type,client_name,phone_number,client_email,comment,uid,file,reward_type,proofreading,kudos_card,reward_status,is_given) values('$emp_id1','$campaign1','$k_type1','$c_name1','$p_number1','$e_add1','$comment1','$supervisor1','$file1','$p_reward1','$pfrd1','$k_card1','$r_status1',now())");
}
Thanks.
The database doesn't have any file because you aren't submitting any. You didn't show any HTML but you must have something like:
<input type="file" id="addfile">
But in jquery, you are retrieving the file using:
var file = $("#addFile").val();
Which will return the file name or an empty string because you won't get file contents (or image) using val(). You need to look for another method to upload form data with file contents using AJAX. Check this out: How can I upload files asynchronously?
I'm having a problem with sending a file from an app I'm developing with phonegap.
I'm new to phonegap, so I might be trying to solve this in an entirely wrong way, so let me describe the the end goal first.
I'm developing a car rental app, I need to make a contact form, so users can leave an order to rent a car.
The form requires user to put in some basic information, like name and phone number, and also attach a photo or a scan of driver's license.
I was able to figure out the basic info part. I'm using $.ajax dataType: 'jsonp', to send the data to the server and then simply e-mail it to my client's address.
But I can find a way to send the file to the server.
I'm using an input[type=file] field to let the user choose what file to upload.
I've tried uploading file using FileTransfer, but apparently input[type=file] gives you some fake file path, that can't be directly used by FileTransfer.upload()
Problem is, I can't understand how can I get a proper file path for FileTransfer.upload function.
I've tried doing it another way, by reading the file using FileReader.
I tried reading the file and setting an image src to the result, but it doesn't work (it show broken image icon instead of an image, the same code works on PC).
I also tried to output it as text, that does output some data (so why doesn't it work for image src?).
Because I did manage to output the data read from the file as text I thought I will send that to the server and save it.
So here is how the code would look like:
On input change I read the file into a global variable
$(".file1").change(function(e){
var caster = e.target;
var files = caster.files;
if(FileReader && files && files.length) {
var fr = new FileReader();
fr.onloadend = function(e) {
//$(".image").attr("src",e.target.result);
window.file1base64 = e.target.result;
}
fr.readAsDataURL(files[0]);
}
});
Then, when user presses a button, I run FileTransfer.upload and then check every 0.1 seconds, whether the file upload is complete
function uploadSuccess(r) {
$(".output").append(" Success ");
window.fileStatus = true;
}
function uploadError(error) {
$(".output").append(" Error "+error.code+" ");
window.fileStatus = true;
window.fileError = error.code;
}
function uploadFile() {
$(".output").append(" uploadFile ");
file = $('.file1').val().split('\\').pop();
$(".output").append(" File-"+file+" ");
if(file){
$(".output").append(" fileExists ");
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = file;
options.mimeType = "image/jpeg";
options.chunkedMode = false;
options.headers = {
Connection: "close"
};
$(".output").append(" FileUploadOptions ");
window.fileStatus = false;
window.fileError = '';
//fileuri = $(".image").attr("src");
fileuri = window.file1base64;
$(".output").append(" fileuri ");
var ft = new FileTransfer();
ft.upload(fileuri, encodeURI("http://***.***/savefile.php"), uploadSuccess, uploadError, options);
$(".output").append(" upload ");
checkFile();
}
}
function checkFile() {
if(!window.fileStatus) {
$(".output").append(" check ");
setTimeout(checkFile, 100);
return;
}
}
After some checks, it prints out Error 3 and I can't figure out what that means or how to fix it.
Server side code is simply this:
Get the file and save it
$dir_name = dirname(__FILE__)."/uploadedimages/";
move_uploaded_file($_FILES["file"]["tmp_name"], $dir_name."test.txt");
But no file is created on the server.
use the FormData object to get the form data (including input file) and submit it this way:
var data = new FormData($('#yourFormID')[0]);
$.ajax({
url: serverURL,
data: data,
cache:false,
contentType: false,
processData: false,
type: 'POST',
error: function(jqXHR,textStatus,errorThrown){
},
success: function(data){
}
});
You should set the FILEURL in some variable and image in some html image element and then use it to transfer the image.
like this:
function onPgCameraSuccess(imageData) {
fileEntry.file(
function(fileObj) {
var previewImage= document.getElementById('SomeImageElement');
fileName=imageData.substr(imageData.lastIndexOf('/')+1);
fileURL=imageData;
previewImage.src =imageData;
$('#SomeTextBox').val(fileName);
});
}
function SubmitPhoto(){
var uOptions = new FileUploadOptions();
var ft = new FileTransfer();
uOptions .fileKey = "keyofyourfileonserver";
uOptions .fileName = fileName;
uOptions .mimeType = "image/jpeg";
uOptions .httpMethod = "POST";
uOptions .params = params;
ft.upload(fileURL,
urlofsvc,
photoSuccess,
photoFail,
uOptions,
true
);}
Admittedly, there are similar questions lying around on Stack Overflow, but it seems none quite meet my requirements.
Here is what I'm looking to do:
Upload an entire form of data, one piece of which is a single file
Work with Codeigniter's file upload library
Up until here, all is well. The data gets in my database as I need it. But I'd also like to submit my form via an AJAX post:
Using the native HTML5 File API, not flash or an iframe solution
Preferably interfacing with the low-level .ajax() jQuery method
I think I could imagine how to do this by auto-uploading the file when the field's value changes using pure javascript, but I'd rather do it all in one fell swoop on for submit in jQuery. I'm thinking it's not possible to do via query strings as I need to pass the entire file object, but I'm a little lost on what to do at this point.
Can this be achieved?
It's not too hard. Firstly, take a look at FileReader Interface.
So, when the form is submitted, catch the submission process and
var file = document.getElementById('fileBox').files[0]; //Files[0] = 1st file
var reader = new FileReader();
reader.readAsText(file, 'UTF-8');
reader.onload = shipOff;
//reader.onloadstart = ...
//reader.onprogress = ... <-- Allows you to update a progress bar.
//reader.onabort = ...
//reader.onerror = ...
//reader.onloadend = ...
function shipOff(event) {
var result = event.target.result;
var fileName = document.getElementById('fileBox').files[0].name; //Should be 'picture.jpg'
$.post('/myscript.php', { data: result, name: fileName }, continueSubmission);
}
Then, on the server side (i.e. myscript.php):
$data = $_POST['data'];
$fileName = $_POST['name'];
$serverFile = time().$fileName;
$fp = fopen('/uploads/'.$serverFile,'w'); //Prepends timestamp to prevent overwriting
fwrite($fp, $data);
fclose($fp);
$returnData = array( "serverFile" => $serverFile );
echo json_encode($returnData);
Or something like it. I may be mistaken (and if I am, please, correct me), but this should store the file as something like 1287916771myPicture.jpg in /uploads/ on your server, and respond with a JSON variable (to a continueSubmission() function) containing the fileName on the server.
Check out fwrite() and jQuery.post().
On the above page it details how to use readAsBinaryString(), readAsDataUrl(), and readAsArrayBuffer() for your other needs (e.g. images, videos, etc).
With jQuery (and without FormData API) you can use something like this:
function readFile(file){
var loader = new FileReader();
var def = $.Deferred(), promise = def.promise();
//--- provide classic deferred interface
loader.onload = function (e) { def.resolve(e.target.result); };
loader.onprogress = loader.onloadstart = function (e) { def.notify(e); };
loader.onerror = loader.onabort = function (e) { def.reject(e); };
promise.abort = function () { return loader.abort.apply(loader, arguments); };
loader.readAsBinaryString(file);
return promise;
}
function upload(url, data){
var def = $.Deferred(), promise = def.promise();
var mul = buildMultipart(data);
var req = $.ajax({
url: url,
data: mul.data,
processData: false,
type: "post",
async: true,
contentType: "multipart/form-data; boundary="+mul.bound,
xhr: function() {
var xhr = jQuery.ajaxSettings.xhr();
if (xhr.upload) {
xhr.upload.addEventListener('progress', function(event) {
var percent = 0;
var position = event.loaded || event.position; /*event.position is deprecated*/
var total = event.total;
if (event.lengthComputable) {
percent = Math.ceil(position / total * 100);
def.notify(percent);
}
}, false);
}
return xhr;
}
});
req.done(function(){ def.resolve.apply(def, arguments); })
.fail(function(){ def.reject.apply(def, arguments); });
promise.abort = function(){ return req.abort.apply(req, arguments); }
return promise;
}
var buildMultipart = function(data){
var key, crunks = [], bound = false;
while (!bound) {
bound = $.md5 ? $.md5(new Date().valueOf()) : (new Date().valueOf());
for (key in data) if (~data[key].indexOf(bound)) { bound = false; continue; }
}
for (var key = 0, l = data.length; key < l; key++){
if (typeof(data[key].value) !== "string") {
crunks.push("--"+bound+"\r\n"+
"Content-Disposition: form-data; name=\""+data[key].name+"\"; filename=\""+data[key].value[1]+"\"\r\n"+
"Content-Type: application/octet-stream\r\n"+
"Content-Transfer-Encoding: binary\r\n\r\n"+
data[key].value[0]);
}else{
crunks.push("--"+bound+"\r\n"+
"Content-Disposition: form-data; name=\""+data[key].name+"\"\r\n\r\n"+
data[key].value);
}
}
return {
bound: bound,
data: crunks.join("\r\n")+"\r\n--"+bound+"--"
};
};
//----------
//---------- On submit form:
var form = $("form");
var $file = form.find("#file");
readFile($file[0].files[0]).done(function(fileData){
var formData = form.find(":input:not('#file')").serializeArray();
formData.file = [fileData, $file[0].files[0].name];
upload(form.attr("action"), formData).done(function(){ alert("successfully uploaded!"); });
});
With FormData API you just have to add all fields of your form to FormData object and send it via $.ajax({ url: url, data: formData, processData: false, contentType: false, type:"POST"})
I was wondering if i could get som suggestions on what the best approach to do the following would be...
I am currently calling a Flash AS3 function from Javascript (using jQuery) this function uploads a file which has already been selected in this flash file. Flash then uploads the file and calls a php file (upload.php) which handles the processed file. This all works fine. However there are other details that are filled out that pertain to the file uploaded (entered by the user in textboxes) All this data including the file path to where it has been uploaded must then be saved to a DB. Which can be done through an ajax call to another php file (processData.php). My issue is that when i upload the file i cant send the other details along with the file through flash (atleast not that i know of) which causes 2 different php scripts to execute. Secondly the other php script called through ajax doesnt have the file information to add to the DB. I can store this info in a session if i want but it just doesnt seem to convince me as the best way to go about this. Any other ideas or suggestions?
There is quite a bit of code I have so to avoid making this a HUGE question ill post the JS part that i think is important and some snippets of flash so you can have an idea of whats going on... If theres anyhting else youd like to see of the code feel free to ask and ill post it...
JS:
$("#uploadAudio").submit(function(event) {
event.preventDefault();
var form = $(this);
var title = form.find("#title").val();
var desc = form.find("#desc").val();
var flash = $("#flash");
var flashFileSet = flash.get(0).jsIsFileSelected();
if(flashFileSet)
{
$.ajax({
type: "POST",
url: "processData.php",
dataType: "text",
data: "title=" + title + "&desc=" + desc,
async: false,
success: function() {
audFile.get(0).jsUploadFile();
}
});
}
});
Flash
public function fUploader(){
req = new URLRequest();
req.url = ( stage.loaderInfo.parameters.f )? stage.loaderInfo.parameters.f : 'http://virtualmanagementonline.com/ajax/audUpload.php';
pFilterType = ( stage.loaderInfo.parameters.filterType )? stage.loaderInfo.parameters.filterType : 'Images';
pFileFilters = ( stage.loaderInfo.parameters.fileFilters )? stage.loaderInfo.parameters.fileFilters : '*.jpg;*.jpeg;*.gif;*.png';
file = new FileReference();
setup( file );
select_btn.addEventListener( MouseEvent.CLICK, browse );
progress_mc.bar.scaleX = 0;
tm = new Timer( 1000 );
tm.addEventListener( TimerEvent.TIMER, updateSpeed );
cancel_btn.addEventListener( MouseEvent.CLICK, cancelUpload );
cancel_btn.visible = false;
ExternalInterface.addCallback("jsUploadFile", uploadFile);
ExternalInterface.addCallback("jsIsFileSelected", IsFileSelected);
}
public function browse( e:MouseEvent ){
filefilters = [ new FileFilter(pFilterType, pFileFilters) ]; file.browse( filefilters );
}
private function selectHandler( e:Event ){
var tf = new TextFormat();
tf.color = 0x000000;
label_txt.defaultTextFormat = tf;
label_txt.text = file.name;
//file.upload( req );
}
public function IsFileSelected():Boolean{
if(label_txt.text != "")
{
return true;
}
else
{
return false;
}
}
public function uploadFile():void{
file.upload(req);
}
**Note: NOT all the flash code is shown since there is alot. I put up what i thought was needed to get an understanding of what exactly is going on.
If there is anything i can add for further details please let me know. Thanks in advance!
You can send as many data as you want to flash, since ExternalInterface is available.
ActionScript 3 Reference states the following about ExternalInterface:
From JavaScript on the HTML page, you can:
- Call an ActionScript function.
- Pass arguments using standard function call notation.
- Return a value to the JavaScript function.
All you have to do is register an ActionScript function/method as callable from the container:
ActionScript
...
ExternalInterface.addCallback("jsUploadFile", uploadFile);
...
public function uploadFile (title:String, desc:String):void
{
var infos:URLVariables = new URLVariables();
infos.desc = desc;
infos.title = title;
/* When you pass the URLVariables to data property of URLRequest,
all variables associated with the URLVariables object will be
sent to the server along with the image uploaded. */
req.data = infos;
file.upload(req);
}
Then, call it from the container (HTML) passing the additional information as parameters.
JavaScript
$("#uploadAudio").submit(function(event) {
event.preventDefault();
var form = $(this);
var title = form.find("#title").val();
var desc = form.find("#desc").val();
var flash = $("#flash");
var flashFileSet = flash.get(0).jsIsFileSelected();
if(flashFileSet)
{
/* Instead of sending title and desc to the server via ajax, pass
them as parameters to the jsUploadFile method. So
you can handle everything in one place */
audFile.get(0).jsUploadFile(title, desc);
}
});
Hope it helps.
First off, I am very bad at flash/actionscript, it is not my main programming language.
I have created my own file upload flash app that has been working great for me up until this point. It uses PHP to upload the files and sends back a status message which gets displayed in a status box to the user.
Now I have run into a situation where I need the HTML to pass a parameter to the Actionscript, and then to the PHP file using POST. I have tried to set this up just like adobe has it on http://livedocs.adobe.com/flex/3/html/help.html?content=17_Networking_and_communications_7.html without success.
Here is my Actionscript code
import fl.controls.TextArea;
//Set filters
var imageTypes:FileFilter = new FileFilter("Images (*.jpg, *.jpeg, *.gif, *.png)", "*.jpg; *.jpeg; *.gif; *.png");
var textTypes:FileFilter = new FileFilter("Documents (*.txt, *.rtf, *.pdf, *.doc)", "*.txt; *.rtf; *.pdf; *.doc");
var allTypes:Array = new Array(textTypes, imageTypes);
var fileRefList:FileReferenceList = new FileReferenceList();
//Add event listeners for its various fileRefList functions below
upload_buttn.addEventListener(MouseEvent.CLICK, browseBox);
fileRefList.addEventListener(Event.SELECT, selectHandler);
function browseBox(event:MouseEvent):void {
fileRefList.browse(allTypes);
}
function selectHandler(event:Event):void {
var phpRequest:URLRequest = new URLRequest("ajax/upload.ajax.php");
var flashVars:URLVariables = objectToURLVariables(this.root.loaderInfo);
phpRequest.method = URLRequestMethod.POST;
phpRequest.data = flashVars;
var file:FileReference;
var files:FileReferenceList = FileReferenceList(event.target);
var selectedFileArray:Array = files.fileList;
var listener:Object = new Object();
for (var i:uint = 0; i < selectedFileArray.length; i++) {
file = FileReference(selectedFileArray[i]);
try {
file.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA, phpResponse);
file.upload(phpRequest);
}
catch (error:Error) {
status_txt.text = file.name + " Was not uploaded correctly (" + error.message + ")";
}
}
}
function phpResponse(event:DataEvent):void {
var file:FileReference = FileReference(event.target);
status_txt.htmlText += event.data;
}
function objectToURLVariables(parameters:Object):URLVariables {
var paramsToSend:URLVariables = new URLVariables();
for(var i:String in parameters) {
if(i!=null) {
if(parameters[i] is Array) paramsToSend[i] = parameters[i];
else paramsToSend[i] = parameters[i].toString();
}
}
return paramsToSend;
}
The flashVars variable is the one that should contain the values from the HTML file. But whenever I run the program and output the variables in the PHP file I receive the following.
//Using this command on the PHP page
print_r($_POST);
//I get this for output
Array
(
[Filename] => testfile.txt
[Upload] => Submit Query
)
Its almost like the parameters are getting over written or are just not working at all.
Thanks for any help,
Metropolis
Try...
print_r($_FILES);
Like I said in my comment: Do you successfully receive the variable in Flash from the flashvars?
I haven't done Flash in a while but maybe, instead of your objectToURLVariables function, just referencing each variable directly is a better way. At least to figure out if you have those variables from your HTML page. So maybe do something like this:
var myVar:String = LoaderInfo(this.root.loaderInfo).parameters.myVar;
var flashVars:URLVariables = objectToURLVariables(myVar);
Ok, I have fixed the issue somehow.....I kept changing things back and forth and realized that the cache had not been cleared in awhile. I cleared the cache and it started working for some reason.
I did change one line back to the way I had it before.
I changed
var flashVars:URLVariables = objectToURLVariables(this.root.loaderInfo);
To
var flashVars:URLVariables = objectToURLVariables(root.loaderInfo.parameters);
Im not positive that this was causing the problem. It may have been that I just needed to clear the cache the whole time. Anyway, thanks for your help guys.