Ajax: Upload the image to choose among many others - javascript

I am going to go crazy if I don't find a solution to this. I drag and drop many pictures to a drag area and then I want to choose anyone of them as to upload it on the server. However, with the following code I always upload the last one...
HTML code:
<form id="upload" action="upload.php" method="POST" enctype="multipart/form-data">
<div id="dragarea"></div>
<input type="file" id="fileselect" name="fileselect[]" multiple="multiple"/>
</form>
JS code which is executed upon a click event on the image file I have dropped inside the dragarea:
var fd = new FormData($('#upload')[0]);
$.ajax({
method:"POST",
url:"upload.php",
dataType:"json",
data:fd,
contentType: false,
cache: false,
processData:false,
success: function(data) {
alert(data);
}
})
and my upload.php
if (!empty($_FILES))
{
$sourcePath = $_FILES['fileselect']['tmp_name'];
echo json_encode($sourcePath);
$targetPath = $_FILES['fileselect']['name'];
move_uploaded_file($sourcePath,$targetPath) ;
}
What changes do I have to do as to send the clicking image for uploading and then get it on the server?
Thank you very much

Related

How to upload a file in Webform using javascript to have it access in global PHP variable $_FILES

I need help and almost crazy. I found a shitload of answers but they all do to work or at least work just a bit !?!
My task is to use a html form and upload one file or more to the webserver using ajax und recieving an answer after evaluation of php. Best I want to send form input information as well as file by an $ajax Request.
I do not understand the syntax.
So can the one or other person ...
a) Tell me how to do correctly one and also a list of files.
How to upload form data and files in one go.
b) What is the structure in detail of the file object
file = $('#file0')[0].files[0] <- I am totally lost, except that
|_____________| '#file0' is the id of the input
? |________| item 'file'
?
in the following piece of code below
Many thanks in advance.
Marvin
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
function ajax_file_upload(){
var fd = new FormData();
var file;
// file = $('#file0')[0].files[0]
// fd.append('file0', file);
var formfiles = document.querySelectorAll('[type=file]');
// we start from since the first two input comes from a different form
for (let i = 0; i < formfiles.length; i++) {
var file = formfiles[i].files[0];
var id = 'file' . i;
fd.append( id , file );
alert( file.name );
}
$.ajax({
url: './ajaxupload.php',
type: 'post',
data: fd,
contentType: false,
processData: false,
success: function(response){
alert(response);
},
error: function(response){
alert("Error occurred while trying to upload file");
}
});
}
</script>
</head>
<body>
<form method="post" action="JavaScript:ajax_file_upload();" enctype="multipart/form-data" id="myform">
<input type="file" id="file0" name="file0" />
<input type="file" id="file1" name="file1" />
<input type="file" id="file2" name="file2" />
<input type="submit" value="Submit">
</form>
</body>
</html>
PHP in script ajaxupload.php:
print_r $_FILES;
I have found the right piece of code I was looking for ...
$.ajax({
...
data: new FormData($('#webform')[0]),
contentType:false,
cache:false,
processData:false,
mimeType: "multipart/form-data",
success: function( upload ){},
...
});

Dynamically adding picture using php

I am having trouble getting a picture stored on a server and its path in my database, then i want to retrieve and showe it on the same page. So far I have the add photo button which onchange triggers the photo to a series of checks then stores it. However, because of this set up the page changes, but there's other info on the page that needs to be inputted. I am assuming I have to create some ajax function, which I have below, but it doesn't work. Here's what I have so far.
<div class="step1-container">
<h3 class="steps-detail">Step 1:</h3>
<p>Upload a picture for you new friends</p>
<form action="../Controllers/fileupload_controller.php" method="post" enctype="multipart/form-data">
Select image to upload:
<label class="upload-cov">
<input type="file" name="fileToUpload" id="fileToUpload">
<span>Add Photo</span>
</label>
<input type="submit" id="photoSubmit" style="display:none">
</form>
</div>
<div class="profile-pix">
</div>
php:
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
$_POST['UserId'] = $_SESSION['logname'];
$_POST['ProfilePix'] = $target_file;
if (storeData($_POST, $table, $cxn)) {
$result = $target_file;
//echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
}
js:
$("#fileToUpload").change(function() {
$('#photoSubmit').click();
});
ajax:
$('#fileToUpload').on('change', 'input', function(e) {
e.preventDefault();
var str = $('#fileToUpload').serialize();
$.ajax({
type: 'POST',
url: '../Controllers/fileupload_controller.php',
async: true,
traditional: true,
data: str,
success: function (msg) {
console.log(msg);
}
});
Since you want to send a file as multi-part/form-data to the server using ajax, the easiest way will be to send the form data of the form.
Example code:
//from within the on change event listener
$.ajax({
//pass the form element to the form data object
data: new FormData($(this).parents('form'))
})

how can i upload file to server using FormData?

I try to file upload to spring server using FormData object. And I hide input for type="file". However, when I submit form, it is not working. I don't know where is incorrect.
This is part of html. when some button is clicked, saveFiles() is called.
<script src="http://malsup.github.com/jquery.form.js"></script>
<form name="fileForm" id="fileForm" method="post" enctype="multipart/form-data">
<input style="display:none" type="file" id="fileSelector" name="fileSelector" multiple="" />
<input type="hidden" id="docId" value="${doc.id}" />
<div id="files"></div>
</form>
(function (global, $) {
...
initFilehandler();
...
}
function initFilehandler() {
document.querySelector('#fileSelector').addEventListener('change', handleFileSelect, false);
selDiv = document.querySelector("#files");
}
function saveFiles() {
$("form#fileForm").submit(function(event){
event.preventDefault();
var formData = new FormData($(this)[0]);
console.log(formdata);
$.ajax({
url: "/rd/file/save",
type: "POST",
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function () {
alert("success");
}
});
});
}
You can't just use formdata for uploading files. There's a lot of options for this one. But Im giving you a less complicated one.
Try using this plugin:
jQuery Form
I've been using that for years especially multiple file uploads. Good thing.. these plugin has callback for upload progress.. you can make a progress bar or something out of it..

Multiple file upload with ajax and php

I want to uplod multiple files through ajax but I can't figure out how I can grab the files in PHP. Can anyone help me? Thank you!
Here is the code:
HTML:
<form enctype="multipart/form-data" method="POST">
<input type="file" id="file" multiple="multiple" name="file"/>
</form>
<div id="info"></div>
<div id="preview"></div>
JavaScript:
$(document).ready(function(){
$("#file").change(function(){
var src=$("#file").val();
if(src!="")
{
formdata= new FormData(); // initialize formdata
var numfiles=this.files.length; // number of files
var i, file, progress, size;
for(i=0;i<numfiles;i++)
{
file = this.files[i];
size = this.files[i].size;
name = this.files[i].name;
if (!!file.type.match(/image.*/)) // Verify image file or not
{
if((Math.round(size))<=(1024*1024)) //Limited size 1 MB
{
var reader = new FileReader(); // initialize filereader
reader.readAsDataURL(file); // read image file to display before upload
$("#preview").show();
$('#preview').html("");
reader.onloadend = function(e){
var image = $('<img>').attr('src',e.target.result);
$(image).appendTo('#preview');
};
formdata.append("file[]", file); // adding file to formdata
console.log(formdata);
if(i==(numfiles-1))
{
$("#info").html("wait a moment to complete upload");
$.ajax({
url: _url + "?module=ProductManagement&action=multiplePhotoUpload",
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function(res){
if(res!="0")
$("#info").html("Successfully Uploaded");
else
$("#info").html("Error in upload. Retry");
}
});
}
}
else
{
$("#info").html(name+"Size limit exceeded");
$("#preview").hide();
return;
}
}
else
{
$("#info").html(name+"Not image file");
$("#preview").hide();
return;
}
}
}
else
{
$("#info").html("Select an image file");
$("#preview").hide();
return;
}
return false;
});
});
And in PHP I get $_POST and $_FILES as an empty array;
Only if I do file_get_contents("php://input"); I get something like
-----------------------------89254151319921744961145854436
Content-Disposition: form-data; name="file[]"; filename="dasha.png"
Content-Type: image/png
PNG
���
IHDR��Ò��¾���gǺ¨��� pHYs��������tIMEÞ/§ýZ�� �IDATxÚìw`EÆgv¯¥B-4 ½Ò»tBU©)"¶+*"( E¥J7ôÞ;Ò¤W©¡&puwçûce³WR¸ èóûrw»³ï}fö
But I can't figure out how to proceed from here.
I am using Jquery 1.3.2 maybe this is the problem?
Thank you!
Sorry about the answer, but I can't add a comment yet.
I would recommend not checking the file type in javascript, it is easily bypassed. I prefer to scrutinise the file in PHP before allowing it to be uploaded to a server.
e.g.
This answer taken from another question (uploaded file type check by PHP), gives you an idea:
https://stackoverflow.com/a/6755263/1720515
<?php
$allowedTypes = array(IMAGETYPE_PNG, IMAGETYPE_JPEG, IMAGETYPE_GIF);
$detectedType = exif_imagetype($_FILES['fupload']['tmp_name']);
$error = !in_array($detectedType, $allowedTypes);
?>
You can read the documentation on the exif_imagetype() function here.
Could you post your PHP code please? And I will update my answer if I have anything to add.
UPDATE:
NOTE: The 'multiple' attribute (multiple="multiple") cannot be used with an <input type='file' /> field. Multiple <input type='file' /> fields will have to be used in the form, naming each field the same with [] added to the end to make sure that the contents of each field are added to an array, and do not overwrite each other when the form is posted.
e.g.
<form enctype="multipart/form-data" method="POST">
<input type="file" id="file_0" name="img_file[]" />
<input type="file" id="file_1" name="img_file[]" />
<input type="file" id="file_2" name="img_file[]" />
</form>
When the form is submitted, the contents of any <input type='file' /> fields will be added to the PHP $_FILES array. The files can then be referenced using $_FILES['img_file'][*parameter*][*i*], where 'i' is key associated with the file input and 'paramter' is one of a number of parameters associated with each element of the $_FILES array:
e.g.
$_FILES['img_file']['tmp_name'][0] - when the form is submitted a temporary file is created on the server, this element contains the 'tmp_name' that is generated for the file.
$_FILES['img_file']['name'][0] - contains the file name including the file extension.
$_FILES['img_file']['size'][0] - contains the file size.
$_FILES['img_file']['tmp_name'][0] can be used to preview the files before it is permanently uploaded to the server (looking at your code, this is a feature you want to include)
The file must then be moved to its permanent location on the server using PHP's move_uploaded_file() function.
Here is some example code:
<?php
if (!empty($_FILES)) {
foreach ($_FILES['img_file']['tmp_name'] as $file_key => $file_val) {
/*
...perform checks on file here
e.g. Check file size is within your desired limits,
Check file type is an image before proceeding, etc.
*/
$permanent_filename = $_FILES['img_file']['name'][$file_key];
if (#move_uploaded_file($file_val, 'upload_dir/' . $permanent_filename)) {
// Successful upload
} else {
// Catch any errors
}
}
}
?>
Here are some links that may help with your understanding:
http://www.w3schools.com/php/php_file_upload.asp
http://php.net/manual/en/features.file-upload.multiple.php
http://www.sitepoint.com/handle-file-uploads-php/
Plus, some extra reading concerning the theory around securing file upload vulnerabilities:
http://en.wikibooks.org/wiki/Web_Application_Security_Guide/File_upload_vulnerabilities
You can use ajax form upload plugin
That's what i have found couple of days ago and implemented it this way
Ref : LINK
You PHP Code can be like this
uploadimage.php
$response = array();
foreach ($_FILES as $file) {
/* Function for moving file to a location and get it's URL */
$response[] = FileUploader::uploadImage($file);
}
echo json_encode($response);
JS Code
options = {
beforeSend: function()
{
// Do some image loading
},
uploadProgress: function(event, position, total, percentComplete)
{
// Do some upload progresss
},
success: function()
{
// After Success
},
complete: function(response)
{
// Stop Loading
},
error: function()
{
}
};
$("#form").ajaxForm(options);
Now you can call any AJAX and submit your form.
You should consider below code
HTML
<input type="file" name="fileUpload" multiple>
AJAX
first of all you have to get all the files which you choose in "input type file" like this.
var file_data = $('input[type="file"]')[0].files;
var form_data = new FormData();
for(var i=0;i<file_data.length;i++)
{
form_data.append(file_data[i]['name'], file_data[i]);
}
then all your data is in formData object now you can send it to server(php) like this.
$.ajax({
url: 'upload.php', //your php action page name
dataType: 'json',
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function (result) {
// code you want to execute on success of ajax request
},
error: function (result) {
//code you want to execute on failure of ajax request
}
});
PHP
<?php
foreach($_FILES as $key=>$value)
{
move_uploaded_file($_FILES[$key]['tmp_name'], 'uploads/' .$_FILES[$key]['name']);
}

AJAX Code For Uploading

My html page for uploading has only two things on it: a file open button, and a Submit. It's no problem getting the open dialog up, but after the user clicks OK, where can I find the path string?
</td>
<td style="width: 109.8pt; padding: .75pt .75pt .75pt .75pt" width="146">
<input id="file" name="file" type="file">
<p class="MsoNormal"> </p>
</td>
Does the php file below come with development tools, or is it part of default Windows javaScrpt?
action="upload.php"
Pekka is correct, this has nothing to do with either asp.net or javascript. When you submit a file upload (whether it be in an asp.net app or php) there will be some standard Response information, some of which will be details on the selected file (filename, etc.).
A quick Google search brings up several open source PHP upload utilities, as well as file upload DOM references, such as:
http://sourceforge.net/projects/uploadtool/
http://www.tizag.com/phpT/fileupload.php
http://www.w3schools.com/php/php_file_upload.asp
I'd recommend editing your question to exclude the asp.net tag and replace it with PHP. That way more PHP developers will see your question.
Try the below code
You have to make an "images" folder in the current directory and make two files :
1: Index.php 2: upload.php
You will also get the image name in the success which can be used for saving image name in the database.
1: Index.php
<html>
<head>
<title>
</title>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" >
var imgName = "";
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
url: "upload.php",
type: "POST" ,
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
success: function (data) {
data = JSON.parse(data);
imgName = data.path;
var pic = imgName;
},
error: function () {}
});
});
});
</script>
</head>
<body>
<form enctype="multipart/form-data">
<input type="file" name="pic" id="pic">
<br>
<input name="submit" type="submit" value="Submit">
</form>
</body>
</html>
2: Upload.php
<?php
if (is_array($_FILES)) {
if (is_uploaded_file($_FILES['pic']['tmp_name'])) {
$sourcePath = $_FILES['pic']['tmp_name'];
$targetPath = "./images/" .time(). $_FILES['pic']['name'];
if (move_uploaded_file($sourcePath, $targetPath)) {
$imgPath['path']=$targetPath;
echo json_encode($imgPath);
}
}
}

Categories