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;
//...
}
Related
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.
I have a postback that should refresh my page and reload page. When the page reloads it should display an image or an uploaded link or an uploaded document link or something. This works great when I run locally, but when I have deployed the same code to my host server, the page reloads with blanks, and the user must hit refresh to see the results. the following code snippet asks the user to upload an image, and then performs an update:
markup:
<form id="updateLogo" enctype="multipart/form-data">
<div class="container">
<div class="row">
<div class="col-lg-6 col-md-12">
<h5 class="red"><b>(Image sizes are limited to 1 Megabyte)</b></h5>
Select File:
<input class="form-control" type="file" name="file" id="file" required="required" />
<input class="form-control" type="hidden" name="communityId" id="communityId" value="#ViewBag.CommunityId" />
</div>
<div class="col-lg-6 col-md-12">
Current Profile Image:
<img src="#ViewBag.LogoImage" class="img-responsive img-circle" style="width:150px; height:150px" />
</div>
</div>
<div class="row">
<div class="col-lg-6 col-md-12">
<input type="submit" value="Upload Image" class="btn btn-habitat" id="updtLogo">
</div>
</div>
</div>
</form>
javascript with ajax :
$("#updtLogo").click(function () {
// Host
var hostname = location.hostname;
var host = '#System.Configuration.ConfigurationManager.AppSettings["hostroot"]';
if (hostname == "localhost")
host = "";
// New Form data including the newly uploaded file
var formSerialized = $("#updateLogo").serializeArray();
var formdata = new FormData();
var logofile = $("#file")[0].files[0];
// Supporting Assets (i.e. uploaded files go here)
for (i = 0; i < $("#file")[0].files.length; i++) {
formdata.append("File", $("#file")[0].files[i]);
}
$.each(formSerialized, function (i, field) {
formdata.append(field.name, field.value);
});
var communityId = $("#communityId").val();
var fileLogo = $("#file").val();
// Only allow if file size is less than 1MB
if (logofile.size < (1024 * 1024)) {
$.ajax({
type: "POST",
url: host + "/Communities/UploadLogo/" + communityId + "?logo=" + fileLogo,
contentType: false,
processData: false,
data: formdata,
success: function () {
console.log('success!!');
}
});
window.location.reload();
} else {
var errorMsg = 3;
$(".modal-dialog").css({
"left": 0,
"top": 200,
});
$(".modal-body").css({
"background-color": "green"
})
$(".modal-title").text("Error Uploading Logo Image");
var url = host + "/Communities/ErrorMessageDialog/" + communityId + "?errorMsg=" + errorMsg;
$("#inviteDialog").load(url, function () {
$("#inviteModal").modal("show");
})
}
return false;
});
MVC ActionResult
[HttpPost]
[Authorize]
public ActionResult UploadLogo(int id, string logo)
{
// Uploaded data files go here
HttpPostedFileBase file = Request.Files[0];
var logoFile = file.FileName != null ? file.FileName : logo;
if (logoFile != null || logoFile != "")
{
var fileName = Path.GetFileName(logoFile);
var host = ConfigurationManager.AppSettings["hostroot"];
if (System.Web.HttpContext.Current.Request.IsLocal)
host = "";
var communityId = id;
// var fileName = file.FileName;
var directory = Server.MapPath("~/CommunityStorage/" + communityId + "/Logo/");
var virtualPath = host + "/CommunityStorage/" + communityId + "/Logo/";
// Create a new directory for the community if it does not exist based on their community id
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
var path = Path.Combine(directory, fileName);
file.SaveAs(path);
// Save file path to the Communities Table
var community = db.Communities.Where(x => x.CommunityId == communityId).SingleOrDefault();
if (community == null)
return RedirectToAction("Index", "login");
// Update the Logo in the communities table
community.LogoPath = virtualPath + fileName;
db.SaveChanges();
}
return View();
}
From the comments:
the typical pattern for ajax follows as:
$.ajax({ ... success: function(data) { /* Do stuff here */ } });
If you are looking to reload the page after you receive your data do so in the callback like so:
$.ajax({
...
success: function(data) {
window.location.reload();
}
});
Be careful when reloading the page: JavaScript data doesn't persist after page reload unless you're using cookies / caching.
I have been searching online looking for the answer to this problem but I cannot seem to find anything that works, I have the following Controller code:
[HttpPost]
public ActionResult UploadFiles()
{
// If files exist
if (Request.Files != null && Request.Files.Count > 0)
{
// ** Do stuff
return Json(new { result = true, responseText = "File(s) uploaded successfully" });
}
// Return no files selected
return Json(new { result = false, responseText = "No files selected" });
}
And following code in my cshtml page which works fine and the controller can see the files that I upload:
<input type="file" name="files" id="files" accept="image/*;capture=camera" multiple>
<button type="button" onclick="submitform()">Submit</button>
<script>
function submitform(){
// Get files from upload
var files = $("#files").get(0).files;
// Create form data object
var fileData = new FormData();
// Loop over all files and add it to FormData object
for (var i = 0; i < files.length; i++) {
fileData.append(files[i].name, files[i]);
}
// Send files to controller
var xhr = new XMLHttpRequest();
xhr.open("POST", "/Quotes/QuoteFiles/UploadFiles", false);
xhr.send(fileData);
}
</script>
However when I try and change this to work using an Ajax call as shown below then Request.Files in the Controller always has no files. The only bit I have changed is the "Send files to controller" part:
<input type="file" name="files" id="files" accept="image/*;capture=camera" multiple>
<button type="button" onclick="submitform()">Submit</button>
<script>
function submitform(){
// Get files from upload
var files = $("#files").get(0).files;
// Create form data object
var fileData = new FormData();
// Loop over all files and add it to FormData object
for (var i = 0; i < files.length; i++) {
fileData.append(files[i].name, files[i]);
}
// Send files to controller
$.ajax({
url: '/Quotes/QuoteFiles/UploadFiles',
type: "POST",
contentType: false, // Not to set any content header
processData: false, // Not to process data
data: fileData,
success: function (result) {
alert(result);
},
error: function (err) {
alert(err.statusText);
}
});
}
</script>
I am running this in Google Chrome but I have tried IE 11 and Edge but not of them work. Can anyone tell me what I am doing wrong?
try using a fileReader instead of a formData and change the mimetype to 'text/plain; charset=x-user-defined-binary'
https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications#Example_Uploading_a_user-selected_file
I have finally found what was causing this issue, I have the following code on my _Layout.cshtml page which is there to automatically send the AntiForgeryToken on any ajax requests I make, this appears to be causing the problem because once I remove it Request.Files is not empty. I now need to see if I can find a way to add this code back in where it will not stop file uploads working:
$(document).ready(function () {
var securityToken = $('[name=__RequestVerificationToken]').val();
$(document).ajaxSend(function (event, request, opt) {
if (opt.hasContent && securityToken) { // handle all verbs with content
var tokenParam = "__RequestVerificationToken=" + encodeURIComponent(securityToken);
opt.data = opt.data ? [opt.data, tokenParam].join("&") : tokenParam;
// ensure Content-Type header is present!
if (opt.contentType !== false || event.contentType) {
request.setRequestHeader("Content-Type", opt.contentType);
}
}
});
});
**** EDIT ****
I have now reworked this as shown below to add 'if(opt.data != "[object FormData]"' which resolves the issue by not calling the code if it is a file upload:
$(document).ready(function () {
var securityToken = $('[name=__RequestVerificationToken]').val();
$(document).ajaxSend(function (event, request, opt) {
if (opt.hasContent && securityToken) { // handle all verbs with content
// If not "FormData" (i.e. not a file upload)
if (opt.data != "[object FormData]")
{
var tokenParam = "__RequestVerificationToken=" + encodeURIComponent(securityToken);
opt.data = opt.data ? [opt.data, tokenParam].join("&") : tokenParam;
// ensure Content-Type header is present!
if (opt.contentType !== false || event.contentType) {
request.setRequestHeader("Content-Type", opt.contentType);
}
}
}
});
});
I'm trying to update a module without uploading a new image. The problem is that if I do not upload a new image and instead try and use the image that i read back from the api then it says read.result is undefined when debugging. I think the reader is expecting an image stream and i'm giving it a url. Not sure how to fix this.
The API takes a DataURL which is the image, then stores it and puts image path/url in ImageURLPATH.
Code:
angular.module('Services.modulesPUT', [])
.service('modulesPUTSrvc', function (baseSrvc, $http,modulesGETSrvc,$rootScope,$state, myConfig) {
var fObject = {};
fObject.myForm = {};
fObject.details = {};
fObject.imgObject = {};
fObject.put = function ()
{
var imageData;
if (fObject.myForm.$valid)
{
var reader = new window.FileReader();
reader.readAsDataURL(fObject.details.ImageURLPath);
reader.onloadend = function () {
$rootScope.loading = true;
var result = $http({
method: "PUT",
dataType: 'json',
data: {
"DataURI": reader.result
},
url: myConfig.baseURL + 'odata/Modules(' + fObject.details.ModuleId + ')'
});
result.success(function (data) {
$rootScope.loading = false;
baseSrvc.toastMessage('Module has successfully been updated.');
$state.go('base.modules.get');
});
result.error(function (data) {
$rootScope.loading = false;
baseSrvc.returnError(data);
});
};
}
else
{
baseSrvc.toastMessage('Please input all required fields.');
};
};
return fObject;
});
<div class="md-block" flex-gt-sm>
<div class="imageUpload">
<md-tooltip md-direction="left">
Click here to select your image
</md-tooltip>
<div class="button"
required
ngf-select
ng-model="srvcObject.details.DataURI"
name="file"
ngf-pattern="'image/*'"
ngf-accept="'image/*'"
ngf-max-size="20MB"
><span ng-show="!srvcObject.details.DataURI">Select <br/> Course Image</span></div>
<div class="preview"
ngf-src="srvcObject.details.ImageURLPath"
ngf-background="srvcObject.details.ImageURLPath"></div>
</div>
</div>
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!