For the longest time, I use a very standard HTML message to load a PHP script to load an image. I wanted to try something new by sending an image to a PHP uplaod script through jQuery / JSON. All the text data on my site is sent through this, and I wanted to try and upload images to work with JQUery. I googled, but only found ready-made scripts, no one ever learned to do it on their own or where to start, there is nothing wrong with using ready-made scripts, but many times I can not get it to work with my site or style so that it fits, so I started to write something quickly, maybe you guys tell me if this will work if the image is not text data?
My HTML:
<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> </div>
My jQuery:
$('#up_btn').click(function(){ var fileCheck = $('#file_up').val(); if(fileCheck == '') { $('#no_file').fadeIn(); } else { var file_upVar = encodeURIComponent($('#file_up').val()); $.ajax({ 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 is my PHP file that I used with my standard HTML message for the 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) { die($HTTP_POST_FILES['ufile1']["error"]); } // 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 message with something like this .. well, if that was the right way to get around this.
$uploaded_file = htmlspecialchars(trim(urldecode($_POST['file_up'])));
Well, thatโs how I would do it if it were text. How can I do this with image data?
Thanks a bunch -Mike