Yii framework: Save uploaded file - javascript

I'm using Yii framework for developing website.
Here, I have a problem in save image file which uploaded to server.
Here is the code which I used for uploading image.
<input type="file" onChange="uploadImage(this);">
function uploadImage(obj) {
var request_url = server_url + "uploadImage";
var formData = new FormData();
formData.append("photo", obj.files[0]);
$.ajax({
url: request_url,
type: 'POST',
data: formData,
processData: false,
contentType:false
});
}
And in server part, I can see the file has uploaded but can't get the file.
public function actionUploadImage() {
if (ISSET($_FILES['photo'])) {
var_dump('is set photo');
$temp = CUploadedFile::getInstanceByName('photo');
var_dump($temp);
}
}
It returns "is set photo" and "array(0){}".
Please help me.

You are uploading images using jquery/ajax. You need to include jquery and their corresponding function.
Here is one of tutorial to upload images using jquery -
http://www.9lessons.info/2013/09/multiple-ajax-image-upload-jquery.html
You could google for other tutorials.

Related

Saving a audio recording in a folder

I am using this GitHub project to record some audio on a website, I want to save that file in a folder instead of displaying it on the website.
https://github.com/addpipe/simple-web-audio-recorder-demo
The current version is creating a download link and displaying the audio clip on the website, I've attempted to send the data to PHP using AJAX.
$.ajax({
url: "uploadAudio.php",
type: "POST",
data: "audio", blob,
processData: false,
contentType: false,
success: function(data){
alert('success');
}
});
and the PHP code I tried to save it as a file
<?php
$dir = "uploads/";
move_uploaded_file($_FILES["audio"]["tmp_name"], $dir. "name");
?>
Am I thinking along the right lines? have you got any suggestions for a better way of doing this?

Multiple file upload isn't sending any data to server

I want to upload multiple file upload.
I have this on client side :
$(document).on( "click", ".save-button", function () {
var data = new FormData();
data.append('title', $(this).parent().parent().find("#title_place").val());
$.each($(this).parent().parent().find("input[type='file']")[0].files, function(i, file) {
data.append('file', file);
});
$.ajax({type: "POST",
url: 'save_view.php',
data: data,
success : viewSaveCallBack,
cache: false,
contentType: false,
processData: false,
});
});
I checked all the data in the debuger, and it is working properly. To see this I displayed the value of
$(this).parent().parent().find("#title_place").val()
And
$(this).parent().parent().find("input[type='file']")[0].files
Then, when I try to var_dump $_FILES or $_POST on server side, it's empty.
Same thing with a debugger.
I tried also with
data.append('files[]', file);
When I try to upload a single file (in another input, not exactly the same code), that is working fine.
The html of the input is this one :
<input type=\"file\" multiple directory webkitdirectory allowdirs class=\"form-control input\" id=\"marzipano\">
And it is added dynamically to the DOM.
When I upload a single file, that is working fine.
It is not a duplicate of Sending multipart/formdata with jQuery.ajax since I already use a FormData object, and my code is the same as the answer. It is still not working as intended.
Try to do:
var files = $(this).parent().parent().find("input[type='file']")[0].files;
for(var i=0; i<files.length; i++) {
data.append('file['+i+']', files[i]);
}
and in PHP you might get files via $_POST["file"]
My code is working actually, problem was that post_max_size in the php.ini was too low.

How to read or download generated pdf via ajax with jquery

im creating a service that will transform html to pdf.
Request with parameter(HTML code to be transfered into PDF) ist send with ajax post.
On server side generating pdf file is no problem.
I was trying to send it back with JSON but i figured out that its not a good idea.
So now im sending it back with no changes - full pdf file as it was generated
...
$pdf->Output('out.pdf', 'I');
And here comes the tricky part.
What can i do with it on client side?
I was trying to show it or download it but i could not figured out how.
$.ajax({
type: 'POST',
url: service_url,
data: out,
success: function (data) {
// WHAT SHOULD I DO WITH "data" IF I WANT TO SHOW IT?
error: function () {
alert("Error");
}
});
Thanks
a wild guess would say that you need to create a PDFObject and then throw it into the Ajax.
HTML
<object id="pdf" data="myfile.pdf" type="application/pdf" width="100%" height="100%">
It appears you don't have a PDF plugin for this browser.
No biggie... you can click here to
download the PDF file.
</object>
and in the Ajax you would have to do something like :
$.ajax({
var pdf = $("#pdf");
type: 'POST',
url: service_url,
data: out,
success: function (data) {
pdf.show();
error: function () {
alert("Error");
}
});

How to fix Ajax Image Upload - response back is the HTML not image

I'm breaking down my problem of trying to upload an image via Ajax to Python.
Step 1: Just get the Ajax to display the selected image on the page.
I found this interesting article on Zurb which seems to have the example code I need:
http://zurb.com/playground/ajax-upload
$(document).ready(function() {
var thumb = $('img#thumb');
new AjaxUpload('imageUpload', {
action: $('form#newHotnessForm').attr('action'),
name: 'image',
onSubmit: function(file, extension) {
$('div.preview').addClass('loading');
},
onComplete: function(file, response) {
thumb.load(function(){
$('div.preview').removeClass('loading');
thumb.unbind();
});
thumb.attr('src', response);
}
});
I'm implemented the plugin and setup things up, however the response that gets set to the src is the HTML page itself, rather then the image.
I'm noticing a similar problem on Zurb's website when I check what the src path of the thumb image is after uploading.
Also duplicated in my jsfiddle here:
http://jsfiddle.net/leongaban/cd5Hy/1/
Can you see where am I going wrong?
You probably are not taking the right action for your upload.
Try to create PHP file that will handle your image on server side, then return that image data already on the server:
<?php
$file = $_FILES['image']; // 'image' as you've set it in js code
$path = 'http://example.com/images/'; //path on the server where you gonna store your images. Remember to set proper directory permissions.
$location = $path. $_FILES["file"]["name"]; //this is where the file will go
move_uploaded_file($_FILES["file"]["tmp_name"], $location); // move the file there
echo $location; //send the file location back to the javascript
?>
Now, if you want to show a preview before loading your image to server - try HTML5 file upload handler
Found the answer here: Ajax Upload image
$(document).ready(function (e) {
$('#imageUploadForm').on('submit',(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
type:'POST',
url: $(this).attr('action'),
data:formData,
cache:false,
contentType: false,
processData: false,
success:function(data){
console.log("success");
console.log(data);
},
error: function(data){
console.log("error");
console.log(data);
}
});
}));
});
By Sohil Desai

Unable to upload file using AJAX

I am trying to upload a file through AJAX. I have searched over a lot but found examples using form submit only, but I can not use form submit. I have tried several examples but nothing reaches my server. When I tried this link, it worked but again it was through a form submission.
Here is the piece of code relevant to the context
JS Code
function _upload(filedata) {
$.ajax({
url: './myURI',
data: filedata,
type: 'POST',
contentType: 'multipart/form-data',
mimeType: 'multipart/form-data', //Property added in 1.5.1
success: function (data) {
alert(data);
}
});
}
$("#cpc-uploadBtn").click(function (evt) {
var data;
data = new FormData();
data.append('file', $('#cpc-upload')[0].files[0]);
_upload(data);
});
HTML Part
<input id="cpc-upload" name="file" type="file" />
<button id="cpc-uploadBtn" type="button">Upload</button>
Edit
Is there any other way to do this without using form submit and formdata?
Assuming that you are using Safari/FireFox (only those support FormData), you need to modify your $.ajax call:
$.ajax({
url: './myURI',
data: filedata,
type: 'POST',
contentType: false,
processData: false,
success: function (data) {
alert(data);
}
});
Seeting contentType option to false will force jQuery not to add a Content-Type header for you (otherwise the boundary string will be missing from it). Also the processData flag must be set to false so jQuery will not try to convert your FormData into a string.
Now if you know that your clients are using HTML5 you should try using new JavaScript File API - check following articles:
Working with files in JavaScript, Part 1: The Basics
Working with files in JavaScript, Part 2: FileReader
Working with files in JavaScript, Part 3: Progress events and errors
Working with files in JavaScript, Part 4: Object URLs
Working with files in JavaScript, Part 5: Blobs
In all other cases you are forced to use custom plugins, for example:
Uploadify
jQuery Form Plugin
I suppose currently FormData objects are only supported in Safari/Firefox, it has not been adopted by most of the browsers yet.
I recently struggled a lot finding ajax file uploader for asp.net and I am currently using this one in my project:
https://github.com/valums/file-uploader
there is a small alternative if you want to use
<script>
// wait for the DOM to be loaded
$(document).ready(function()
{
// bind 'myForm' and provide a simple callback function
$("#tempForm").ajaxForm({
url:'../calling action or servlet',
type:'post',
beforeSend:function()
{
alert("perform action before making the ajax call like showing soinner image");
},
success:function(e){
alert("data is"+e);
alert("now do whatever you want with the data");
}
});
});
</script>
you can find the plugin here

Categories