How to check if uploaded file is a JSON file? - html

I am taking a file input from a user and I want to check if the selected file is a JSON file. How can I do that?
<input type = "file" onChange = {checkJSON}/>
Also how do I retrieve data from the JSON file.

If JSON.parse throws an error, its most likely invalid, therefore you can check if its valid by getting the data into a string and then trying to parse it.
try {
const json = JSON.parse(jsonStr);
} catch (e) {
console.log('invalid json');
}

You can check if file extension is json and be sure that selected file is valid JSON in that way:
function Validate() {
fileName = document.querySelector('#myfile').value;
extension = fileName.split('.').pop();
if (extension != "json")
{
alert("Sorry, " + fileName + " is invalid, allowed extension is json!");
return false;
}
var file = document.getElementById('myfile').files[0];
var reader = new FileReader();
reader.readAsText(file, 'UTF-8');
reader.onload = function(evt) {
var jsondata = evt.target.result;
try {
const json = JSON.parse(jsondata);
document.getElementById('jsondata').innerHTML = jsondata;
} catch (e) {
alert("Sorry, " + fileName + " is not valid JSON file!");
return false;
}
}
return true;
};
Html content:
<script src="script2.js"></script>
File: <input type="file" id="myfile" onchange="Validate()"/><br /><br />
<div id="jsondata"></div>
You can play with my little working live demo on ReplIt (both cases - onsubmit and onchange demos)

Related

Html to Pdf Format Angular

Hello i want to convert from html to pdf format and send it as a file to my backend, so i can save it in my server, i tried using jspdf but its not working
SendMail() {
var doc = new jspdf();
doc.fromHTML('<h1>Hello World!</h1>', 20, 20);
var blob = new Blob([doc.output("blob")], { type: "application/pdf" });
let lruta = 'report/' + 'test';
this.uploaderService.uploadfile(blob, lruta).subscribe(
response => {
this.fetcher = response;
this.blockUI.stop();
}, error => {
this.blockUI.stop();
}
);
}
This is my service UploadFile
uploadfile(cabecera, ruta) {
const formData = new FormData();
formData.append('file', cabecera[0]);
formData.append('ruta', ruta);
return this._http.post(this.apiUrl + this.serviceUrl + 'gestion/uploadrevision', formData);
}
When i replace blob with this.file in my this.uploaderService.uploadfile
it works, but i dont want to download and upload my file
file: any;
onFileChange(event) {
this.file = event.target.files;
}

compress image on upload in angular

I wanted to upload images to products, and users. So im converting the image to base64 string and sending it. But when the selected image is large, the image is not getting uploaded as the base64 string is too large.
Here is the code:
Html
<input type="file" (change)="onFileSelected($event)">
<button type="submit" title="upload" (click)="uploadImage()"></button>
TS File
onFileSelected(event){
var files = event.target.files;
var file = files[0];
if (files && file) {
var reader = new FileReader();
reader.onload =this._handleReaderLoaded.bind(this);
reader.readAsBinaryString(file);
}
}
_handleReaderLoaded(readerEvt) {
var binaryString = readerEvt.target.result;
this.base64textString= btoa(binaryString);
console.log(btoa(binaryString));
}
Im just accepting the images on selection. So, is there any way to comress the image after selection or a way to reduce the base64 string so the image gets uploaded.
Thanks!! in advance.
In Angular you can upload image wihtout converting it into base64. Check this...
import { ViewChild } from '#angular/core';
export class yourComponent {
#ViewChild('fileInput') fileInput;
.
.
.
}
uploadImage(){
let fileBrowser = this.fileInput.nativeElement;
if (fileBrowser.files && fileBrowser.files[0]) {
console.log(fileBrowser.files[0]);
const formData = new FormData();
formData.append("userId", this.userId ); //appending userId in formData
formData.append("image", fileBrowser.files[0]); //appending image in formData
this.apiService.UploadImageMethod(formData)
.subscribe(
response=>{
console.log(response);
if(response.status == 'success'){
console.log(response);
}
},
err => {
this.imageErrorMsg = <any>err.message;
console.log(this.imageErrorMsg);
}
);
}
}
HTML:
<input type="file" id="fileInput" (click)="hideErrorMsg()" accept="image/*" #fileInput>
In API, you can get image data this way. (Php)
UploadImageMethod(){
$fileName = request()->image->getClientOriginalExtension();
$ext = strtolower(request()->image->getClientOriginalExtension());
}
Good Luck!!!

After upload CSV file and Read the data How to save multiple records from angular4(service.ts) to webapi controller for saving data into db

Note: i have uploaded CSV file by using above code and Read& Validate the data also , but i am unable to save those records into db. can any one can help me to pass data from my service.ts to webpapi controllers action method.
Bellow code is html code for csv fileupload -
<td><input type="file" name="File Upload" id="txtFileUpload"
(change)="changeListener($event.target.files)"
accept=".csv"/></td>
<td> <button class="btn btn1 btn2" color="primary" mat-raised-button *ngIf="isUploadFile" (click)="uploadCSVFile($event)">
UploadFile
</button></td>
Bellow code is Component.ts code -
uploadCSVFile($event) {
event.preventDefault();
alert('upload');
let businessAccountData = this.csvRecords;
let merchantdata: UserMerchantData = this.commonfunction.getUserMerchantData();
let email = this.commonfunction.getEmail();
// let userName = this.commonfunction.getUserName();
// for(let i =1; i<= businessAccountData.length;i++)
// {
// businessAccountData[i].UserName =userName;
// businessAccountData[i].MerchantKeyId =merchantdata.MerchantKeyId;
// }
this.service.addOnBusinessAccountData(businessAccountData,email).subscribe(result => {
console.log(' result - ', result);
if (result != null) {
//this.router.navigate(['/home/addonBusiness/manage-business-accounts']);
}
});
}
below code is service.ts file -
**strong text**
addOnBusinessAccountData(data,email)
{
alert('service');
// alert(JSON.stringify(data));
alert(data);
return this.service.create(environment.createBusinessAccountDataUrl+"?email="+email, data);
}
below code is for webapi controller's action method -
[HttpPost]
public IHttpActionResult AddAccountData(AddOnAccountData[] addOnAccountData, string email)
{
try
{
_apiConnectivity = new VposApiConnnectivity(email);
var businessAccountResponse = _apiConnectivity.AddAccountData(addOnAccountData);
return Json(businessAccountResponse);
}
catch (Exception e)
{
return Ok("");
}
}

How can I parse this XML with xml2js?

I have some XML that I'm trying to parse (using xml2js).
var xml2js = require('xml2js');
var json;
var XMLPath = './public/tsa.ibm.com/meijer/gpfs_hacmp_powersc.xml';
var rawJSON = loadXMLDoc(XMLPath);
function loadXMLDoc(filePath) {
try {
var fileData = fs.readFileSync(filePath, 'ascii');
var parser = new xml2js.Parser();
parser.parseString(fileData.substring(0, fileData.length), function(err, result) {
console.log(err);
console.log(result);
json = JSON.stringify(result);
console.log("JSON:");
console.log(JSON.stringify(result));
});
console.log("File '" + filePath + "/ was successfully read.\n");
return json;
} catch (exception) {
console.log(exception);
}
}
[Error: Invalid character in entity name Line: 44 Column: 123 Char: =]
On that line, the code is: <value xs:nil="true" />
I'm not sure what's going on here. :( Could anyone please help? I haven't really tried anything. I'm not sure what to even try.
Thanks for the help!

Switch to getJSON from raw data

I have this code that works for me:
$('#demo').live('pagecreate', function(event) {
var data, template, html;
data = {
"sver": [{"title":"Buffet Stagaljxxs" , "url_titler":"buffet-stagalj" },{"title":"Restoran Vrske" , "url_titler":"restoran-vrske" }]
};
template = '<ul data-role="listview" data-divider-theme="b" data-inset="false">{{#sver}}<li data-theme="b"><h3>{{title}}</h3><p>Opis: {{title}}</p></li>{{/sver}}</ul>';
html = Mustache.to_html(template, data);
$('#content').html(html);
});
Now i need to use remote json using getJSON, instead raw json like in my example.
I can't get it to work. Access-Control-Allow-Origin is not the issue.
This is the remote json address
Thanks
Call the data by using Ajax (like the function below)
<script>
function getJSONData(url)
{
var data = null;
var request = window.XMLHttpRequest ? new XMLHttpRequest() : (window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : null);
if (null != request)
{
request.open('GET', url, false);
request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
request.send(data);
//Parse returned JSON string.
data = JSON.parse(request.responseText);
}
return data;
}
$('#demo').live('pagecreate', function(event) {
var data, template, html;
data = getJSONData('http://wmd.hr/mobile-rss/jason/');
template = '<ul data-role="listview" data-divider-theme="b" data-inset="false">{{#sver}}<li data-theme="b"><h3>{{title}}</h3><p>Opis: {{title}}</p></li>{{/sver}}</ul>';
html = Mustache.to_html(template, data);
$('#content').html(html);
});
</script>