Carga de PHP, JSON y JQuery

For the longest time, I've been using a very standard HTML post to my PHP upload script for my image upload. I wanted to try something new by sending the image to the PHP uplaod script via JQuery/JSON. All text data on my site is sent through this and I wanted to try and get image uploads to work with JQUery. I googled, but only found pre-made scripts, no one ever has a tutorial on making it yourself or where to begin, there's nothing wrong with using premade scripts but alot of times I can't get it to work with my website or style it so that it fits in, so I began to write a quick something, can you guys please tell me if this would work being that an image isn't text data?


<div class="upload_box_logged">
<input type="file" id="file_up"><br />
<button id="up_btn">Upload</button>
<em style="display:none; color:red;" id="no_file"  >Please Select a File!</em>
<em style="display:none; color:red;" id="up_fail" >Failed!</em>
<em style="display:none; color:red;" id="up_success" >Success!</em>

Mi JQuery:


var fileCheck = $('#file_up').val();
    if(fileCheck == '')

        var file_upVar = encodeURIComponent($('#file_up').val());

            type: 'POST', url: 'upload.php',  dataType: "json",  data: { file_up: file_upVar  }, 
            success: function(result) {                 
                if (!result.success) { $('#up_fail').fadeIn().fadeOut(5000); }  
                else { $('#up_success').fadeIn().fadeOut(5000);  } 



Now here's my PHP file that I've been using with my standard HTML post to PHP method:

$file_name = $HTTP_POST_FILES['ufile1']['name'];
$file_name_for_db = ($HTTP_POST_FILES['ufile1']['name']);
$new_file_name = $id."_pic1_".$file_name;

    $allowedTypes = array("image/jpg", "image/jpeg", "image/png"); 
    $maxSize = 5 * 1024 * 1024; // 3Mb 

    $fileType = $HTTP_POST_FILES['ufile1']["type"]; 
    $fileSize = $HTTP_POST_FILES['ufile1']["size"]; 

    // check if there was an error 
    if ($HTTP_POST_FILES['ufile1']["error"] > 0) 

    // check if the filetype is valid 
    if (!in_array($fileType, $allowedTypes)) 
        die("Invalid file type: $fileType"); 

    // check if the size doesn't exceed the limitations 
    if ($fileSize > $maxSize) 
        die("The file was too big: $fileSize"); 

    $name = $HTTP_POST_FILES['ufile1']["name"]; 
    $tmpfile = $HTTP_POST_FILES['ufile1']["tmp_name"]; 

    // check if the filename is valid 
    if (preg_match("/[\w-]+\.(jpg|jpeg|png)$/", $name) != 1) 
        die("Invalid file name: $name"); 

    $path = "../pic/";

    move_uploaded_file($tmpfile, $path); 

I will obviously have to de-code the post with something like this.. well I would if this is a correct way of going about it.

$uploaded_file = htmlspecialchars(trim(urldecode($_POST['file_up'])));

Well this is how I'd do it if it were text. Any way I can do this with image data?

Thanks a bunch -Mike

preguntado el 10 de marzo de 12 a las 07:03

I was thinking, you know how you can store your images as text in a MySQL DB by base64 encrypting it? Can I somehow break the image down to base64 within the JQuery and then send that as text to the PHP file, then un-base 64 there, re-render as a jpg or png and then have it save where I want... or is that just too weird of a thing? -

I'm not sure if it's possible to uploading file like that. In a form uploading, the browser reads the file content from the local disk. In ajax, no form post is performed, how would you read the content of a local file within javascript? it can only get the filename from the file input element. I heard of a solution you can try, which is to embbed an iframe in the page that contains a form to do the uploading, the script in page will manipulate the form in iframe. So the uploading process will not refresh the page but the iframe, it looks like normal ajax action without page refreshing. -

3 Respuestas

Unfortunately I don't believe there is a way to post Images & Files via Ajax.

The way I've normally done it in the past is creating a hidden iframe and making the form target the iframe name.

So an example would look like:

<form name="imageform" method='POST' action="upload_image.php" target="image_upload_frame" enctype="multipart/form-data">
<iframe name="image_upload_frame" height="1" width="1" style="visibility: hidden"></iframe>

respondido 10 mar '12, 08:03

This makes perfect sense! Awesome logic! Thank you sir! - user1053263

Podrías usar este: - Works fine for every Firefox (the most used browser on earth! ;) )

respondido 10 mar '12, 08:03

Ohh sweet! thanks man. I'm going to see if I can get something like this to work in firefox. - user1053263

Using an iframe is the common and cross browser way of uploading files in AJAX. There are many interresting resources:

respondido 10 mar '12, 08:03

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.