I have an idea and would like to try it out. I am using a cool tool called cropit. I need to upload multiple images, crop them automatically and save them on the server side. Unfortunately I can process only one image at a time and I have 12 separate fields for the upload and preview. The current code for the 5th image for example looks like this:
HTML:
<div id="image-cropper5">
<!-- This is where user selects new image -->
<label> Upload Photo <input type="file" class="cropit-image-input"/></label>
<!-- This is where the preview image is displayed -->
<label><div class="cropit-preview"></div></label>
<!-- This is the confirmation -->
<button type="button" id="image5pick" disabled>OK</button>
</div>
JQuery:
$('#image-cropper5').cropit();
$('#image5pick').click(function() {
var imageData5 = $('#image-cropper5').cropit('exportZoom', 3);
imageData5 = $('#image-cropper5').cropit('export');
$.post('php/upload.php', { imageData5: imageData5 }, function() { $('#image5pick').data('clicked', true) })
});
PHP:
$imageData5 = $_POST["imageData5"];
if ($_POST["imageData5"]){
$decoded = $imageData5;
$exp = explode(',', $decoded);
$base64 = array_pop($exp);
$data = base64_decode($base64);
$file = "data5.png";
file_put_contents($file, $data);
}
What I want to try out is to upload multiple images via <input name="photos[]" type="file" class="multiupload" multiple/>, take every image from the array and process every image automatically and separately through the codes (also without the "OK" confirmation, just process as soon as the preview comes on).
So the first question here: How do I take the files seperately to the jquery code?
Related
i have a form for uploading files / images. I have no problem uploading and displaying the images , but i want to forward the images back to the same page that the imageas where selected, and use the POST data to place the image chosen in the 1st place , so the user can view and then if wanting to change the image for another.
The Problem i am having though is posting the flie back.
I have tried using it as a veriable and just using the variable to display an image but when i send that back to the image selection page, it does not display anything and if the user does not select a new image , the image data is not sent either..
i know im short cutting my explanation but i hope sum1 can help
here is my code (simplyfied)
THE INPUT FORM
<input type='file' class='fileinput' id='sellimage0' name='sellimage0' onchange='addimg0(this , img0, mainimage);' accept='image/*' /></input>
THE RECEIVER
if (!empty($_FILES['sellimage0']['name'])){
$image_path0 = $_FILES['sellimage0']['name'];
$image_path0 = filter_var($image_path0, FILTER_SANITIZE_STRING);
$image_path0 = strip_tags($image_path0);
$i0url=$image_path0;
} else {$i0url='';}
THE DISPLAY
<?php if (!empty($i0url)) { echo "
<div class='image0' id='image0' title='1st Image' >
<img id='img0' src='{$i0url}' class='imageclass'></img>
<input type='hidden' id='img0' name='sellimage0' value='{$_FILES['sellimage1']['name']}' ></input>
</div>
"; } ?>
THE POST BACK & RECEIVE
if (!empty($_FILES['sellimage0']['name'])){
$image_path0 = $_FILES['sellimage0']['name'];
$image_path0 = filter_var($image_path0, FILTER_SANITIZE_STRING);
$image_path0 = strip_tags($image_path0);
$i0url=$image_path0;
} else {$i0url='';}
<img id='img0' <?php if (!empty($i0url)) { echo " src='{$i0url}' "; } else { echo " src='' style='opacity:0;' "; } ?> onclick=' document.getElementById("sellimage0").click();' class='imageclass' ></img>
<div class='cancel' onClick='cancelimage(sellimage0 , img0);'> </div>
<div class='magnify' > </div>
<input type='file' class='fileinput' id='sellimage0' name='sellimage0' onchange='addimg0(this , img0, mainimage);' accept='image/*' /></input>
I hope this is making sense to you all.
i wish to choose an image, then post that choice to a view page
then from the view page , user has option to go back and edit
but how do i send the form data back to be received correctly so i can send the file back and forth between edit and review...
The way i have been trying just removes the selected images when i go back to the mainpage again.. iv tried many methods, but im lost on how to do this correctly.. Iv looked on the net to but finding my specific problem seems to be difficult.
Thank you.
Is there a way to add a base64 image string to the $_FILES array (the array that you get when you upload a file)? Basically, I want to fake a file upload from a base64 string. The base64 string comes from an email attachment. I don’t wish to use file_get_contents(), because I want to save the image in a database as a binary image. I don’t need to upload it, as such, but I do need it be a part of the $_FILES array.
Uploading is a way of sending the contents of a file from a client (usually a web browser) to a server. It sounds like you've already got the data you need on the server (in PHP), so you don't need to upload it.
You can use base64_decode() to convert it from base64 to the straight file contents.
If you need it as a file on your server, you can use something like file_put_contents() to save it as a new file.
If you're trying to do something else with the uploaded file in the $_FILE array, please provide more details. Whatever it is, you don't need to actually upload the file.
The $_FILES array doesn't actually contain the contents of the file - it contains a filename where the contents have been saved.
If you must use the $_FILES array (in order to re-use an existing class, for example), you'll need to use file_put_contents() to save a new temporary file, and then manually add an entry the the $_FILES array pointing to that temporary file (Just like modifying any other array). Don't forget to delete your temporary file when you're done - this is normally handled automatically by PHP, but if you create the file manually, you'll have to delete it manually too.
I'd highly recommend refactoring or providing an alternate interface to your class instead though. You shouldn't have to pretend that the file was uploaded just to save it to the database.
index.php
// https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL
/* Simple */
function previewImage( image, preview, string )
{
var fileImage = image.files[0];
var preview = document.querySelector( preview );
var reader = new FileReader();
reader.addEventListener( "load", function() {
preview.style.height = "100";
preview.title = fileImage.name;
// convert image file to base64 string
preview.src = this.result;
/* --- */
document.querySelector( string ).value = this.result;
}, false );
if ( fileImage )
{
reader.readAsDataURL( fileImage );
}
}
document.querySelector( "#imageID" ).addEventListener( "change", function() {
previewImage( this, "#imagePreviewID", "#imageStringID" );
} )
/* Simple || */
<form method="post" action="process.php" >
Title: <input type="text" name="title" /><br />
File Upload: <input type="file" name="image" id="imageID" /><br />
Preview: <img src="#" id="imagePreviewID" /><br />
String base64: <textarea name="imageString" id="imageStringID" rows="10" cols="50" readonly="readonly" ></textarea>
<hr />
<input type="submit" name="submit" value="Submit" />
</form>
process.php
<?php
$data = array(
"post" => $_POST,
"files" => $_FILES
);
echo "<pre>";
// echo json_encode($data);
var_dump($data);
?>
<img src="<?= $_POST['imageString']; ?>" />
repl.it
I have a rental listing site where users can create a page and show photos of their listing. I have created a form with multiple file input fields for the users to pick the files to upload as well as a submit button:
<form method="post" enctype="multipart/form-data">
<input type="file" name="image_1" id="image_1" />
<input type="file" name="image_2" id="image_2" />
<input type="file" name="image_3" id="image_3" />
<input type="submit" name="submit" value="Submit" />
</form>
After the user selects their images, I am running a function which resizes and uploads them:
function uploadAndResize($imageFile, $filename) {
$folder = '../images/';
$orig_w = 400;
$filename = str_replace(' ', '_', $filename);
list($width, $height) = getimagesize($imageFile);
$src = imagecreatefromjpeg($imageFile);
$orig_h = ($height / $width) * $orig_w;
$tmp = imagecreatetruecolor($orig_w, $orig_h);
imagecopyresampled($tmp, $src, 0, 0, 0, 0, $orig_w, $orig_h, $width, $height);
imagejpeg($tmp, $folder.$filename, 100);
imagedestroy($tmp);
imagedestroy($src);
}
$imageFile_1 = $_FILES['image_1']['tmp_name'];
$filename_1 = basename( $_FILES['image_1']['name']);
$imageFile_2 = $_FILES['image_2']['tmp_name'];
$filename_2 = basename( $_FILES['image_2']['name']);
$imageFile_3 = $_FILES['image_3']['tmp_name'];
$filename_3 = basename( $_FILES['image_3']['name']);
uploadAndResize($imageFile_1,$filename_1);
uploadAndResize($imageFile_2,$filename_2);
uploadAndResize($imageFile_3,$filename_3);
The current setup I have works great to upload the photos, but I would like to replace the multiple file input fields with one single file input field that has the ability to select multiple files at one time. I do, however, want each file that gets selected to have a name attribute of "image_" combined with the next iteration, so that it will work well with the current script I am using. I also need it to call the function for as many files that were selected.
How do I allow users to select multiple files out of a single input field using php and jquery and still have it work with my current script?
using "mutiple" attribute in HTML form input elements.
for eg:
<input type="file" name="attacheDocument" multiple="multiple" />
returns array of files.
Refer to this great tutorial showing how to use a multi-file jquery plugin with php. Note that you will have to loop through the files in your php code (refer to the tutorial mentioned above.)
I recommend you http://valums.com/ajax-upload/
It is something difficult to make it works, but the results is awesome. Allow:
.- Multiple files
.- Progress bar
This plugin contains a php script that can be easily modified.
Just test it in the page I showed you.
Use jquery multi file upload plugin. Its simple. Refer below link
http://www.fyneworks.com/jquery/multiple-file-upload/
I want any php script which can demonstrate me how to upload multiple files in PHP. In my application I have given a link "Add Image" & 'Remove Image', on click of "Add Image" I am adding a new upload field on the page using javascript, using which user can upload more and more images, no limit on number of images for now. On click of delete i am removing that element.
I am just not getting the concept on how to process them in the POST request in PHP. I know in HTML if we give the name of field like myimages[] then it will create a PHP array, but how to process this.
I don't want to use AJAX/JavaScript for uploading, want to do it with traditional POST request in PHP.
If anyone have any link or code which shows such functionality, then pleas provide it will be really helpful.
Thanks!
combine this uploading multiple files & move_uploaded_file
<form action="file-upload.php" method="post" enctype="multipart/form-data">
Send these files:<br />
<input name="userfile[]" type="file" /><br />
<input name="userfile[]" type="file" /><br />
<input type="submit" value="Send files" />
</form>
$uploads_dir = '/uploads';
foreach ($_FILES["userfile"]["error"] as $key => $error)
{
if ($error == UPLOAD_ERR_OK)
{
$tmp_name = $_FILES["userfile"]["tmp_name"][$key];
$name = $_FILES["userfile"]["name"][$key];
move_uploaded_file($tmp_name, "$uploads_dir/$name");
}
}
Uploaded files are not in the POST array, they are in the FILES array.
http://www.php.net/manual/en/features.file-upload.multiple.php
The files are uploaded to a temp area with "safe" names. The array will contain the name of the file and the tmp file. You can then move them to where you want.
Name file input fields as file[] in HTML, then just run a loop from 0 do count($_FILES) in PHP...
for($i = 0; $i < count($_FILES['file']['tmp_name']); $i++){
$tmp = $_FILES['file']['tmp_name'][$i];
$name = md5(microtime());
if(move_uploaded_file($tmp, "dir/$name.jpg")){
echo "File '$tmp' uploaded successfully";
}else{
echo "Uploading '$tmp' failed";
}
}
I've implemented something similar in the past as follows:
Have a hidden JavaScript form variable (e.g.: "numuploads") that stores the number of file inputs currently in the form. This will need to be incremented/decremented when you add/remove an input on the front end.
Name each of the inputs on the front end using a pattern such as "upload_X", where X is the next in the sequence. (Effectively the same as the counter above -1.)
On the PHP landing page, simply scan the $_FILES superglobal, looking for each "upload_X" where X is zero thru numuploads - 1.
You can then carry out the required logic for each of the uploaded files, other form elements, etc.
All the scripts I have found via Google search rely on some sort of screen that first asks the user how many files they need to upload and the upload script works based on that number.
But what if I don't want any limits, but want to allow the user to upload as many or as few as they want. How to go about this?
All I have for now is the form:
<form enctype="multipart/form-data" method="post" action="script.php">
<input id="my_file_element" type="file" name="myFile[]" >
<input type="submit" value="Upload!" name="submit">
</form>
EDIT
I think the way I phrased my question is causing some misunderstanding. I am not in need of some way to add more "input type = file" field elements. I am already using a javascript that enables the user to add more form fields by clicking a button, those other fields are identical to the 1st one posted above.
What I am asking this question for, is to know how to handle the actual upload of files to the server using a php script.
EDIT
Let's say your form is like this
<form enctype="multipart/form-data" method="post" action="script.php">
<input id="my_file_element" type="file" name="myFile[]" >
<input id="my_file_element" type="file" name="myFile[]" >
<input id="my_file_element" type="file" name="myFile[]" >
etc...
<input type="submit" value="Upload!" name="submit">
</form>
What you want to do is get all the files called myFile[]. Here's what you do in PHP:
foreach ($_FILES["myFile"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["myFile"]["tmp_name"][$key];
$name = $_FILES["myFile"]["name"][$key];
// here we move it to a directory called data
// you can move it wherever you want
move_uploaded_file($tmp_name, "data/$name");
} else {
// an error occurred, handle it here
}
}
ORIGINAL
Using HTML and JavaScript alone, there isn't any easy way to upload multiple files at the same time.
I would use a Flash library, such as SWFUpload, to do the upload instead. Using this plugin, you can show a standard multi-file upload window, as shown in this demo. This will allow users to easily select multiple files in the same file browser.
If you don't want to use Flash for some reason, you could use JavaScript to dynamically swap input elements, as in this example.
EDIT
That depends on how you called the file input elements. If you followed my approach below, you can get the number of files with:
if (empty($_FILES['attach']['name']))
$count_files = 0;
else
$count_files = count($_FILES['attach']['name']);
Try var_dump($_FILES) to see the complete $_FILES array, in case you have any doubts on its structure.
ORIGINAL
Something like this, with Javascript:
<script type="text/javascript">
var j = 2; //default two files
function novoa() {
j = j+1;
var elem = document.createElement("input");
var par = document.getElementById("filed");
elem.setAttribute("type", "file");
elem.name = "attach[]";
elem.id = "file_" + j;
par.appendChild(elem);
}
function delult() {
if (j == 0) return;
var elem = document.getElementById("file_" + j);
var par = document.getElementById("filed");
j = j-1;
par.removeChild(elem);
}
</script>
...
<p id="addupl">More files |
Less files</p>
<p id="filed">
<input type="file" name="attach[]" id="file_1" />
<input type="file" name="attach[]" id="file_2" />
</p>
OMG you're asking how to handle this form?
there is an example right on the manual page:
http://www.php.net/manual/en/features.file-upload.post-method.php
<?php
foreach ($_FILES["pictures"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["pictures"]["tmp_name"][$key];
$name = $_FILES["pictures"]["name"][$key];
move_uploaded_file($tmp_name, "data/$name");
}
}
?>
In your PHP script, do a var_dump($_FILES). The output should help you move further into the direction you wish. Take a look at PHP's filesystem functions for more info on what you can do with the files, after using the move_uploaded_file function.
In order to really answer your question How to handle the upload, you'd need to tell us what you want to accomplish/do with the files.
Just use JavaScript to append another input element to the form.