I have a fileList from upload file using Nz Zorro Ant for html in Angular 7, data will post to database using Spring Boot API, I want to use [nzRemoved] to delete file in fileList. How to use it?
This is my .ts,
checkUpload(event) {
// console.log(event);
// this.payload = JSON.stringify(event.file.response);
if (event.type === 'success'){
// (<Array<any>>this.fileList).pop();
this.fileList.push({
uid : event.file.uid,
name : event.file.name,
status: event.file.status,
url : event.file.response.data[0].path_url
});
// this.payload = JSON.stringify(this.fileList);
this.project.doc_url = JSON.stringify(this.fileList);
this.projectOverviewService.postDocument(this.project_id,
this.fileList).subscribe( res => {
console.log('success');
});
}
}
handleRemove(){
for (let i = 0; i <= this.fileList.length; i++) {
this.fileList.splice(0 , i)
}
}
And this is my html,
<div nz-col nzSpan="6" >
<nz-upload
nzAction="/upload/documents"
[(nzFileList)]="fileList"
(nzChange)="checkUpload($event)"
[nzRemove]="handleRemove">
<button nz-button type="button"><i nz-icon nzType="upload"></i>
<span>Upload dokumen Overview</span></button>
</nz-upload>
</div>
When I add [nzRemoved], removing file button in UI can not work.
You can change your code like this::
HTML
<div nz-col nzSpan="6" >
<nz-upload
nzAction="/upload/documents"
[(nzFileList)]="fileList"
(nzChange)="checkUpload($event)"
[nzRemove]="handleRemove">
<button nz-button type="button"><i nz-icon nzType="upload"></i>
<span>Upload dokumen Overview</span></button>
</nz-upload>
</div>
JS
handleRemove= (file: any) => new Observable<boolean>((obs) => {
}
Related
I have a main page containing a component called single-contact as below:
<el-row id="rowContact">
<!-- Contacts -->
<el-scrollbar wrap-class="list" :native="false">
<single-contact ref="singleContact"></single-contact>
</el-scrollbar>
</el-row>
And I want to dynamically render this component after AJAX polling, so in SingleContact.vue I use $axios and mounted() to request the data from the backend. And I want to render the component using v-for. I have my code as:
<template>
<div :key="componentKey">
<el-row id="card" v-for="contact in contacts" :key="contact.convUsername">
<div id="avatar" ><el-avatar icon="el-icon-user-solid"></el-avatar></div>
<h5 id='name' v-if="contact">{{contact.convUsername}}</h5>
<div id='btnDel'><el-button size="medium" type="danger" icon="el-icon-delete" v-on:click="delContact(contact.convUsername)"></el-button></div>
</el-row>
</div>
</template>
And the data structure is:
data() {
return {
timer: null,
contacts: []
}
And the method of Ajax polling is:
loadContacts () {
var _this = this
console.log('loading contacts')
console.log(localStorage.getItem('username'))
this.$axios.post('/msglist',{
ownerUsername: localStorage.getItem('username')
}).then(resp => {
console.log('success')
var json = JSON.stringify(resp.data);
_this.contacts = JSON.parse(json);
console.log(json);
console.log(_this.contacts[0].convUserName);
// }
}).catch(failResponse => {
console.log(failResponse)
})
}
This is what I get in the console:
Console Result
And the mounted method I compute is as:
beforeMount() {
var self = this
this.$axios.post('/msglist',{
ownerUsername: localStorage.getItem('username')
}).then(resp => {
this.$nextTick(() => {
self.contacts = resp.data
})
}).catch(failResponse => {
console.log(failResponse)
})
},
mounted() {
this.timer = setInterval(this.loadContacts(), 1000)
this.$nextTick(function () {
this.loadContacts()
})
},
beforeDestroy() {
clearInterval(this.timer)
this.timer = null
}
I can get the correct data in the console. It seems that the backend can correctly send json to the front, and the front can also receive the right result. But the page just doesn't render as expected.
Any advice would be great! Thank you in advance!
I am using jhipster to generate CRUD for my web application.
by configuring jdl generator I expect to see search panel in UI for each entity. But it just generates EntityQueryService classes in backend,it works fine
and it is reachable in swagger-ui in the API docs page
Is there any UI library thing to help me pass parameters as expected format or any predicate filter panel ?
Thanks.
Finally I addded manual search panel as below :
<div class="container-fluid">
<div class="row">
<jhi-alert-error></jhi-alert-error>
<div class="col-sm-4">
<label for="field_billOrgType">organization</label>
<select id="field_billOrgType" ng-model="vm.searchModel.billOrgType">
<option ng-repeat="x in vm.Utilities" value="{{x.key}}">{{x.name}} - {{x.key}}</option>
</select>
</div>
</div>
</div>
My controller:
( function () {
'use strict';
angular
.module('ebppApp')
.factory('TmpBill', TmpBill);
TmpBill.$inject = ['$resource'];
function TmpBill($resource) {
var resourceUrl = 'api/tmp-bills/:id';
return $resource(resourceUrl, {}, {
'search': {
method: 'GET'
, isArray: true
, url: 'api/tmp-bills?:billOrgType',
params: {
billOrgType: '#billOrgType'
}
}
}
});
} })();
function search() {
TmpBill.search({
billOrgType: vm.searchModel.billOrgType ? "billOrgType.equals=" + vm.searchModel.billOrgType : ''
page: vm.page - 1,
size: vm.itemsPerPage,
sort: sort()
}, onSuccess, onError);
function sort() {
var result = [vm.predicate + ',' + (vm.reverse ? 'asc' : 'desc')];
if (vm.predicate !== 'id') {
result.push('id');
}
return result;
}
function onSuccess(data, headers) {
vm.links = ParseLinks.parse(headers('link'));
vm.totalItems = headers('X-Total-Count');
vm.queryCount = vm.totalItems;
vm.tmpBills = data;
// vm.page = pagingParams.page;
}
function onError(error) {
AlertService.error(error.data.message);
}
}
i try to implement a anonymous login with Ember and Firebase. I have successfully configure my project for use with Firebase and Emberfire, and i can login to my Firebase. But when i try to save user information in a Session initializer, i can't retrieve it to make my controllers aware of the user state.
This is my code :
I have a sidebar in my application.hbs that i want to display if the user is connected.
<div class="container-fluid" id="main">
<div class="row">
{{#if loggedIn}}
<aside class="col-xs-3">
{{outlet sidebar}}
</aside>
<div class="col-xs-9">
{{outlet}}
</div>
{{else}}
<div class="col-xs-12">
{{outlet}}
</div>
{{/if}}
</div>
</div>
Inside of my application.js controller i try to define a computed property :
import Ember from "ember";
var ApplicationController = Ember.ObjectController.extend({
loggedIn :function() {
console.log("Tota", this.session.get('isConnected'));
return this.session.get('isConnected');
}.property(this.session.get('isConnected')),
});
export default ApplicationController;
this.session references an Initializer that is inject inside of controllers and routes :
import Ember from 'ember';
export function initialize(container, application) {
var session = Ember.Object.extend({
authData : [],
user : null,
login : function(authData, user) {
console.log(authData);
console.log(user);
this.set('authData', authData);
this.set('user',user);
},
getUser: function() {
return this.get('user');
},
getAuthData: function() {
return this.get('authData');
},
isConnected : function() {
return (this.get('user') == null) ? false : true;
}.property('user')
});
application.register('session:main', session, { singleton: true });
// Add `session` object to route to check user
application.inject('route', 'session', 'session:main');
// Add `session` object to controller to visualize in templates
application.inject('controller', 'session', 'session:main');
}
export default {
name: 'session',
initialize: initialize
};
And this is my LoginController :
import Ember from "ember";
var LoginController = Ember.ObjectController.extend({
model : {},
ages : function() {
var ages = Ember.A();
for(var i = 18; i <= 99; i++) {
ages.push(i);
}
return ages;
}.property(),
sexs : ['Male', 'Female'],
actions : {
logIn : function() {
var data = this.getProperties("name", "age", "sex");
var that = this;
this.database.authAnonymously(function(error, authData) {
if (error) {
console.log(error);
} else {
var newUser = that.store.createRecord('user', {
name: data['name'],
age: data['age'],
sex:(data['age'] === "Male" ? 0 : 1)
});
newUser.save();
that.session.login(authData, newUser);
console.log("Toto", that.session.get('isConnected'));
that.transitionToRoute('chat');
}
});
}
}
});
export default LoginController;
So in my application.js, if i define loggedIn to be just a property() not property(this.session.get('isConnected'). loggedIn is not refreshed when the user connects to the application. If i tell it to computes with " this.session.get('isConnected') ", Ember tells me that "this.session" is not defined.
How to refresh this value, to tell to my template to display sidebar if my user is connected?
Simple answer
var ApplicationController = Ember.ObjectController.extend({
loggedIn :Em.computed.alias('session.isConnected'),
// or
loggedIn : function(){
return this.get('session.isConnected');
}.property('session.isConnected')
});
Your problem was your dependencies. Either you weren't watching it (property()) or you were crashing because this.session doesn't exist in the scope of the window. And I doubt Ember was really yelling it at you, more of just the javascript engine while it parsing your javascript.
loggedIn :function() {
console.log("Tota", this.session.get('isConnected'));
return this.session.get('isConnected');
}.property(),
// this is resolved while defining the controller, think of its scope
It is resolved like this:
var tmp = this.session.get('isConnected');
var tmp2 = function() {
console.log("Tota", this.session.get('isConnected'));
return this.session.get('isConnected');
}.property(tmp);
var tmp3 = {
loggedIn: tmp2
};
var ApplicationController = Ember.ObjectController.extend(tmp3);
I need to upload multiple files as one request.
For example, i have two required files (.csv & .ctl) that I need to save.
Basically on the server side, I'm reading the .csv file and checking it against the .ctl file. If certain criteria doesn't match, I don't need to upload it. I'm not sure how or need to update the 'upload' method to read the filenames[]. Nor if I need to update this line "uploader.fineUploader('uploadStoredFiles');" to now accept the filenames[] after the user clicks "Upload now."
<script type="text/javascript">
$(document).ready(function () {
var filenames = [];
var uploader = $("#fine-uploader").fineUploader({
request: {
endpoint: '<%= ResolveUrl("~/Handler/UploadHandler.ashx")%>'
},
autoUpload: false,
text: {
uploadButton: '<span class="glyphicon glyphicon-plus"></span> Select Files'
},
validation: {
allowedExtensions: ['csv', 'ctl']
},
showMessage: function (message) {
// Using Bootstrap's classes
$('#fine-uploader').append('<div class="alert alert-danger">' + message + '</div>');
}
}).on('validate', function (event, fileData) {
return $.inArray(fileData.name, filenames) < 0;
}).on('submitted', function (event, fileId, fileName) {
filenames.push(fileName);
}).on('upload', function (event, fileId, fileName) {
var fileItemContainer = $(this).fineUploader('getItemByFileId', fileId);
$(this).fineUploader('setParams', { uploadType: 'VendorFileType', vendorId: '<%=vendorDropdownList1.CurrentVendorID %>' }, fileId);
}).on('complete', function (event, fileName, fileName, responseJSON) {
if (responseJSON.success) {
var div = document.getElementById('fine-uploader-status');
div.innerHTML = 'Upload process complete.';
}
else {
var div = document.getElementById('fine-uploader-status');
div.innerHTML = 'Upload denied.';
}
});
$('#uploadSelectedFiles').click(function () {
uploader.fineUploader('uploadStoredFiles');
});
});
</script>
//here's the aspx side.
<div id="fine-uploader">
</div>
<div id="fine-uploader-status">
</div>
<button id="uploadSelectedFiles" class="btn btn-primary">
<span class="glyphicon glyphicon-upload"></span>Upload now</button>
Fine Uploader does not support sending multiple files in a single request. This complicates the code unnecessarily and would break some existing features. Each file is sent in a separate request. You say you are performing some server-side checks to prevent uploads, but the files have already been uploaded by the time your server is able to perform these comparisons anyway. It's not clear from your question why you need to upload multiple files in a single request, or what benefit this gives you. If you clarify, perhaps I can provide alternate suggestions.
I'm using the Kendo UI File Upload for MVC and it works great. On my edit page, I want to show the files that were previously uploaded from the Create page. For visual consistency, I would like to re-use the upload widget on my edit page so the user can use the "remove" functionality, or add additional files if they choose. Does the upload widget support this?
Thanks!
So, I realize this is question pretty old, but I recently figured out how to do this reliably. While the other answer on here will certainly display the files, it doesn't really wire it up to any of the events (specifically the "remove" event). Also, rather than manually setting all of this up, I figured I'd much rather have Kendo do all of the real dirty work.
Note, this only applies if your file upload is not set to autosync. If you use the auto upload feature, you can find examples in the Kendo documentation here: http://docs.kendoui.com/api/web/upload#configuration-files
So anyway, let's assume we have a file input that we've made into a Kendo Upload:
<input id="files" name="files" type="file" multiple="multiple" />
$(document).ready(function () {
var $upload = $("#files");
var allowMultiple = Boolean($upload.attr("multiple"));
$upload.kendoUpload({
multiple: allowMultiple,
showFileList: true,
autoUpload: false
});
}
Then, we just need to get the information about the files to our jQuery. I like to jam it into JSON strings in hidden fields, but you can do it however you want.
Here's an example using the Mvc HtmlHelpers and Newtonsoft's JSON.NET (I don't use Razor, but you should get the general idea):
if (Model.Attachments.Count > 0)
{
var files = Model.Attachments.Select(x => new { name = x.FileName, extension = x.FileExtension, size = x.Size });
var filesJson = JsonConvert.SerializeObject(files);
Html.Render(Html.Hidden("existing-files", filesJson));
}
Note, the format there is incredibly important. We're tying to match the structure of the JavaScript object that Kendo is expecting:
{
relatedInput : sourceInput,
fileNames: [{ // <-- this is the collection we just built above
name: "example.txt",
extenstion: ".txt",
size: 1234
}]
}
So, then all that's left to do is put it all together. Basically, we're going to recreate the onSelect function from Kendo's internal syncUploadModule:
$(document).ready(function () {
// setup the kendo upload
var $upload = $("#files");
var allowMultiple = Boolean($upload.attr("multiple"));
var upload = $upload.kendoUpload({
multiple: allowMultiple,
showFileList: true,
autoUpload: false
}).getKendoUpload();
// initialize the files
if (upload) {
var filesJson = $("[name$='existing-files']").val();
if (filesJson) {
var files = JSON.parse(filesJson);
var name = $.map(files, function (item) {
return item.name;
}).join(", ");
var sourceInput = upload._module.element.find("input[type='file']").last();
upload._addInput(sourceInput.clone().val(""));
var file = upload._enqueueFile(name, {
relatedInput : sourceInput,
fileNames : files
});
upload._fileAction(file, "remove");
}
}
});
And that's pretty much it!
I came up with a way to do this.
Basically, you need HTML that mimics what the Upload control generates, and you use a bit of JavaScript to hook each item up. I initially render the HTML as hidden, then after you initialize the Kendo Upload control, you append the HTML list to the parent container that Kendo creates.
This is my MVC view:
#if (Model.Attachments != null && Model.Attachments.Count > 0)
{
<ul id="existing-files" class="k-upload-files k-reset" style="display: none;">
#foreach (var file in Model.Attachments)
{
<li class="k-file" data-att-id="#file.Id">
<span class="k-icon k-success">uploaded</span>
<span class="k-filename" title="#file.Name">#file.Name</span>
<button type="button" class="k-button k-button-icontext k-upload-action">
<span class="k-icon k-delete"></span>
Remove
</button>
</li>
}
</ul>
}
and here is the JavaScript (note, it was generated from CoffeeScript):
var $fileList, $files, item, _fn, _i, _len;
$fileList = $("#existing-files");
if ($fileList.length > 0) {
$(".k-upload").append($fileList);
$files = $(".k-file");
_fn = function(item) {
var $item, fileId, filenames;
$item = $(item);
fileId = $item.data("att-id");
filenames = [
{
name: fileId
}
];
return $item.data("fileNames", filenames);
};
for (_i = 0, _len = $files.length; _i < _len; _i++) {
item = $files[_i];
_fn(item);
}
$fileList.show();
}
You can find the full write up on my blog where I go into depth on the topic. I hope this helps you!
Some additional searches gave me the answer I wasn't looking for - According to this and this, Telerik does not support pre-populating an upload widget with previously uploaded documents.
It has been added in the options since this question has been asked.
Check out http://docs.telerik.com/kendo-ui/api/web/upload#configuration-files
It only works in async mode.
Try this...
#(Html.Kendo().Upload()
.Name("files")
.Async(a => a
.Save("SaveFile", "Home")
.Remove("RemoveFile", "Home")
.AutoUpload(true))
.Files(files =>
{
foreach (var file in Model.FundRequest.Files)
{
files.Add().Name(file.Name).Extension(Path.GetExtension(file.Name)).Size((long)file.SizeKb * 1024);
}
}))
My Model has a reference to my "FundRequest" object that has a List of "File" objects, so I just loop through each "File" and add.
Check this out!
<script>
var files = [
{ name: "file1.doc", size: 525, extension: ".doc" },
{ name: "file2.jpg", size: 600, extension: ".jpg" },
{ name: "file3.xls", size: 720, extension: ".xls" },
];
$("#upload").kendoUpload({
async: {
saveUrl: "Home/Save",
removeUrl: "Home/Remove",
autoUpload: true
},
files: files
});
</script>
<input type="file" name="files" id="upload" />
Check this out, this is it.
Below code is copied and adapted from kendo-ui documentation:
<div id="example">
<div>
<div class="demo-section">
<input name="files" id="files" type="file" />
</div>
</div>
<script>
$(document).ready(function () {
if (sessionStorage.initialFiles === undefined) {
sessionStorage.initialFiles = "[]";
}
var initialFiles = JSON.parse(sessionStorage.initialFiles);
$("#files").kendoUpload({
showFileList: true,
multiple: true,
async: {
saveUrl: "save",
autoUpload: false,
batch: true
},
files: initialFiles,
success: onSuccess
});
function onSuccess(e) {
var currentInitialFiles = JSON.parse(sessionStorage.initialFiles);
for (var i = 0; i < e.files.length; i++) {
var current = {
name: e.files[i].name,
extension: e.files[i].extension,
size: e.files[i].size
}
if (e.operation == "upload") {
currentInitialFiles.push(current);
} else {
var indexOfFile = currentInitialFiles.indexOf(current);
currentInitialFiles.splice(indexOfFile, 1);
}
}
sessionStorage.initialFiles = JSON.stringify(currentInitialFiles);
}
});
</script>
</div>