How can I save JSON data to a file with Knockout? - json

I'm trying to learn some stuff with Knockout by following the examples.
I've followed the loading and saving data tutorial and read the docs on Loading and Saving JSON Data.
Using the code in these examples, I can't seem to overwrite the JSON file. I tried setting permissions to 777 to make sure that wasn't the problem.
On "success," it just seems to return the data in the file. I confirmed this by loading the HTML file, manually editing the JSON file, deleting tasks, and clicking save. The result I saw in my console was the data from the manual edit of the JSON file.
I have this hosted on my server right now: index.html, test.json.
For the sake of posterity, here is that code:
HTML
<!doctype html>
<html>
<body>
<h3>Tasks</h3>
<form data-bind="submit: addTask">
Add task: <input data-bind="value: newTaskText" placeholder="What needs to be done?" />
<button type="submit">Add</button>
</form>
<ul data-bind="foreach: tasks, visible: tasks().length > 0">
<li>
<input type="checkbox" data-bind="checked: isDone" />
<input data-bind="value: title, disable: isDone" />
Delete
</li>
</ul>
You have <b data-bind="text: incompleteTasks().length"> </b> incomplete task(s)
<span data-bind="visible: incompleteTasks().length == 0"> - it's beer time!</span>
<button data-bind="click: save">Save</button>
<script src="//cdnjs.cloudflare.com/ajax/libs/knockout/3.0.0/knockout-min.js"></script>
<script src="//code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
function Task(data) {
this.title = ko.observable(data.title);
this.isDone = ko.observable(data.isDone);
}
function TaskListViewModel() {
// Data
var self = this;
self.tasks = ko.observableArray([]);
self.newTaskText = ko.observable();
self.incompleteTasks = ko.computed(function() {
return ko.utils.arrayFilter(self.tasks(), function(task) { return !task.isDone() && !task._destroy });
});
// Operations
self.addTask = function() {
self.tasks.push(new Task({ title: this.newTaskText() }));
self.newTaskText("");
};
self.removeTask = function(task) { self.tasks.destroy(task) };
self.save = function() {
var data = ko.toJSON({ tasks: self.tasks });
$.post('test.json', data, function(returnedData) {
console.info(returnedData);
});
/*
$.ajax("test.json", {
data: ko.toJSON({ tasks: self.tasks }),
type: "post", contentType: "application/json",
success: function(result) { console.info(result) }
});
*/
};
// Load initial state from server, convert it to Task instances, then populate self.tasks
$.getJSON("test.json", function(allData) {
var mappedTasks = $.map(allData, function(item) { return new Task(item) });
self.tasks(mappedTasks);
});
}
ko.applyBindings(new TaskListViewModel());
</script>
</body>
</html>
JSON
[{"title":"Wire the money to Panama","isDone":true},{"title":"Get hair dye, beard trimmer, dark glasses and \"passport\"","isDone":false},{"title":"Book taxi to airport","isDone":false},{"title":"Arrange for someone to look after the cat","isDone":false}]

The form is working properly, it's posting the correct JSON to the server (you can see this in the browser's dev tools). But because it's just a JSON file on the server, you're not able to overwrite it by simply posting to it. Instead, you'll need to create a web service endpoint on the server that you can post the data to, and the service will then save the file on the server's file system.

Related

Google API Autocomplete in SvelteKit

I am building an application where I need to get the value return from the API and bind it to my variable. I have been stuck on this for days, and I couldn't go any further.
Here is my code:
<script>
let address = "";
async function addExample() {
const response = await fetch(
"https://api",
{
method: "PUT",
headers: {
"api-key":
"api-key",
},
body: JSON.stringify({
address: address,
}),
}
);
}
</script>
<svelte:head>
<script
src="https://maps.googleapis.com/maps/api/js?key=my-key&libraries=places&callback=initAutocomplete"
async
defer
>
</script>
<script>
let autocomplete;
function initAutocomplete() {
const input = document.getElementById("autocomplete");
const options = {
componentRestrictions: { country: "au" },
strictBounds: false,
};
const autocomplete = new google.maps.places.Autocomplete(
input,
options
);
}
autocomplete.addListener("place_changed", onPlaceChanged);
function onPlaceChanged() {
address = autocomplete.getPlace();
}
</script>
</svelte:head>
<input
id="autocomplete"
placeholder="address"
type="text"
bind:value={address}
/><br />
I tried to add my tag svelte:head inisde the script tag but it didn't work, among others tries. And due my lack of experience, I want if I'm doind this on the right way instead of waste more time on this. PS: I don't need to create a map or anything like that now. I just want to bind the value of autocomplete to my variable, so I will be able to fetch data into DB.
I have tried eveything I could find googling but none of them worked. I am newbie with all this, and I don't know what else to think/try.

How can I do something or call back-end after upload a file

I'm trying to allow user upload their excel file, after that back-end will convert it as html format and suppose put it in the iframe src allow user preview in browser.
Now I'm trying to call the get path function for set the iframe src during page ready, but seems not work.
<portlet:actionURL var="checkworkbook" name="checkWorkbook"></portlet:actionURL>
<b>Please Upload a Document</b>
<form name ="UploadExcelForm" action="<%=checkworkbook%>" method="post" enctype="multipart/form-data">
<input type="file" id="uploadedFile" name="uploadedFile" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel">
<button type="button" onclick="<portlet:namespace />uploadExcel()"> submit </button>
</form>
<div id="displayArea">
<iframe id="displayExcel" src="" weight=800 height=400>Please Upload a file</iframe>
</div>
Here is the ajax part
function <portlet:namespace />uploadExcel() {
if ($('#uploadedFile').val() == null) {
alert("Please choose a file!");
return false;
}else{
document.UploadExcelForm.submit();
}
}
$(document).ready(function(){
<portlet:namespace />getDisplayPath();
});
function <portlet:namespace />getDisplayPath() {
var url = '<%=urlForAjax%>';
/*Make ajax call*/
$.ajax({
type : "POST",
url : url,
data: {
portletAction : "getDisplayPath"
},
success : function(data)
{
var obj = jQuery.parseJSON(data);
if(obj.jsonPath !=null){
var json = JSON.parse(obj.jsonPath);
$("#displayExcel").attr('src',obj.jsonPath);
}
},
error : function(XMLHttpRequest, textStatus, errorThrown)
{
/*Write you error-handling logic here*/
}
});
}
Moreover,I'm trying to use uploadExcel() part to make sure that user have select a file before upload, but it's not work, why?
I've do more testing, found that the problem maybe is getting the JSON, so I paste my back-end code here.
if ("getDisplayPath".equalsIgnoreCase(ajaxAction)){
String jsonPath = this.displayPath;
JSONObject json = JSONFactoryUtil.createJSONObject();
json.put("jsonPath", jsonPath);
response.getWriter().write(json.toString());
}

error in uploading the image from angular to nodejs

My Html file is -
<form method="post" [formGroup]="orderForm" enctype="multipart/form-data" (ngSubmit)="OnSubmit(orderForm.value)" >
<div class="form-group">
<label for="image">Select Branch Image</label>
<input type="file" formControlName="branchImg" (change)="onFileChange($event)" class="form-control-file" id="image">
</div>
</form>
and my .ts file is -
public orderForm: FormGroup;
onFileChange(event) {
const reader = new FileReader();
if (event.target.files && event.target.files.length) {
const [file] = event.target.files;
reader.readAsDataURL(file);
reader.onload = () => {
this.orderForm.patchValue({
branchImg: reader.result
});
};
}
}
ngOnInit() {
this.orderForm = this.formBuilder.group({
branchImg: [null, Validators.required]
});
}
and then submit the form.
I am supposed to get the image address and the upload that address in cloudinary
But when I am consoling the body in my nodejs app
it gives something like this-
branchImg: 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAgAAAQABAAD/7QCEUGhvdG9zaG9wIDMuMAA4QklNBAQAAAAAAGccAigAYkZCTUQwMTAwMGE4MjBkMDAwMD and so on.
I don't think that it is the images address. Can anyone tell me that what is this? and how to get that image's address which I will upload to cloudinary
As the Eric suggest -
my app.js code is
router.post('/branch',(req,res) =>{
const body = req.body;
const base64Data = body.branchImg.replace(/^data:image\/png;base64,/, "");
console.log(base64Data);
fs.writeFile("out.jpg", base64Data, 'base64', function(err,result) {
console.log(result);
});
});
it gives result as undefined
That basically is a base64 encoding of the image data. What you need to do after you get that is write that to a file, and then upload it to cloudinary
//this will write the base64 data as a jpg file to your local disk
require("fs").writeFile("out.jpg", base64Data, 'base64', function(err) {
//after you write it to disk, use the callback space here to upload said file
//to your cloudinary endpoint
});

MVC5 controller not getting file from HTML file input

I'm trying to simply allow a user to upload a file.
I have a simple begin form that contains a file element as shown below:
#using (Html.BeginForm("LoadData", "Input", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div style="width:23%; display:inline-block;">
<label>Select Type:</label>
<select name="UploadType">
<option value="First">First</option>
<option value="Second">Second</option>
</select>
</div>
<div style="width:43%; display:inline-block;">
<input type="file" name="files1" id="files1" />
</div>
<div style="width:33%; display:inline-block;">
<input type="submit" value="Upload"/>
</div>
}
The controller is :
[HttpPost]
public ActionResult LoadData(string UploadType, HttpPostedFileBase file1)
{
if(file1 != null && UploadType != null)
{
Console.WriteLine(file1.FileName);
Console.WriteLine(UploadType);
}
}
Everything displays and works on the site but when it posts back the file is null. I've looked at many google results including:
Binding HttpPostedFileBase using Ajax.BeginForm
MVC 4 Razor File Upload
http://www.aurigma.com/upload-suite/developers/aspnet-mvc/how-to-upload-files-in-aspnet-mvc
and more. they all say my stuff is correct. As long as the names match on the file input and the controller param, it should work. But it's not.
I've tried naming it file, files, and now file1 but no mater what I call it, it comes back null.
What am I doing wrong? I even tried checking the Request.Files but that says it has a count of 0.
I ended up using javascript to handle the files instead. Here's the working code:
Javascript (it allows multiple files now):
function SendData() {
var formData = new FormData(document.querySelector('UploadForm'));
for(var i = 0; i < $('#file')[0].files.length; i++)
{
formData.append('files', $('#file')[0].files[i]);
}
formData.append('samplevalue', $('#samplevalue').val());
var url = $('#baseUrl').val() + 'Input/LoadData';
$.ajax({
url: url,
type: 'POST',
data: formData,
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
success: function (data) {
// your logic....
},
error: function(data)
{
// logic....
}
});
}
The controller then accepts
public string LoadData(string samplevalue, HttpPostedFileBase[] files)
{
}
Of course the trick is the javascript. I still don't know why the form doesn't work normally but this works perfectly. :)
Your file input is named files1, but your action param is file1 (no s).
#using (Html.BeginForm("MethodName", "ControllerName", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<input type="file" name="ImgUploader" id="ImgUploader" />
<input type="submit" value="Create" class="btn btn-default" />
}
**Your Controller**`[HttpPost]
public ActionResult Create()
{
HttpPostedFileBase file = Request.Files["ImgUploader"];
}

How to get the path of the uploaded image from the client machine

I am looking for the code that can help me in getting the original path(not fake path) of the image that has to be uploaded from the client machine.As many browsers doesn't provide the path due to some security issues.
Here is my html code:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="js\ajax_jquery_jquery-1_9_0.js" type="text/javascript"></script>
<script type="text/javascript" language="javascript">
function valueCheck() {
//alert ur fileupload control value
var path = document.getElementById("file").value;
//alert(document.getElementById("file").value);
alert(" PATH " + path);
//check for other controls value
var icon_elem = document.getElementById("img");
icon_elem.src = path;
display();
}
function display() {
$.ajax({
type: 'POST',
url: 'xidirectorywebservice.asmx/UploadImage',
data: "{ }",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (image_string) {
var data = 'data:image/png;base64,' + image_string.d;
var icon_elem = document.getElementById("ItemPreview");
icon_elem.src = data;
},
error: function () {
alert("Error");
}
});
}
</script>
</head>
<body>
<br />
<img id="ItemPreview" src="" />
<label for="file">Filename:</label>
<input type="file" name="file" id="file"/><br/>
<input type="submit" name="submit" value="Submit" onclick="valueCheck()" />
</body>
</html>
The above code has two buttons choose file which is used to choose the image from the client machine and submit button which checks the path of the image(we are getting the fake path here) as we need to pass it to the web service in order to save it in database.
After a long struggle i realized that i cannot get the path using the client side code, and have got no idea how to extract this path using vb.net web service can any one help me with this?
cheers.