Hi I am trying to upload multiple files in angularjs. I am not able to upload multiple files as it is giving me error eferenceError: $upload is not defined
This is my html code.
<div class="upload-button" ng-repeat="file in files">
<div class="upload-button-icon">
<img src="images/folder-small.png">
<div class="upload-text">{{file}}</div>
<input type="file" id="file1" name="file1" />
</div>
</div>
<input type="submit" value="{{ 'NEXT' | translate }}" class="blue-button" ng-click="upload()">
Below is my angularjs code to upload file.
$scope.upload = function () {
debugger;
var fileuploadurl = baseurl + 'api/Customer/UploadLeaseFiles/' + LoginID + '/' + "GOSI";
for (var i = 0; i < $scope.files.length; i++) {
var $file = $scope.files[i];
$upload.upload({
url: fileuploadurl,
file: $file,
progress: function (e) {
// wait...
}
})
.then(function (data, status, headers, config) {
alert('file is uploaded successfully');
});
}
alert('file is uploaded successfully');
};
Above code gives me error $upload is not defined. May i know where i am doing wrong in the above code? Any help would be appreciated. Thank you.
Related
We are taking over a site that is using Angular js for a form for data and multi-file upload (up to 4 files).
We are posting to a .php file. I have been able to separate and capture the field data - but can only seem to 'see' one file. If I upload multiple files I 'see' only the last one added to the form.
Can someone please help me to get the files using PHP?
Form HTML (for files):
<ul class="attachments">
<li ng-repeat="attachment in attachments" class="attachment">
{{attachment.name}}
<i class="btn-submit-att-x-hover-off"></i>
</li>
</ul>
<button type="button" class="attachments-button btn btn-default" ngf-select ngf-change="onFileSelect($files)" ngf-multiple="true" ng-if="attachments.length < 4">
<i class="btn-submit-attch"></i>Upload Attachments
</button>
Angular JS Code - for the files as I see:
$scope.attachments = [];
//onFileSelect adds file attachments to the $scope up to the
//configured maximum value.
$scope.onFileSelect = function ($files) {
var MAX_ATTACHMENTS = 4;
for(var i=0; i < $files.length; i++){
if($scope.attachments.length >= MAX_ATTACHMENTS){
break;
}
$scope.attachments.push($files[i]);
}
};
$scope.removeAttachment = function (attachment) {
var index = $scope.attachments.indexOf(attachment);
if (index > -1) {
$scope.attachments.splice(index, 1);
}
};
//POST form data
$scope.upload = Upload.upload({
url: 'forms/pressrelease.html',
method: 'POST',
data: $scope.model,
file: $scope.attachments,
fileFormDataName: "files"
})
.success(function (data, status, headers, config) {
alertSuccess("Your press release has been submitted successfully!");
$scope.showSuccess = true;
}
The only PHP code we've used that has given us anything back - but again - only 1, or the last file name is:
if(isset($_FILES['files'])){
$files = $_FILES['files'];
$sentfilename = $_FILES['files']['name'];
$email_body .= "I see files: $sentfilename<br />";
$tmpsentfile = $_FILES['files']['tmp_name'];
$i=0;
$getfile = $files[0];
$sentfilename = $getfile;
$sentfilesize = $_FILES['files']['size'];
$errormessage = $_FILES['files']['error'];
$email_body .= "I see files: $sentfilename<br />";
}
If anyone one can show us the PHP code we need to use to capture these uploaded files.
Thanks
Create a names array and post the dynamic file names:
var names = []
foreach file:
names.push(files[i].name)
in upload:
method: 'POST',
data: $scope.model,
file: $scope.attachments,
fileFormDataName: names
I am using kendo to upload files from the client everything is working as expected while loading , But here i have question related to url when we upload files i am using url in the config when file loads succesfully i have response from the server.
How can i extract data from response using kendo async saveUrl method ?
main.html
<div class="form-group col-md-6">
<div class="col-md-6">
<label for="prcFileUploadField">File:</label>
</div>
<div class="col-md-6">
<input name="file" type="file" kendo-upload="fileAttachment" k-upload="addMorePostParameters" k-success="onSuccess" k-error="onError" k-options="fileAttachmentOptions" k-select="onSelect" k-remove="onUploadRemove" />
</div>
</div>
ctrl.js
angular.module('App').controller('PrcUploadCtrl',function($scope,$timeout,$rootScope,prcUploadConfig){
'use strict';
var fileData = [];
$scope.fileAttachmentOptions = prcUploadConfig.fileAttachmentConfig;
$scope.prcUploadGridOptions = prcUploadConfig.getPrcUploadDataGrid;
prcUploadConfig.getPrcUploadDataGrid.dataSource='';
$scope.onSelect = function (e) {
fileData = e.files;
var message = $.map(e.files, function(file) { return file.name; }).join(", ");
console.log(message);
console.log(JSON.stringify(fileData));
};
//if error
$scope.onError = function() {
console.log("loggin error");
$timeout(function () {
var filesToBeRemoved = $scope.fileAttachment.wrapper.find('.k-file');
$scope.fileAttachment._removeFileEntry(filesToBeRemoved);
},5000);
}
});
config.js
fileAttachmentConfig: {
async: {
saveUrl: 'app/upload/uploadAttch',
removeUrl: 'remove',
removeVerb: 'DELETE',
autoUpload: false
},
template: '<span class=\'file-name-heading\'>Name:</span> <span>#=name#</span><button type=\'button\' class=\'k-upload-action\'></button>'
}
You can always get a response body from successful requests like this:
$scope.onSuccess = function(e) {
var response = e.response;
//...
}
I am trying to send image to server with some additional data. My issue is that the image is not getting saved on server where other recordings are.
below is my .html code :
<div class="widget uib_w_4 d-margins" data-uib="media/file_input" data-ver="0">
<input type="file" name="image" id="image"
accept="image/jpeg, image/png, image/gif"
ng-model="image" class="ng-pristine ng-untouched ng-valid">
</div>
<div class="widget uib_w_5 d-margins" data-uib="media/text" data-ver="0">
<div class="widget-container left-receptacle"></div>
<div class="widget-container right-receptacle"></div>
<div>
<p>Username:</p>
</div>
</div>
JS code
< script >
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$scope.SendData = function()
var data = $.param({
image: $scope.image,
username: $scope.username,
});
var config = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded;
charset = utf - 8;
'
}
}
var param = getParameterByName('id');
$http.post('myrurl.php', data, config)
.success(function(data, status, headers, config) {
window.location.href = 'view.html';
})
.error(function(data, status, header, config) {
alert('Please retry');
});
};
});
< /script>
I tried to to print the value in PHP using print_r($_REQUEST);
The value of image is null.
How can I send my image to the server?
Pretty easy. A good approach can be to Base64 encode the image, then send that Base64 to the server; the best part is that PHP natively supports decoding Base64.
You can do something like:
<!-- In your HTML file -->
<input type="file" id="file" />
<input type="submit" ng-click"uploadFile" value="Upload File"/>
Then, in your JavaScript:
$("#file").on('change', function(event) {
var reader = new FileReader();
reader.onload = function( loadEvent ) {
$scope.fileData = loadEvent.target.result;
$scope.$apply();
};
reader.readAsDataURL( event.target.files[0] );
});
$scope.uploadFile = function() {
if ( $scope.fileData === null || $scope.fileData === "" || !($scope.fileData) ) {
alert("No file has been uploaded");
return;
}
var dtx = eval("(" + atob($scope.fileData.substring("data:application/json;base64,".length)) + ")");
$http.get( 'yourScript.php?data=' + encodeURIComponent( JSON.stringify(dtx) ) ).then( function(response) {
if( response.data.status_code == 200 ) {
// Done!
} else { ERROR }
});
};
Lastly, in your PHP file you can:
$imageData = base64_decode( $_GET[ 'data' ] ); // Now you have a binary image file. Do whatever you want!
What do I need to add to my code here to add the ability to upload a video?
<div id="title">Upload Videos</div>
<div class="vidUpload">
<form id="vidUpload" enctype="multipart/form-data">
<input name="vidName" type="text" required="required" id="vidName" placeholder="Enter Video Name Here" title="Video Name">
<br>
<textarea name="videoDescription" id="videoDescription" required class="videoDescription" placeholder="Enter Video Description Here" title="Enter Video Description Here"></textarea>
<select name="select" required class="choosevidCat" id="choosevidCat">
<option value="">Choose the Catagory for your Video Here</option>
<?php
$sql = ("SELECT albumId, albumName, albumSelect FROM albums");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($mysqli, $sql);
while($row = mysqli_fetch_array($result)) {
$albumid = ($row['albumId']);
$album_name = ($row['albumName']);
$album_name1 = ($row['albumSelect']);
echo "<option value=".$album_name1. ">$album_name</option>";
}
?>
<option id="createCat" value="createCatagory">Create New Catagory Here</option>
</select>
<input type="file" name="video" id="video">
<input type="button" name="videoToUpload" id="videoToUpload" value="Upload">
</form>
<div id="loader"></div>
<div id="viduploadResult"></div>
jquery
<script type="text/javascript">
$(document).ready(function() {
$("#videoToUpload").click(function() {
var vidName = $("#vidName").val();
var videoDescription = $("#videoDescription").val();
var albumName1 = $("#choosevidCat").val();
var vidFile =$("#video").val();
// Put an animated GIF image insight of content
$("#loader").empty().html('<img src="/images/loader.gif" class="vidloader1"/>');
$.post("includes/vid_upload.inc.php",{vidName: vidName, videoDescription: videoDescription, albumName1: albumName1, vidFile: vidFile}, function(json)
{
if(json.result === "success") {
$("#viduploadResult").html( "The Video "+vidName+" has been Uploaded!");
// // First remove all the existing options
// $('#choosevidCat').empty();
//
// // Load the content:
// $('#choosevidCat').load(location.href + "#choosevidCat > *");
}else{
$("#viduploadResult").html(json.message);
}
});
});
})
</script>
I have spent hours looking at API's like blueimp etc, I just want to upload a video file and put it on my server from the form I have here.
Any help would be greatly appreciated
You are just passing the value of input type file. You should pass the file stream to your server script. Here is a sample code for uploading files using jquery.
Note: I am writing only jquery code to submit file. You must have to write server side code (PHP script) to upload the requested file.
Following code will help you to upload files. Customize it according to your scenario
if($("#video")[0].files.length)
{
this.total_files = $("#video")[0].files.length;
this.start_process = 0;
$.each($("#video")[0].files, function(i,o){
var files = new FormData();
files.append(1, o);
});
$.ajax({
url:"http://example.com",
method:"POST",
contentType:false,
processData: false,
data:files,
async:true,
xhr: function()
{
if(window.XMLHttpRequest)
{ var xhr = new window.XMLHttpRequest();
//Upload progress
xhr.upload.addEventListener("progress", function(evt){
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
//Do something with upload progress
}
}, false);
}
},
success:function(data){
alert("file uploaded..");
}
});
}
After further research I found this script and video tutorial which provided a resolution, so thought I would add it to my own question
Web Tutorial
https://www.developphp.com/video/JavaScript/File-Upload-Progress-Bar-Meter-Tutorial-Ajax-PHP
Video Tutorial
http://www.youtube.com/watch?v=EraNFJiY0Eg
I am using dropzone.js for uploading the file in .aspx application
So Can we get Image property(Like Image height and width) after uploading file for doing some client side animation
Javascript
$(document).ready(function () {
$(".dropzone").dropzone({
url: 'BatchUpload_New.aspx',
paramName: "files", // The name that will be used to transfer the file
maxFilesize: 102, // MB
enqueueForUpload: false,
accept: function (file, done) {
return done();
}
});
});
.aspx
<div id="frmMain" runat="server" class="dropzone">
<div>
<div class="fallback">
<input name="file" type="file" multiple />
</div>
Code Behind
foreach (string s in Request.Files)
{
HttpPostedFile file = Request.Files[s];
if (file != null)
{
string fileExtension = "";
if (!string.IsNullOrEmpty(file.FileName))
{
fileExtension = Path.GetExtension(file.FileName);
}
// IMPORTANT! Make sure to validate uploaded file contents, size, etc. to prevent scripts being uploaded into your web app directory
string savedFileName = Path.Combine(#"C:\Temp\", Guid.NewGuid()+ fileExtension);
file.SaveAs(savedFileName);
lbTtest.Text += " " + file.FileName;
}
Dropzone adds data to the file object you can use when events fire. You can access file.width and file.height if it's an image, as well as file.upload which is an object containing: progress (0-100), total (the total bytes) and bytesSent.