jQuery upload running but not uploading file - php

I was wondering if i could get a bit of advice.
Im trying to upload a file using jquery while keeping the user on the same page.
Whatever i try isnt working. I was wondering if someone could have a look and tell me where im going wrong.
My HTML is
<form id="import" enctype="multipart/form-data" action="/ajax/postimport" method="POST">
<div class="form-group">
<input type="file" name="filename" id="filename" />
</div>
<button type="button" id="importSave">Import</button>
</form>
This is my jquery
$("#importSave").click(function()
{
$.ajax({
url: '/ajax/postimport',
type: 'POST',
dataType: 'json',
contentType: false,
processData: false,
data: {file: $(#filename).val()},
success: function(data)
{
alert(data.result)
},
error: function(textStatus, errorThrown)
{
}
});
});
and then my PHP, which is Laravel 4
if (Input::hasFile('filename')) {
$file = Input::file('filename');
$destPath = public_path() . '/uploads/';
$filename = str_random(10) . '_' . $file->getClientOriginalName();
$uploadSuccess = $file->move($destPath, $filename);
}

It is not possible to upload files by just using the jQuery ajax function. You will need to use a FormData object to do this. The problem with Formdata is that it is not supported in all browsers. If you do want to use it, you can always find plenty tutorials like this one.
You can also use a jQuery plugin that does the work for you. :)

It is not possible to do like this. you are just making post ajax request with only one field file: $(#filename).val().
So you need to use ajax upload library like.
There are several alternatives. But I like most are
http://www.plupload.com/
http://www.uploadify.com/

Related

Laravel SparkForm file upload error

I'm working on a Laravel Spark project and I am trying to get a form to upload a folder to my S3 bucket. I have the form built:
<form enctype="multipart/form-data">
<input type="file" name="resume" v-model="form.resume">
<button #click="updateProfile">Update Profile</button>
</form>
Then I have a vue component set up to handle the form submit:
Vue.component('resume-links', {
template: '#edit-resume-links',
data() {
return {
form: new SparkForm({
resume: ''
})
};
},
methods: {
updateProfile() {
console.log(this.form.resume);
Spark.post('/route/to/controller', this.form).then(response => {
console.log(response);
});
}
}
});
Then in my laravel controller:
$resume = $request->file('resume');
$resumeFileName = time() . '.' . $resume->getClientOriginalExtension();
$s3 = \Storage::disk('s3');
$filePath = '/resumes/' . $resumeFileName;
$s3->put($filePath, file_get_contents($resume), 'public');
When I try to submit the form with a file it throws this error:
Call to a member function getClientOriginalExtension() on null
I have tried var_dumping $resume right after setting it to the file() and what I see outputted to the console is a bunch of js looking code
From everything that I reading it looks like file uploads with Laravel is super easy and I don't know why I am having this issue. Any assistance/advice would be appreciated! Thanks!
First of all, your file input needs to have the v-el attribute rather than v-model.
In your case it would be <input type="file" name="form" v-el:resume />.
Next, in your Vue component, you need to gather the FormData so that it becomes possible to send the file to the server. Files have to be handled slightly differently to plain text fields and such.
Add this to your methods object:
gatherFormData() {
const data = new FormData();
data.append('resume', this.$els.resume.files[0]);
return data;
}
In your updateProfile method you now need to send this data off to the server as a POST request.
updateProfile(e) {
e.preventDefault();
var self = this;
this.form.startProcessing();
$.ajax({
url: '/route/to/controller',
data: this.gatherFormData(),
cache: false,
contentType: false,
processData: false,
type: 'POST',
headers: {
'X-XSRF-TOKEN': Cookies.get('XSRF-TOKEN')
},
success: function (response) {
self.form.finishProcessing();
console.log(response)
},
error: function (error) {
self.form.setErrors(error.responseJSON);
}
});
},
Finally, in your controller method, you can now handle the file as normal
(e.g., $request->file('resume');)
Handling files with Laravel really is a breeze – you just need to make sure you're actually getting them to the server ;)

Trouble getting data on server from FormData

I am having trouble uploading a picture file via AJAX.
Web:
<div>
<form id="birdi_image_form">
<input type="file" name="birdi_image" id="birdi_image" ></input>
</form>
<input type="text" name="species"></input>
<textarea name="comments"></textarea>
</div>
<div id="debug"></div>
<script type="text/javascript">
jQuery(function($){
$('#birdi_image').change(function(){
var ima = new FormData($('#birdi_image_form')[0]);
$.ajax({
url:"/bird/bird_scripts/fu.php",
type:"post",
data: ima,
processData: false,
dataType:"text",
success:function(data, textStatus, jqXHR) {
$('#debug').text(data);
}
});
});
});
</script>
/bird/bird_scripts/fu.php:
<?php
$imagedir = '/images';
$tmpfname = tempnam($imagedir, "b_");
echo var_dump($_POST);
if (move_uploaded_file($_FILES['birdi_image']['tmp_name'], $tmpfname)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Upload failed";
}
?>
From looking around online I was expecting to find contents in my $_FILES variable, but this is empty. Dumping out the $_POST var to the screen like in the example gives me the following. $_POST['birdi_image'] gives me NULL.
array(68) { ["------WebKitFormBoundaryYCAoI8shwgBavjJP
Content-Disposition:_form-data;_name"]=> string(339) ""birdi_image";
filename="test.jpg" Content-Type: image/jpeg ����JFIFdd��
ExifMMbj(1r2��i��B#'B#'Adobe Photoshop
CS2 Windows2008:06:24 11:11:48��b�g"
["?o��(�ci�\�R��Μꟑ���]T��z���"]=> string(82) "���
f�zߠ����i���/��v��E~��[,�Y
�s�������1l�G����-���߿�enu'=�v�z���=?Ҳ���"
["�{��<o��ӗ�M��ysnʨo87~;l���۔�"]=> string(172) "�<��t�2~���O�S
�����t���㵺C�}E������}��I�d]c���y}#�����C,�Z��־��V��ynʿ��?�g�*����o��ٌ�.}�y����}��z����w^�]�m�u������z>�37�_C긵��K𭪣�Y-{��뺷��M���ul��Y�"
["c�yhHp����"]=> string(152)
"��[-���1�]��|�����۽Q�\�e���o�~��g������u�.���A��t�]�3�W�ד��b���}>�����%��K���Ѳ�3���zX��qZ��}u��sc�
���N� ^-w�7���\r� ����c��=?՗δX�j" ["C�uw���-��"]=> string(57)
"���m��w��������ѩ���������k��r����m�t�62rIk���m�ߗV��}" ["�"]=>
string(384)
"!�<��B���6*�c��劷Q���uF*��U��������ď,�y{R���������E%���Q����5.��IE���N�����Ο�̿4~R��...............Upload failed.
I have uploaded files before by using a complete form submit. This is the first time I am trying to do it with AJAX. It looks like the data is getting to the server, but I can't seem to make any sense of it from the server side. As you can see in the code I expected $_FILES['birdi_image'] to exist but it doesn't. Am I doing something completely wrong?
Thanks
You have to set the content type to false, otherwise jQuery will set one(the wrong one) for you
$.ajax({
url:"/bird/bird_scripts/fu.php",
type:"post",
data: ima,
processData: false,
contentType: false,
dataType:"text",
success:function(data, textStatus, jqXHR) {
$('#debug').text(data);
}
});
I struggled with this also - it's just not as easy as it should be. I finally found a guy who did it right, and studied his code.
Ravi Kusuma's jQuery File Upload
In the end, because Kusuma wrote a plugin, I just used his code/plugin. Why re-invent the wheel? He's got everything solved, right down to sending extra data along with the uploaded file.

PHP file uploaded showing false

I have a form that has multiple file uploads and each input is uniquely named, however, when attempting to get the uploaded file, my test if showing false.
Please find the code below. I am at a loss as to why this is happening.
<label class="label" for="uploadfile">Contract:</label>
<input name="'.$ICP.'_uploadedfile" id="'.$ICP.'_uploadedfile" type="file" />
The $ICP var is looped out, as there can be multiple instances, so this way each name is unique and on the server side, the POST is requested for each loop of the ICP.
while($icp_details = mysqli_fetch_array($ICP_exist_qry)){
$ICP_ID = stripslashes($icp_details['ICP_ID']);
if(!file_exists($_FILES[$ICP_ID."_uploadedfile"]['tmp_name']) || !is_uploaded_file($_FILES[$ICP_ID."_uploadedfile"]['tmp_name'])) {
echo false;
} else {
echo true;
}
}
I am not having any problems retrieving the values of the other posted inputs, just the files uploaded part.
Any help on this one is appreciated. :)
Note: Form is being submitted by Ajax.
To upload the file correctly using Ajax (and in this case JQuery) you need to use the FormData object. The code snippet below illustrates how it can be used. It is used instead of the .serialize() or .serializeArray() methods.
$('#file-form').submit(function(e) {
$.ajax({
url: 'http://example.com/upload/',
type: 'POST',
data: new FormData(this),
processData: false,
contentType: false
});
e.preventDefault();
});

Uploading a file with jQuery [duplicate]

This question already has answers here:
jQuery Ajax File Upload
(27 answers)
Closed 9 years ago.
I've a question about file uploading with Ajax. How to submit file with $.ajax()
without a special js-plugin?:
<form action="javascript:return false;">
<input type="text" id="name" />
<input type="file" id="myfile" />
<input type="button" id="submitbutton" value="submit" />
</form>
This is a jQuery small code:
<script type="text/javascript">
$(document).ready(function() {
$('#submitbutton').click(function() {
$.ajax({
type: 'POST',
dataType: 'json',
enctype: 'multipart/form-data',
url: 'upload.php',
async: false,
data: {
'name': $('#name').val(),
'myfile': $('#myfile').val()
},
success: function(data) {
alert(data.msg);
}
});
});
});
</script>
And upload.php file:
<?php
$name = isset($_POST['name']) ? $_POST['name'] : '';
if (isset($_FILES) && isset($_FILES["file"])) {
$files = $_FILES['file'];
$error = isset($files["error"]) ? $files["error"] : '';
$fname = isset($files["name"]) ? $files["name"] : '';
$type = isset($files["type"]) ? $files["type"] : '';
$size = isset($files["size"]) ? $files["size"] : '';
$tmp_name = isset($files["tmp_name"]) ? $files["tmp_name"] : '';
return array('msg' => "Hello, $name! \nYour file data:\nErr: $error, Name: $fname, Type: $type, Size: $size, Tmp: $tmp_name");
}
echo json_encode(array('msg' => 'create image'));
?>
Other option is using iframe, this is a tutorial for doing this;
Files cannot be uploaded via ajax. You may want to checkout the Form Plugin which does support file uploads: http://jquery.malsup.com/form/
If you expect to get this working cross browser, than you can't do that with AJAX only. (But it is ok for you that this will work not in all browsers, you may take a look how to upload files with XMLHttpRequest and jquery here)
As for me, the best would be to use jQuery Forms plugin.
Another option is to do the same thing that plugin does manually.
It will be something like below:
var ifrm = $("<iframe>", {id:"tmp_upload_frame"}).onload(function() {
// do something when response is returned
}).hide();
$("body").append(ifrm);
$("form").prop("target", "tmp_upload_frame")
.prop("enctype","multipart/form-data")
.submit();
But as for me, Forms plugin is much better as it has an interface very similar to ajax interface and does a lot of dirty work for you (like retrieving response from iframe) for you.

Trying to upload a file through jQuery .post() - file input not showing up on back end (using codeigniter)

First of all I'd like to ask that you don't suggest I turn to a jQuery plugin to solve my issue. I'm just not willing to make my app work with a plugin (and it prevents me from learning!)
I have a form with a bunch of fields that I'm passing to my backend via the use of jQuery's $.post() This is what I have as my jQuery function:
$.post(
"/item/edit",
$("#form").serialize(),
function(responseJSON) {
console.log(responseJSON);
},
"html"
);
This is how I opened my form:
<form action="http://localhost/item/edit" method="post" accept-charset="utf-8" class="form-horizontal" enctype="multipart/form-data">
This was auto generated by codeigniter's form_open() method (hence why action="" has a value. Though this shouldn't matter because I don't have a submit button at the end of the form)
Within my #form I have this as my file input: <input type="file" name="pImage" />
When the appropriate button is hit and the $.post() method is called, I have my backend just print the variables like so: print_r($_POST) and within the printed variables the 'pImage' element is missing. I thought that maybe files wouldn't come up as an element in the array so I went ahead and just tried to upload the file using this codeigniter function: $this->upload->do_upload('pImage'); and I get an error: "You did not select a file to upload."
Any idea as to how I can overcome this problem?
You cannot post an image using AJAX, i had to find out here as well PHP jQuery .ajax() file upload server side understanding
Your best bet is to mimic an ajax call using a hidden iframe, the form has to have enctype set to multipart/formdata
Files wont be sent to server side using AJAX
One of the best and simplest JQuery Ajax uploaders from PHP LETTER
all you need is include js in your header normally and Jquery code will be like below
$.ajaxFileUpload({
url:'http://localhost/speedncruise/index.php/snc/upload/do_upload',
secureuri:false,
fileElementId:'file_upload',
dataType: 'json',
data : {
'user_email' : $('#email').val()
},
success: function (data, status) {
// alert(status);
// $('#avatar_img').attr('src','data');
}
,
error: function (data, status, e) {
console.log(e);
}
});
wish this can help you
I can't do this with codeigniter and Ajax, I pass the image to base64 and in the controller I convert into a file again
//the input file type
<input id="imagen" name="imagen" class="tooltip" type="file" value="<?php if(isset($imagen)) echo $imagen; ?>">
//the js
$(document).on('change', '#imagen', function(event) {
readImage(this);
});
function readImage(input) {
var resultado='';
if ( input.files && input.files[0] ) {
var FR= new FileReader();
FR.onload = function(e) {
//console.log(e.target.result);
subirImagen(e.target.result);
};
FR.readAsDataURL( input.files[0] );
}
}
function subirImagen(base64){
console.log('inicia subir imagen');
$.ajax({
url: 'controller/sube_imagen',
type: 'POST',
data: {
imagen: base64,
}
})
.done(function(d) {
console.log(d);
})
.fail(function(f) {
console.log(f);
})
.always(function(a) {
console.log("complete");
});
}
//and the part of de controller
public function sube_imagen(){
$imagen=$this->input->post('imagen');
list($extension,$imagen)=explode(';',$imagen);
list(,$extension)=explode('/', $extension);
list(,$imagen)=explode(',', $imagen);
$imagen = base64_decode($imagen);
$archivo='archivo.'.$extension;
file_put_contents('imagenes/'.$archivo, $imagen);
chmod('imagenes/'.$archivo, 0777); //I use Linux and the permissions are another theme
echo $archivo; //or you can make another thing
}
ps.: sorry for my english n_nU

Categories