Multiple images upload using javascript, PHP, MySQl - javascript

Here I am doing a Hybrid Android app conversion. My page is HTML page. I need to upload multiple images using Javascript only. In my page I can't use PHP if(isset($_POST['submit'])) function because it's a HTML page. And also I can't use <form action='upload.php' method='POST'>, because it redirect to that PHP page. So I can't be in a same page.
<form method="POST" action="" id="proinsert" name="proinsert" enctype="multipart/form-data">
<input type="file" name="photo" id="photo" class="form-control">
<button id="submit" name="submit" class="btn btn-primary margintop">Submit</button>
</form>
and my PHP page
foreach($_FILES['photos']['name'] as $file){
$message .= "Attachments:" .$file['filename'];
}

Your question is very broad. However, I'll do my best to answer it:
You have 3 logical layers to your problem here:
The HTML that creates the user interface
The Javascript - that handles processing and sending your images (or any file) to another place.
Your PHP code, which will accept your images and process/save them to your server.
A brief overview of how to approach the solution:
Build a form in HTML with a file upload field.
<form method="post" enctype="multipart/form-data">
<input type="file" name="files[]" multiple>
<input type="submit" value="Upload File" name="submit">
</form>
In your HTML file, write or include Javascript that will serialise the form data, and POST it to your PHP file.
<script type="text/javascript">
const url = 'process.php';
const form = document.querySelector('form');
form.addEventListener('submit', e => {
e.preventDefault();
const files = document.querySelector('[type=file]').files;
const formData = new FormData();
for (let i = 0; i < files.length; i++) {
let file = files[i];
formData.append('files[]', file);
}
// Uses browser's built in Fetch API - you can replace this with jQuery or whatever you choose.
fetch(url, {
method: 'POST',
body: formData
}).then(response => {
console.log(response);
});
});
</script>
Write the logic into a new PHP file (called process.php) to handle the form data (images) as appropriate.
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (isset($_FILES['files'])) {
$errors = [];
$path = 'uploads/';
$extensions = ['jpg', 'jpeg', 'png', 'gif'];
$all_files = count($_FILES['files']['tmp_name']);
$fileNames = [];
for ($i = 0; $i < $all_files; $i++) {
$file_name = $_FILES['files']['name'][$i];
$file_tmp = $_FILES['files']['tmp_name'][$i];
$file_type = $_FILES['files']['type'][$i];
$file_size = $_FILES['files']['size'][$i];
$file_ext = strtolower(end(explode('.', $_FILES['files']['name'][$i])));
$fileNames[] = $file_name;
$file = $path . $file_name;
if (!in_array($file_ext, $extensions)) {
$errors[] = 'Extension not allowed: ' . $file_name . ' ' . $file_type;
}
if ($file_size > 2097152) {
$errors[] = 'File size exceeds limit: ' . $file_name . ' ' . $file_type;
}
if (empty($errors)) {
move_uploaded_file($file_tmp, $file);
}
}
if ($errors) {
print_r($errors);
} else {
print_r(json_encode(['file_names' => $fileNames]));
}
}
}
For speed - the example code in this solution was taken from https://www.taniarascia.com/how-to-upload-files-to-a-server-with-plain-javascript-and-php/
For other examples - you could check out StackOverflow's other questions. Here's a similar one to yours: uploading image using javascript

Related

How to Upload a Full Folder with their files

I got this code for Upload multiple files but now I don't know how can I upload a folder with multiple files and maybe subfolder with more files. etc
As you can see I'm using javscript for getting and php for procesing and saving the files right now with files around 2MB
I was trying to get like $_Folder with a foreach but it doesn't work for me :/
Index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Upload Files</title>
</head>
<body>
<form method="post" enctype="multipart/form-data">
<input type="file" name="files[]" multiple>
<input type="submit" value="Upload File" name="submit">
</form>
<script src="upload.js"></script>
</body>
</html>
process.php
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (isset($_FILES['files'])) {
$errors = [];
$path = 'uploads/';
$extensions = ['jpg', 'jpeg', 'png', 'gif'];
$all_files = count($_FILES['files']['tmp_name']);
for ($i = 0; $i < $all_files; $i++) {
$file_name = $_FILES['files']['name'][$i];
$file_tmp = $_FILES['files']['tmp_name'][$i];
$file_type = $_FILES['files']['type'][$i];
$file_size = $_FILES['files']['size'][$i];
$file_ext = strtolower(end(explode('.', $_FILES['files']['name'][$i])));
$file = $path . $file_name;
if (!in_array($file_ext, $extensions)) {
$errors[] = 'Extension not allowed: ' . $file_name . ' ' . $file_type;
}
if ($file_size > 2097152) {
$errors[] = 'File size exceeds limit: ' . $file_name . ' ' . $file_type;
}
if (empty($errors)) {
move_uploaded_file($file_tmp, $file);
}
}
if ($errors) print_r($errors);
}
}
upload.js
const url = 'process.php';
const form = document.querySelector('form');
form.addEventListener('submit', e => {
e.preventDefault();
const files = document.querySelector('[type=file]').files;
const formData = new FormData();
for (let i = 0; i < files.length; i++) {
let file = files[i];
formData.append('files[]', file);
}
fetch(url, {
method: 'POST',
body: formData
}).then(response => {
console.log(response);
});
});
Expecting to Upload something like this
Upload:
-(1Folder)
--Image.png
--Imagen.jpg
--(2Folder)
---Image2.png
--(3Folder)
---Image3.jpg
--Imagen.gif
In modern Chrome, Firefox, and Edge you can set a html attribute, webkitdiretory to let the file input become a directory select window instead. And if you also use the multiple attribute after selecting the folder all contents (and contents in subfolders) will be in the .files list
<input type="file" webkitdirectory multiple>
You would then just use the same code to include all the files for upload.
Now if you want to keep the folder structure you would have to also include the webkitRelativePath which holds the relative path for that file within the folder you selected. And use that path to create the folders on the server.
for (let i = 0; i < files.length; i++) {
let file = files[i];
let fileParamName = `file${i}`;
let filePathParamName = `filepath${i}`;
formData.append(fileParamName, file);
formData.append(filePathParamName,file.webkitRelativePath);
}
And then on the server use filePathParamName to make the directory structure and move the file to it:
//Just for example
//make sure to used sanitized data in production
$folderpath = $path.dirname($_POST["filepath23"]);
$file = $path.$_POST["filepath23"];
$file_tmp = $_FILES["file23"]["tmp_name"];
//third option is for recursive folder creation (make subfolders)
mkdir($path,0644,true);
move_uploaded_file($file_tmp, $file)
For an easier method you could put all the files into a zip file within javascript and just upload the single zip file and extract on the server. Using JSZip and PHP ZipArchive class:
var zip = new JSZip();
for (let i = 0; i < files.length; i++) {
let file = files[i];
zip.file(file.webkitRelativePath, file);
}
zip.generateAsync({type:"blob"})
.then(function(content) {
formData.append("folderzip",content);
fetch(url, {
method: 'POST',
body: formData
}).then(response => {
console.log(response);
});
});
Then in php unzip the folder to where you want it:
move_uploaded_file($file_tmp, $path);
$zip = new ZipArchive();
if($zip->open($path)){
$zip->extractTo($somepath);
$zip->close();
//delete zip file
unlink($path);
}
Client side demo of file listing using webkitRelativePath:
var output = document.querySelector("#output");
document.querySelector("input").onchange = function() {
var files = this.files;
for (file of files) {
output.insertAdjacentHTML('beforeend', `<div>${file.webkitRelativePath}</div>`);
}
}
<input type="file" webkitdirectory multiple>
<div id="output"></div>

Upload multiple files using ajax

Hi I have a modal to upload multiple images as shown below and would like to upload the images and return back the error message or a successful message. The problem is I cannot seem to process all images.I have created a formdata in the javascript where I am appending all files but from the php I seem not to be able to handle all of them. Any idea why?
<!-- Modal -->
<div class="modal fade" id="uploadImages" role="dialog">
<div class="modal-dialog modal-lg">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Upload Scanned Images</h4>
</div>
<div class="modal-body" id="body">
<form method="POST" enctype="multipart/form-data">
Select file : <input type='file' name='file[]' id='file' class='form-control' multiple=""><br>
<input type='submit' class="btn btn-info" value="Upload File" id='but_upload' name='submit'>
</form>
<script src="uploadImages.js"></script>
</div>
<div class="modal-footer">
<p>Only jpeg, png, bmp and tiff Images are allowed to be uploaded</p>
</div>
</div>
</div>
</div>
I also have a javascript to send an ajax post:
$(document).ready(function () {
$("#but_upload").click(function () {
var filedata = $('#file')[0];
var formdata = false;
if (window.FormData) {
formdata = new FormData();
}
var i = 0,
len = filedata.files.length,
img, reader, file;
for (i = 0; i < len; i++) {
file = filedata.files[i];
if (formdata) {
formdata.append("file", file);
}
}
$.ajax({
url: 'uploadImages3.php',
type: 'post',
data: formdata,
contentType: false,
processData: false,
success: function (response) {
alert(response);
},
});
});
});
and this is my php file
<?php
/* Getting file name */
$filename = $_FILES['file']['name'];
/* Location */
$location = "SavedImages/" . $filename;
$uploadOk = "No Errors";
$imageFileType = pathinfo($location, PATHINFO_EXTENSION);
$extensions = ['jpg', 'jpeg', 'png', 'gif', 'tiff'];
$all_files = count($_FILES['file']['name']);
for ($i = 0; $i < $all_files; $i++) {
$file_name = $_FILES['file']['name'][$i];
$file_tmp = $_FILES['file']['tmp_name'][$i];
$file_type = $_FILES['file']['type'][$i];
$file_size = $_FILES['file']['size'][$i];
$file_ext = strtolower(end(explode('.', $_FILES['file']['name'][$i])));
$file = $path . $file_name;
if (!in_array($file_ext, $extensions)) {
$uploadOk = $uploadOk . 'Extension not allowed: ' . $file_name . ' ' . $file_type;
}
if ($file_size > 2097152) {
$uploadOk = $uploadOk . 'File size exceeds limit: ' . $file_name . ' ' . $file_type;
}
if (file_exists($file)) {
$uploadOk = $uploadOk . 'File already exists: ' . $file_name . ' ' . $file_type;
}
if ($uploadOk != "No Errors") {
echo $uploadOk;
} else {
/* Upload file */
if (move_uploaded_file($_FILES['file']['tmp_name'], $location)) {
echo "File saved";
} else {
echo $uploadOk;
}
}
}
You have:
formdata.append("file", file);
When working with PHP, if you have multiple form fields with the same name, that name must end in [] or only one of them will be available.
Looping over the files manually in the JS is pointlessly overcomplicated though.
Bind the event handler to the submit event of the form
Use the form to populate the FormData object
You also need to prevent the default behaviour - at the moment you are running your JS when the submit button is clicked, but the normal form submission is going to continue and load a new page (killing the JS program as it goes).
Such:
$("form").on("submit", function(e) {
e.preventDefault();
var formdata = new FormData(this);
$.ajax({
url: 'uploadImages3.php',
type: 'post',
data: formdata,
contentType: false,
processData: false,
success: function(response) {
alert(response);
},
});
});
Then your PHP will have an array of files, each of which will have name, etc. It won't have a file, containing an array of names etc.
$_FILES['file']['name'][$i]; should be $_FILES['file'][$i]['name']; and your count method is wrong too.
It's easier to work with a foreach loop though:
foreach ($_FILES['file'] as $file) {
$file_name = $file['name'];
# etc
}

Can't upload multiple files using ajax

First of all this might be a silly question as there are many topics available on this but seriously I am not being able to get it straight and understand how to make it work.
WHAT I AM TRYING TO DO
I am trying to upload multiple files using AJAX and PHP.
PROBLEM
I cant figure out how to pass the data to the PHP script using AJAX.
I don't want to use a form and a submit button for uploading.
Tried using a form and submitting it using jQuery still couldn't make
it.
HTML
<div id="content">
<div id="heading">Upload your files seamlessly</div>
<a href="#"><div id="upload" class="button" title="Upload your files"><i class="fa fa-cloud-upload fa-align-center" aria-hidden="true"></i>
</div></a>
<a href="view.php"><div id="view" class="button" title="View all files on my cloud"><i class="fa fa-eye fa-align-center" aria-hidden="true"></i>
</div></a>
</div>
<form id="fileupload" method="POST" enctype="multipart/form-data">
<input type="file" multiple name="uploadfile[]" id="uploadfile" />
</form>
JS
<script type="text/javascript">
$(document).ready(function(){
$('#upload').click(function(){
$('input[type=file]').click();
return false;
});
$("#uploadfile").change(function(){
//submit the form here
$('#fileupload').submit();
});
});
</script>
PHP
<?php
if(isset($_FILES['uploadfile'])){
$errors= array();
foreach($_FILES['uploadfile']['tmp_name'] as $key => $tmp_name ){
$file_name = $key.$_FILES['uploadfile']['name'][$key];
$file_size =$_FILES['uploadfile']['size'][$key];
$file_tmp =$_FILES['uploadfile']['tmp_name'][$key];
$file_type=$_FILES['uploadfile']['type'][$key];
if($file_size > 2097152){
$errors[]='File size must be less than 2 MB';
}
//$query="INSERT into upload_data (`USER_ID`,`FILE_NAME`,`FILE_SIZE`,`FILE_TYPE`) VALUES('$user_id','$file_name','$file_size','$file_type'); ";
$desired_dir="storage";
if(empty($errors)==true){
if(is_dir($desired_dir)==false){
mkdir("$desired_dir", 0700); // Create directory if it does not exist
}
if(is_dir("$desired_dir/".$file_name)==false){
move_uploaded_file($file_tmp,"$desired_dir/".$file_name);
}
else{ // rename the file if another one exist
$new_dir="$desired_dir/".$file_name.time();
rename($file_tmp,$new_dir) ;
}
//mysql_query($query);
}
else{
print_r($errors);
}
}
if(empty($error)){
echo "Success";
}
}
?>
Any help would be appreciated.
This is a very simple example of what you want to do.
HTML
Wrap your inputs within a form. Why? Because it is the easiest way to do it.
<form action="process.php" method="post">
<input type="file" multiple name="uploadfile[]">
<input type="submit" value="Upload">
</form>
JavaScript
Attach an onsubmit event handler to your form. Use $.ajax() to send a POST request.
Pass your form element i.e. this into the constructor of a FormData object and use it as your data when you send the request as shown below. You need to make sure that you set processData and contentType as false also for this to work.
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
// send request
$.ajax({
url: this.action,
type: this.method,
data: new FormData(this), // important
processData: false, // important
contentType: false, // important
success: function (res) {
alert(res);
}
});
});
});
PHP (process.php)
Let's clean up your PHP.
<?php
// always a good idea to turn on errors during development
error_reporting(E_ALL);
ini_set('display_errors', 1);
$dir = './storage';
$errors = [];
if (isset($_FILES['uploadfile'])) {
$files = $_FILES['uploadfile'];
// create directory if it does not exist
!is_dir($dir) && mkdir($dir, 0700);
// validate & upload files
foreach (array_keys($files['tmp_name']) as $key) {
$file = [
'name' => $files['name'][$key],
'size' => $files['size'][$key],
'tmp_name' => $files['tmp_name'][$key],
'type' => $files['type'][$key],
'error' => $files['error'][$key]
];
// skip if no file was given
if ($file['error'] === UPLOAD_ERR_NO_FILE) {
continue;
}
// get file extension
$file['ext'] = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
// generate a unique name (!)
$file['name'] = uniqid() . '.' . $file['ext'];
// validate
if (!file_exists($file['tmp_name']) ||
!is_uploaded_file($file['tmp_name']) ||
$file['error'] !== UPLOAD_ERR_OK) {
$errors[$key] = 'An unexpected error has occurred.';
} elseif ($file['size'] > 2097152) {
$errors[$key] = 'File size must be less than 2 MB';
// upload file
} elseif (!move_uploaded_file($file['tmp_name'], $dir . '/' . $file['name'])) {
$errors[$key] = 'File could not be uploaded.';
}
}
}
if ($errors) {
print_r($errors);
} else {
echo 'no errors';
}
?>
(!) Do keep in mind that uniqid() is actually not unique.

How to receive & process data sent to php with XMLHttpRequest?

I'm working on upload form for mp3 files and I hit a wall :/. Can you help please?
Here is my HTML:
<form id="file-form" method="POST">
<input class="profileMenu" id="mp3file" name="mp3file" type="file" multiple/>
</form>
<div onclick="test()" class="col-md-1 profileMenu" id="uploadButton">Upload</div>
Here is my JavaScript:
function test() {
var form = document.getElementById('file-form');
var fileSelect = document.getElementById('mp3file');
var uploadButton = document.getElementById('uploadButton');
uploadButton.innerHTML = 'Uploading...';
var files = fileSelect.files;
var formData = new FormData();
for (var i = 0; i < files.length; i++) {
var file = files[i];
formData.append('mp3file', file, file.name);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'php/commercial/upload.php', true);
xhr.onload = function () {
if (xhr.status === 200) {
uploadButton.innerHTML = 'Upload';
}
else {
alert('An error occurred!');
}
};
xhr.send(formData);
}
}
And lastly my PHP:
<?php
$target_path = "uploads/";
$target_path = $target_path . basename( $_FILES['filename']['name']);
if(move_uploaded_file($_FILES['filename']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['filename']['name']). " has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
?>
I'm trying to upload mp3 files to my server and sort them in folders, form validation is going ok, request doesn't return any errors and it seems my php code is not doing what it should be, I know i can do it with submit button without using JavaScript but i need to do it this way. So if any of you have any idea i would be very thankful.

uploading files through html form using javascript calling php

I have an HTML form in which I have to upload 3 files.
I have to call a create.js script after form submission which uses getElementById to format the input in desired way. Then it uses a xmlHTTPRequest to call create.php which inserts the form data into mysql database, and in the mean time fetches some data that it sends back to create.js using json_encode.
So I don't use the form action attribute but instead use the onClick attribute on my Submit button to call create.js.
But I have to upload my 3 files also on clicking Submit. I tried using $_FILE['file1']['name'] and other $_FILE[][] variables, where I use <input type="file" name="file1" id="file1"> to uplaod my first file but it gave the following error:
Undefined index: file1 in C:\xampp\htdocs\mywebsite\sites\all\themes\danland\create.php on line 77
So how can I incorporate my code for storing uploaded files on my server in the same php that returns xmlhttp.responseText to my .js file ?
I also tried putting my code of uploading in upload.php and called it using <form action="the/correct/path/upload.php"> besides using onClick = "my_create.js_function()" in my submit button but it did not work
Note that I have read html upload using ajax and php and know that I cannot upload my file using xmlhttprequest, but I am not trying to do that. I want my xmlhttprequest to fetch data after submit is clicked and my submit button to also store my files.
My HTML form is:
<script src="http://localhost/mywebsite/sites/all/themes/danland/src/create.js">
</script>
<script type="text/javascript" src="http://localhost/mywebsite/sites/all/themes/danland/src/datepickr.js"></script>
<script>
window.onload = create_new_project_getoptions();
</script>
<div class="searchinterfacecontainer">
<p id="my_first_para"></p>
<p id="this_is_my_new_para"></p>
<h2>Enter Details</h2>
<form id="create_projectform1" name="create_projectform1" method="POST" enctype="multipart/form-data" action="http://localhost/mywebsite/sites/all/themes/danland/create_new_project_upload.php">
<input type="text" name="project_id" id="project_id" required/>
<input type="text" name="project_name" id="project_name" required/>
<input id="project_start_date" onClick="new datepickr('project_start_date')" required/>
<select id="project_geography" name="project_geography">
<option value="">Select Country </option>
</select><br/>
<input type="file" name="file1" id="file1">
<input type="file" name="file2" id="file2">
<input type="file" name="file3" id="file3">
<div class="searchinterfacebuttons"><input type="submit" class="searchinterfaceform1go" value="Search" onClick="create_new_project()"/> <button class="searchinterfaceform1go" type="reset" value="Reset"> Reset </button></div>
</form>
</div>
My create.js:
function create_new_project( )
{
alert("entered");
var project_id = document.getElementById("project_id").value;
var project_name = document.getElementById("project_name").value;
var project_start_date = document.getElementById("project_start_date").value;
// some more getElementByID
var error_para = document.getElementById("my_first_para");
var my_error = "";
error_para.innerHTML = my_error;
// some string manipulation with the above defined variables
project_start_date = date_fixer(project_start_date);
project_completion_date = date_fixer(project_completion_date);
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
var params = "project_id=" + project_id + "&project_name=" + project_name ; // + some more parameters
var url = "http://localhost/mywebsite/sites/all/themes/danland/create.php";
xmlhttp.open("POST",url,true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", params.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var val = xmlhttp.responseText;
//alert(val);
var jsonData = JSON.parse(val);
// some manipulation with json data
var answer = document.getElementById("this_is_my_new_para");
answer.innerHTML = jsonData;
}
}
xmlhttp.send(params);
}
function date_fixer(my_date)
{
// code here that works fine
}
My create.php:
<?php
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'this_user');
define('DB_PASSWORD', 'this_password');
define('DB_DATABASE', 'mywebsite');
$project_id = $_POST["project_id"];
$project_name = $_POST["project_name"];
$project_start_date = $_POST["project_start_date"];
// some more $_POST[]
$date_status1 = date_fixer($project_start_date);
$date_status2 = date_fixer($project_completion_date);
//echo "date status 1 is $date_status1 and date_status2 is $date_status2";
if ( $date_status1 == -1 || $date_status2 == -1 ) // not a valid date
{
echo "The date was not in correct format. Please use the date picker";
}
else
{
try
{
$db = new PDO('mysql:host=' .DB_SERVER . ';dbname=' . DB_DATABASE . ';charset=utf8', DB_USERNAME, DB_PASSWORD);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$query_geography = "INSERT into " . DB_TABLE . "( projectID, project_name, start_date) values ( (:pid), (:pname), (:sdate))";
$parameters1 = array(':pid'=>$project_id, ':pname'=>$project_name, ':sdate'=>$project_start_date);
$statement1 = $db->prepare($query_geography);
$statement1->execute($parameters1);
}
catch(Exception $e)
{
echo 'Exception -> ';
var_dump($e->getMessage());
}
}
function date_fixer($my_date)
{
// valid function that works fine
}
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file1"]["name"]);
$extension = end($temp);
print_r($temp);
print_r($extension);
if ( ( ($_FILES["file1"]["type"] == "image/gif") || ($_FILES["file1"]["type"] == "image/jpeg") || ($_FILES["file1"]["type"] == "image/jpg") || ($_FILES["file1"]["type"] == "image/pjpeg") || ($_FILES["file1"]["type"] == "image/x-png") || ($_FILES["file1"]["type"] == "image/png") ) && ($_FILES["file1"]["size"] < 20000) && in_array($extension, $allowedExts) )
{
if ($_FILES["file1"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file1"]["error"] . "<br>";
}
else
{
echo "Upload: " . $_FILES["file1"]["name"] . "<br>";
echo "Type: " . $_FILES["file1"]["type"] . "<br>";
echo "Size: " . ($_FILES["file1"]["size"] / 1024) . " kB<br>";
echo "Temp file: " . $_FILES["file1"]["tmp_name"] . "<br>";
if (file_exists("upload/" . $_FILES["file1"]["name"]))
{
echo $_FILES["file1"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file1"]["tmp_name"], "upload/" . $_FILES["project_file1"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["project_file1"]["name"];
}
}
}
else
{
echo "Invalid file";
}
?>
to get values from $_FILE you have to set form enctype to multipart/form-data.
if you want to read the value of file field then in jQuery simply write $('#id_filefield').val();

Categories

Resources