I need to upload multiple files to a server using an ajax call.
Here is the code, every-time I am using it I am getting an upload error. The post is not working in the html side.
Below is the code I have used in html and php.
HTML
<input name="fileToUploadName" id="fileinput0" type='file' />
<input name="fileToUploadName" id="fileinput1" type='file' />
<input name="fileToUploadName" id="fileinput2" type='file' />
JS
function upload(){
var formdata = new FormData();
var image0 = $('#fileinput0')[0].files[0];
if(image0)
formdata.append('fileToUpload[]',image0);
var image1 = $('#fileinput1')[0].files[0];
if(image1)
formdata.append('fileToUpload[]',image1);
var image2 = $('#fileinput2')[0].files[0];
if(image2)
formdata.append('fileToUpload[]',image2);
$.ajax({
url: 'server.php',
type: 'POST',
data: formdata,
async: true,
dataType: "text",
success: function (data) {
alert(data);
},
error: function(jqXHR, textStatus, errorThrown){
var p =0;
alert("Error uploading data");
},
cache: false,
contentType: false,
processData: false
});
}
server.php
if(isset($_POST['submit']))
{
$uploaddir = 'uploads/';
foreach ($_FILES['fileToUpload']['error'] as $key => $error)
{
if ($error == UPLOAD_ERR_OK)
{
$tmp_name = $_FILES['fileToUpload']['tmp_name'][$key];
$name = $_FILES['fileToUpload']['name'][$key];
$uploadfile = $uploaddir . basename($name);
if (move_uploaded_file($tmp_name, $uploadfile))
{
echo "Success: File ".$name." uploaded.<br/>";
}
else
{
echo "Error: File ".$name." cannot be uploaded.<br/>";
}
}
}
}
But every time I am getting an upload error.
Your problem is here, in your JavaScript file:
url: 'serever.php';
This should be
url: 'server.php';
This is, however, a simple typographical error.
Related
With this code I want to insert and move a file into a folder but when I choose a file and upload it shows me an error in my console:
Uncaught TypeError: Failed to construct 'FormData': parameter 1 is not of type 'HTMLFormElement'.
How can I solve this problem? Please help me. Thank You
<input type="file" id="multiFiles" name="files" />
<button id="upload_file_multiple" class="btn btn-success add-btn update-btn">Upload</button>
$("#upload_file_multiple").click(function(event) {
event.preventDefault();
var form_data = new FormData($("#multiFiles"));
var id = "<?php echo $this->uri->segment(3) ?>";
jQuery.ajax({
type: "POST",
url: "<?php echo base_url() ?>syllabus/UploadFile/" + id,
data: form_data,
processData: false,
contentType: false,
success: function(response) {
$('#afx_khjk').html(response);
},
error: function(response) {
$('#afx_khjk').html(response);
}
});
});
public function UploadFile($id)
{
if (isset($_FILES['files']) && !empty($_FILES['files']))
{
$rename = 'file_no-'.time().$_FILES["files"]["name"];
move_uploaded_file($_FILES["files"]["tmp_name"], 'uploads/syllabus/' . $rename);
$data = array(
'pdf'=>$rename,
'subjectID'=>$id,
'unique_id'=>time()
);
$this->db->insert('sylabus_pdf',$data);
$insert_id = $this->db->insert_id();
echo 'File successfully uploaded : uploads/syllabus/' . $rename . ' ';
$this->commondata($id);
}
else
{
echo 'Please choose at least one file';
}
}
The error is because the FormData constructor expects an FormElement object, not a jQuery object containing an input.
To fix this create the FormData object with the empty constructor and use append() to add your file:
var input = document.querySelector('#multiFiles');
var form_data = new FormData();
for (var i = 0; i < input.files.length; i++) {
form_data.append('files[]', input.files[i]);
}
Alternatively you can make this more simple by providing the form to the constructor. That way the data in all form controls will be included for you automatically.
var form_data = new FormData($('#yourForm')[0]);
HTML
<form id="frm_upload_file">
<input type="file" id="multiFiles" name="files" />
<button type="submit" id="upload_file_multiple" class="btn btn-success add-btn update-btn">Upload</button>
</form>
Ajax
$("#frm_upload_file").submit(function (event) {
event.preventDefault();
var id = "<?php echo $this->uri->segment(3) ?>";
var form_data = new FormData(this);
jQuery.ajax({
type: "POST",
url: "<?php echo base_url() ?>syllabus/UploadFile/" + id,
data: form_data,
cache: false,
contentType: false,
processData: false,
success: function (response) {
$('#afx_khjk').html(response);
},
error: function (response) {
$('#afx_khjk').html(response);
}
});
});
I have a form in which I have a field for name and dropzone. So if I go with simple one like to upload files in main upload folder then it is working but I want to upload files in child folder like I am getting folder name through <input type="text" name="name" /> and on upload file should go to new generated folder.
HTML:
<input type="text" name="name" class="form-control fl_name" />
<div class="dropzone"></div>
JS:
// CREATE FOLDER FOR FILE UPLOADS
$('.name-alert').hide();
$('.fl_name').on('change', function() {
var fl_name = 'name='+ $(this).val();
var fl_url = $(this).closest('form').attr('action');
$.ajax({
type: 'POST',
url: fl_url,
data: fl_name,
cache: false,
success: function(result){
if (result == '0') {
$('.name-alert').slideDown();
setTimeout(function() {
$('.name-alert').slideUp();
}, 2000);
}
}
});
});
// CREATE DROPZONE ENVIORMENT
var myDropzone = new Dropzone('div.dropzone', {
url: "http://localhost/build/assets/php/customer-query.php",
addRemoveLinks: true,
init: function() {
this.on('success', function( file, resp ){
var fl_name = 'name='+ $('.fl_name').val();
var fl_url = 'http://localhost/build/assets/php/customer-query.php';
$.ajax({
type: 'POST',
url: fl_url,
data: fl_name,
cache: false,
success: function(result){
console.log(result);
}
});
});
},
});
PHP:
// Create Folder On Input Field Change
$fname = $_POST['name'];
if (!file_exists('../uploads/'.$fname.'/')) {
mkdir('../uploads/'.$fname.'/', 0777, true);
} else {
echo '0';
}
// Upload Files
$fl_name = $_POST['name'];
$ds = DIRECTORY_SEPARATOR;
$storeFolder = '../uploads/'.$fl_name.'/';
if (!empty($_FILES)) {
$tempFile = $_FILES['file']['tmp_name'];
$targetPath = dirname( __FILE__ ) .$ds. $storeFolder .$ds;
$targetFile = $targetPath. $_FILES['file']['name'];
move_uploaded_file($tempFile,$targetFile);
}
in my code files are still uploading in main folder instead of new folders.
Thanks
Your "data" in the ajax call doesn't look like a json object. Try changing it to:
$.ajax({
type: 'POST',
url: fl_url,
data: {'name':fl_name},
dataType: "json",
cache: false,
success: function(result){
console.log(result);
}
});
See Passing data with jquery ajax if you need a further example on passing data with json via ajax
You may also be missing the following in your php file to read the json input:
$inputJSON = file_get_contents("php://input");
$result = json_decode($inputJSON,TRUE);
in which case you need to change
$fname = $_POST['name'];
to
$fname = $result['name'];
I am using codeigniter 3.1 . I want to post upload data using ajax.
Ajax upload file not working. But when i post the simple form without ajax, it working fine.
I don't know why but no error in console.
HTML
<?php echo form_open_multipart(site_url("upload/post"), ['id' => 'uploader']) ?>
<input type="file" name="userfile" value="">
<input type="submit" value="Submit" />
<?php echo form_close() ?>
JAVASCRIPT
$('#uploader').submit(function (event) {
event.preventDefault();
$.ajax({
url: window.location.href + '/post',
type: "POST",
dataType: 'json',
data: new FormData(this)
});
});
CONTROLLERS
public function post()
{
$this->load->helper('url');
$this->load->helper('form');
$this->load->library("upload");
$file = $this->common->nohtml($this->input->post("userfile"));
$this->upload->initialize(array(
"upload_path" => 'upload',
"overwrite" => FALSE,
"max_filename" => 300,
"encrypt_name" => TRUE
));
$this->upload->do_upload('userfile');
$data = $this->upload->data();
$image_file = $data['file_name'];
}
Another approach to this would be passing to PHP the file encoded in base64:
get the selected file from #userfile field using $('#userfile').prop('files')[0];
transform the contents of that file into a base64 encoded string using FileReader.readAsDataURL(). We're going to call this content; Here's a similar question showing how to do and expanding the answer & possibilities;
send the AJAX passing both the filename and content strings;
now on CI, fetch the POST data;
base64_decode() the content;
fwrite() the result into a file using the filename.
That way also you could avoid POSTing all form fields.
try this..
Post data using FormData() formdata post file also.
To get all your form inputs, including the type="file" you need to use FormData object.
$('#post').on('click', function (e) {
var file_data = $("#userfile").prop("files")[0];
var form_data = new FormData();
form_data.append("userfile", file_data)
$.ajax({
url: window.location.href+'/post',
type: 'POST',
data: form_data,
async: false,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
return false;
});
For more...https://abandon.ie/notebook/simple-file-uploads-using-jquery-ajax
One of the issues is that file uploading uses a different mechanism than the other form <input> types. That is why $this->input->post("userfile") isn't getting the job done for you. Other answers have suggested using javascript's FormData and this one does too.
HTML
A very simple form for picking a file and submitting it. Note the change from a simple button to <input type="submit".... Doing so makes it a lot easier for the javascript to use the FormData object.
FormData documentation
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script src="https://code.jquery.com/jquery-2.2.2.js"></script>
<title>Upload Test</title>
</head>
<body>
<?= form_open_multipart("upload/post", ['id' => 'uploader']); ?>
<input type="file" name="userfile">
<p>
<input type="submit" value="Upload">
</p>
<?php echo form_close() ?>
<div id="message"></div>
<script>
$('#uploader').submit(function (event) {
event.preventDefault();
$.ajax({
url: window.location.href + '/post',
type: "POST",
dataType: 'json',
data: new FormData(this),
processData: false,
contentType: false,
success: function (data) {
console.log(data);
if (data.result === true) {
$("#message").html("<p>File Upload Succeeded</p>");
} else {
$("#message").html("<p>File Upload Failed!</p>");
}
$("#message").append(data.message);
}
});
});
</script>
</body>
</html>
JAVASCRIPT
Use FormData to capture the fields.
Note that instead of handling the button click we handle the submit event.
$('#uploader').submit(function (event) {
event.preventDefault();
$.ajax({
url: window.location.href + '/post',
type: "POST",
dataType: 'json',
data: new FormData(this),
processData: false,
contentType: false,
success: function (data) {
//uncomment the next line to log the returned data in the javascript console
// console.log(data);
if (data.result === true) {
$("#message").html("<p>File Upload Succeeded</p>");
} else {
$("#message").html("<p>File Upload Failed!</p>");
}
$("#message").append(data.message);
}
});
});
CONTROLLER
I've added some code that "reports" results to ajax and will display it on the upload page.
class Upload extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->helper(['form', 'url']);
}
public function index()
{
$this->load->view('upload_v');
}
public function post()
{
$this->load->library("upload");
$this->upload->initialize(array(
"upload_path" => './uploads/',
'allowed_types' => 'gif|jpg|png|doc|txt',
"overwrite" => FALSE,
"max_filename" => 300,
"encrypt_name" => TRUE,
));
$successful = $this->upload->do_upload('userfile');
if($successful)
{
$data = $this->upload->data();
$image_file = $data['file_name'];
$msg = "<p>File: {$image_file}</p>";
$this->data_models->update($this->data->INFO, array("image" => $image_file));
} else {
$msg = $this->upload->display_errors();
}
echo json_encode(['result' => $successful, 'message' => $msg]);
}
}
This will upload your file. Your work probably isn't done because I suspect that your are not saving all the file info you need to the db. That, and I suspect you are going to be surprised by the name of the uploaded file.
I suggest you study up on how PHP handles file uploads and examine some of the similar codeigniter related questions on file uploads here on SO.
Controller
public function upload()
{
$this->load->library('upload');
if (isset($_FILES['myfile']) && !empty($_FILES['myfile']))
{
if ($_FILES['myfile']['error'] != 4)
{
// Image file configurations
$config['upload_path'] = './upload/';
$config['allowed_types'] = 'jpg|jpeg|png';
$this->upload->initialize($config);
$this->upload->do_upload('myfile');
}
}
}
View
<form id="myform" action="<?php base_url('controller/method'); ?>" method="post">
<input type="file" name="myfile">
("#myform").submit(function(evt){
evt.preventDefault();
var url = $(this).attr('action');
var formData = new FormData($(this)[0]);
$.ajax({
url: url,
type: 'POST',
data: formData,
processData: false,
contentType: false,
success: function (res) {
console.log(res);
},
error: function (error) {
console.log(error);
}
}); // End: $.ajax()
}); // End: submit()
Let me know if any query
you need to submit the form not on click but on submit ... give the form an id and then on submit put ajax
HTML
<?php $attributes = array('id' => 'post'); ?>
<?php echo form_open_multipart(site_url("upload/post",$attributes), ?>
<input type="file" id="userfile" name="userfile" value="">
<button id="post">Submit</button>
<?php echo form_close() ?>
JAVASCRIPT
$('#post').on('submit', function () {
var formData = new FormData();
formData.append("userfile",$("#userfile")[0].files[0]);
$.ajax({
url: window.location.href+'/post',
type: "POST",
data: formData
});
CONTROLLERS
public function post()
{
$this->load->library("upload");
$file = $this->common->nohtml($this->input->post("userfile"));
$this->upload->initialize(array(
"upload_path" => 'upload',
"overwrite" => FALSE,
"max_filename" => 300,
"encrypt_name" => TRUE,
));
$data = $this->upload->data();
$image_file = $data['file_name'];
$this->data_models->update($this->data->INFO, array(
"image" => $image_file
)
);
}
I am trying to upload a file (PDF) by AJAX to my server to be handled by a php script in a laravel project. I cannot get the file to send and be received on the server.
In the network I can see that the POST request is getting a 200 response, however it is returning a response of 'file not present', which is the response from laravel.
Also in the post request the Request Payload contains the following
------WebKitFormBoundaryliAmA3wxs0bB32iZ--
Please see the js and html and php below:
html
<form enctype="multipart/form-data">
<input type="file" id="cv" name="cv"/>
<button id="file-send">Add</button>
</form>
js
$('#file-send').bind('click', function () {
$.ajax({
url:"test",
data: new FormData($("#cv")[0]),
type:'POST',
processData: false,
contentType: false,
success:function(response){
console.log(response);
},
});
});
LARAVEL CODE
public static function uploadingFile(){
if (Input::hasFile('cv'))
{
return "file present";
}
else{
return "file not present";
}
Try this:
JS:
$('#file-send').on('click', function() {
var file_data = $('#pic').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url : 'upload.php', // point to server-side PHP script
dataType : 'text', // what to expect back from the PHP script, if anything
cache : false,
contentType : false,
processData : false,
data : form_data,
type : 'post',
success : function(output){
alert(output); // display response from the PHP script, if any
}
});
$('#pic').val(''); /* Clear the file container */
});
Php:
<?php
if ( $_FILES['file']['error'] > 0 ){
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
if(move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']))
{
echo "File Uploaded Successfully";
}
}
?>
Try This Plugin to upload file
http://malsup.com/jquery/form/#file-upload
var options = {
beforeSubmit: showRequest,
success: showResponse,
dataType :'json'
};
$('#file-send').ajaxSubmit(options);
function showRequest()
{
//before uploading file
}
function showResponse()
{
//response after uploading file
}
My form is -
<form id="fileupload" method="post" enctype="multipart/form-data">
<input type="file" id="headerimage" spellcheck="true" class="typography" name="headerimage">
</form>
My ajax code is -
var fileData = new FormData($('#fileupload'));
fileData.append('imagefile', $('#headerimage')[0].files);
$.ajax({
type : 'post',
data : fileData,
url : 'UploadImage.php',
dataType: 'json',
processData: false,
success : function(data)
{
alert("done");
},
});
Php code -
<?php
# Data Base Connection
require_once('conn/dbConn.php');
var_dump($_REQUEST);
if (!empty($_FILES)) {
var_dump($_FILES);
}
Please Help. On the php page i am not getting file data.
HTML CODE:
<form id="fileupload" method="post" enctype="multipart/form-data">
<input name="userImage" id="uploadForm" type="file" class="inputFile" />
</form>
AJAX :
<script type="text/javascript">
$(document).ready(function (e){
$("#fileupload").on('submit',(function(e){
e.preventDefault();
$.ajax({
url: "UploadImage.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data){
$("#targetLayer").html(data);
},
error: function(){}
});
}));
});
</script>
Use this javascript
$(document).on("submit", "#fileupload", function(event)
{
event.preventDefault();
$.ajax({
url: 'UploadImage.php',
type: 'POST',
data: new FormData(this),
dataType: 'json',
processData: false,
contentType: false,
success: function (data, status)
{
}
});
});
Try this...
//Image will upload without submit form
<form id="uploadimage" action="" method="post" enctype="multipart/form-data">
<div id="image_preview"><img id="previewing" src="noimage.png" /></div>
<hr id="line">
<div id="selectImage">
<label>Select Your Image</label><br/>
<input type="file" name="file" id="file" required />
</div>
</form>
<script>
$(document).ready(function (e) {
$("#uploadimage").on('change',(function(e) {
e.preventDefault();
$.ajax({
url: "UploadImage.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function(data) // A function to be called if request succeeds
{
}
});
}));
});
</script>
UploadImage.php
<?php
if(isset($_FILES["file"]["type"]))
{
$validextensions = array("jpeg", "jpg", "png");
$temporary = explode(".", $_FILES["file"]["name"]);
$file_extension = end($temporary);
if ((($_FILES["file"]["type"] == "image/png") || ($_FILES["file"]["type"] == "image/jpg") || ($_FILES["file"]["type"] == "image/jpeg")
) && ($_FILES["file"]["size"] < 100000)//Approx. 100kb files can be uploaded.
&& in_array($file_extension, $validextensions)) {
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br/><br/>";
}
else
{
if (file_exists("upload/" . $_FILES["file"]["name"])) {
echo $_FILES["file"]["name"] . " <span id='invalid'><b>already exists.</b></span> ";
}
else
{
$sourcePath = $_FILES['file']['tmp_name']; // Storing source path of the file in a variable
$targetPath = "upload/".$_FILES['file']['name']; // Target path where file is to be stored
move_uploaded_file($sourcePath,$targetPath) ; // Moving Uploaded file
}
}
}
else
{
echo "<span id='invalid'>***Invalid file Size or Type***<span>";
}
}
?>
JS code -
var form = document.getElementById('fileupload');
var fileInput = document.getElementById('headerimage');
var file = fileInput.files[0];
var formData = new FormData();
var filename = '';
formData.append('file', file);
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
filaname = xhr.responseText;
}
}
// Add any event handlers here...
xhr.open('POST', form.getAttribute('action'), true);
xhr.send(formData);
PHP code -
<?php
# Data Base Connection
require_once('conn/dbConn.php');
if (!empty($_FILES)) {
$file = $_FILES;
if ($file['file']['error'] == 0) {
$name = explode('.', $file['file']['name']);
$newName = "header.".$name[count($name)-1];
if (move_uploaded_file($file['file']['tmp_name'], "../assets/Themes/Default/".$newName)) {
echo $newName;
exit;
}
} else {
echo "";
exit;
}
} else {
echo "";
exit;
}