how to read xml file content from file in react? - node.js

I'm sure this question has been asked before but i can't find it in Stakoverflow
i'm doing a simple site where you upload an xml and it parses it to json.
i'm having a form to upload the xml:
<form onSubmit={this.handleSubmit}>
<label>
Upload file:
<input
type="file"
ref={input => {
this.App = input;
}}
/>
</label>
<br />
<button type="submit">Submit</button>
</form>
and my lisenter:
handleSubmit(event) {
//here the file will be opened
//submit pressed
event.preventDefault();
alert(
`Selected file - ${this.App.files[0].name}`
);
}
how do i extract the xml content from the file in the event ?
i want to have a String with the xml content from the file
thnx !!!

Found it i used this code:
var rawFile = new XMLHttpRequest();
var allText;
rawFile.open("GET", this.App.files[0], false);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
allText = rawFile.responseText;
// alert(allText);
}
}
}
rawFile.send(null);

Related

Upload multiple Files in angular node multer

I am facing problem while uploading multiple files in angular, node, multer.
Last file in array is uploaded to server.
Here is my HTML.
<div class="mb-1">
<p class="text-muted m-0">Anti Black List</p>
<input type="file" (change)="fileChangeEvent($event)" name="Anti Black List" id="4" #fileDataAntiBlackList (onFileSelected)="onFileSelected($event ,fileDataAntiBlackList)" ng2FileSelect [uploader]="uploader" accept="application/pdf"/>
</div>
<div class="mb-1">
<p class="text-muted m-0">Anti Black List</p>
<input type="file" (change)="fileChangeEvent($event)" name="Shop Act" id="3" #fileDataShopAct (onFileSelected)="onFileSelected($event ,fileDataShopAct)" ng2FileSelect [uploader]="uploader" accept="application/pdf"/>
</div>
<div class="mb-1">
<p class="text-muted m-0">Anti Black List</p>
<input type="file" (change)="fileChangeEvent($event)" name="Professional Tax" id="2" #fileDataPRO (onFileSelected)="onFileSelected($event ,fileDataPRO)" ng2FileSelect [uploader]="uploader" accept="application/pdf"/>
</div>
<div class="mb-1">
<p class="text-muted m-0">Anti Black List</p>
<input type="file" (change)="fileChangeEvent($event)" name="GST Copy" id="1" #fileDataGST (onFileSelected)="onFileSelected($event ,fileDataGST)" ng2FileSelect [uploader]="uploader" accept="application/pdf"/>
</div>
<mat-label>First name</mat-label>
<input formControlName="f_name" matInput type="text" name="first_name" placeholder="First name" required/>
<mat-label>Last name</mat-label>
<input formControlName="l_name" matInput type="text" name="Last_name" placeholder="Last name" required/>
<button mat-raised-button color="primary" class="mx-4" (click)="onSubmit()"
[disabled]="uploader.getNotUploadedItems().length && signupForm.invalid">Upload And Save </button>
There are more fields, but i have shown less here.
Following is TS file code
filesToUpload: Array<File> = [];
fileChangeEvent(fileInput: any) {
this.filesToUpload = <Array<File>>fileInput.target.files;
//this.product.photo = fileInput.target.files[0]['name'];
}
onSubmit() {
//let files = this.getFiles();
let dbId: number;
let formData = new FormData();
const files: Array<File> = this.filesToUpload;
for(let i = 0; i < files.length;i++){
formData.append("files", files[i], files[i]['name']);
}
formData.append('first_name',this.signupForm.value.f_name);
this.http.post('http://localhost:3000/api/newUpload', formData)
.map(files => files)
.subscribe(files => console.log('files', files));
return false;
}
This is my backend API
Upload
let user_storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, DIR);
},
filename: (req, file, cb) => {
cb(null, file.fieldname + '-' + Date.now() + '' + path.extname(file.originalname));
}
});
let upload = multer({ storage: user_storage }).array('files',10);
API function
router.post('/newUpload',function(req,res){
console.log('before upload',req.body);
upload(req,res,function(err) {
//console.log(req.body);
//console.log(req.files);
if(err) {
return res.end("Error uploading file.");
}
console.log('files', req.files);
console.log(req.body);
res.send(req.files);
//res.end("File is uploaded");
});
});
This is what i have tried. Only last file in array is save in uploads folder.
Also i want to insert first name , last name etc to database but when i console req.body is gives empty json {}
Edit quetion
i got where i am missing.
Its in angular code : when i print
const files: Array<File> = this.filesToUpload;
i get last file which i uploaded. means it takes last file which is uploaded not all files.
so i use following function
getFiles(){
return this.uploader.queue.map((fileItem) => {
return fileItem.file;
});
}
So in onsubmit function
onSubmit() {
let files = this.getFiles();
let formData = new FormData();
for(let i = 0; i < files.length;i++){
console.log(files[i]);
formData.append("files", files[i],files[i]['name']);
}
When i console files[i], get all files.
But in line formData.append line i get following error
Argument of type 'FileLikeObject' is not assignable to parameter of type 'string | Blob'.
Property 'slice' is missing in type 'FileLikeObject' but required in type 'Blob
P.S : when i send file name in formdata.append, i get all file names in node serevr.
After trying different solutions, finally i got working solutions by which multiple files and other input fields are also send to sever.
In my Edit part of question, i have use following function
getFiles(){
return this.uploader.queue.map((fileItem) => {
return fileItem.file;
});
}
above code was giving error. I have just changed return line.
from
return fileItem.file;
to
return fileItem.file.rawFile;
Thats it. All remaining code is same as in edit.
you forget to add multer middleware to your router.post
it should be
outer.post('/newUpload',
upload.array('myFiles', 12),
function(req,res){
upload(req,res,function(err) {
if(err) {
return res.end("Error uploading file.");
}
res.send(req.files);
//res.end("File is uploaded");
});
});

I can't upload file in adonis js, move is not function

I have the following file type field
<form action = "javascript:;" enctype="multipart/form-data" id="formulario" class="form-horizontal">
<div class="form-group">
<div class="span7">
<input type="file" multiple class="file file-loading" data-preview-file-type="any" id="fileUp" name="fileUp[]">
</div>
</div>
</form>
and in the controller i have this for upload file
const Helpers = use('Helpers')
const myFile = request.file('fileUp')
const directory = Helpers.publicPath()
await myFile.move(directory, {
overwrite: true
})
but return error "move is not function"
i don't understand
Your input is for multiple files (fileUp[]), the docs has a section for multiple file upload,you should use moveAll() instead of move()
await profilePics.moveAll(Helpers.tmpPath('uploads'))
if (!profilePics.movedAll()) {
return profilePics.errors()
}

Angularjs jQuery FIle Upload

I'm new at Angularjs and I'm trying to create an AngularJS project with jQuery File Upload but I could not distinguish between directives file controllers file and the view.
Can anyone help me by providing me a clear structure of how files should be placed? (controllers, directives, and view)
I wrote something for my very first Angular.js project. It's from before there was an Angular.js example, but if you want to see the hard way, you can have it. It's not the best, but it may be a good place for you to start. This is my directives.js file.
(function(angular){
'use strict';
var directives = angular.module('appName.directives', []);
directives.directive('imageUploader', [
function imageUploader() {
return {
restrict: 'A',
link : function(scope, elem, attr, ctrl) {
var $imgDiv = $('.uploaded-image')
, $elem
, $status = elem.next('.progress')
, $progressBar = $status.find('.bar')
, config = {
dataType : 'json',
start : function(e) {
$elem = $(e.target);
$elem.hide();
$status.removeClass('hide');
$progressBar.text('Uploading...');
},
done : function(e, data) {
var url = data.result.url;
$('<img />').attr('src', url).appendTo($imgDiv.removeClass('hide'));
scope.$apply(function() {
scope.pick.photo = url;
})
console.log(scope);
console.log($status);
$status.removeClass('progress-striped progress-warning active').addClass('progress-success');
$progressBar.text('Done');
},
progress : function(e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
$progressBar.css('width', progress + '%');
if (progress === 100) {
$status.addClass('progress-warning');
$progressBar.text('Processing...');
}
},
error : function(resp, er, msg) {
$elem.show();
$status.removeClass('active progress-warning progress-striped').addClass('progress-danger');
$progressBar.css('width', '100%');
if (resp.status === 415) {
$progressBar.text(msg);
} else {
$progressBar.text('There was an error. Please try again.');
}
}
};
elem.fileupload(config);
}
}
}
]);
})(window.angular)
I didn't do anything special for the controller. The only part of the view that matters is this:
<div class="control-group" data-ng-class="{ 'error' : errors.image }">
<label class="control-label">Upload Picture</label>
<div class="controls">
<input type="file" name="files[]" data-url="/uploader" image-uploader>
<div class="progress progress-striped active hide">
<div class="bar"></div>
</div>
<div class="uploaded-image hide"></div>
</div>
</div>

backbonejs node file upload

None of the answers I have found anywhere have worked. I am trying to extend the example in "Developing Backbone.js Applications" to upload files. Although the form has enctype="multipart/form-data," request.files is always undefined.
The form HTML is:
<form id="addBook" action="..." enctype="multipart/form-data">
<div>
<label for="coverImage">CoverImage: </label><input id="coverImage" name="coverImage" type="file" />
<label for="title">Title: </label><input id="title" type="text" />
<label for="author">Author: </label><input id="author" type="text" />
<label for="releaseDate">Release date: </label><input id="releaseDate" type="text" />
<label for="keywords">Keywords: </label><input id="keywords" type="text" />
<button id="add">Add</button>
</div>
</form>
The backbone that saves the new record is
addBook: function( e ) {
e.preventDefault();
var formData = {};
var reader = new FileReader();
$( '#addBook div' ).children( 'input' ).each( function( i, el ) {
if( $( el ).val() != '' )
{
if( el.id === 'keywords' ) {
formData[ el.id ] = [];
_.each( $( el ).val().split( ' ' ), function( keyword ) {
formData[ el.id ].push({ 'keyword': keyword });
});
} else if( el.id === 'releaseDate' ) {
formData[ el.id ] = $( '#releaseDate' ).datepicker( 'getDate' ).getTime();
} else {
formData[ el.id ] = $( el ).val();
}
}
});
console.log(formData);
this.collection.create( formData );
}
The Node being called.
//Insert a new book
app.post( '/api/books', function( request, response ) {
console.log(request.body);
console.log(request.files);
});
The value of coverimage send to node is correct, I just never get anything in request.files. I have a cool drag and drop I would like to use instead, but until I get this working I am stuck.
I tried the JQuery-file-upload, that got me nowhere.
If I had hair, I would be pulling it out right now.
I wouldn't be submitting the file as part of the model.save/collection.create(model).
What I've used is Plupload for a file upload manager, submitting a file to an upload handler. This upload handler either returns the path to the uploaded file, or fileId if a reference is stored in a database table.
From there I populate a property in my backbone model, then persist the model. You can have your model listenTo plupload, for an upload completed event or similar.
I'm also following the sample of the book "Developing Backbone.js Applications", I extended the functionality to upload images to a folder in the server and save the path in my model to show the correct images. It is working fine. I tried to use Plupload and other jquery plugins but I didn't like them. My sample is using ajax to upload images to the server and then using them. I read many posts referencing the use of iframes to have ajax functionality. The best approach for this I found is using the jquery.form.js to avoid postbacks and load the images in a nice way.
The running sample working fine with nodeJS:
https://github.com/albertomontellano/bookLibrarySampleNodeJS
I based my solution in the post of Mark Dawson:
http://markdawson.tumblr.com/post/18359176420/asynchronous-file-uploading-using-express-and-node-js
However, I had to correct a method of this post to make it work correctly:
app.post('/api/photos', function(req, res) {
var responseServerPath = 'images/' + req.files.userPhoto.name;
var serverPath = 'site/images/' + req.files.userPhoto.name;
console.log(req.files.userPhoto.path);
require('fs').rename(
req.files.userPhoto.path,
serverPath,
function(error) {
if(error) {
console.log(error);
res.send({
error: 'Ah crap! Something bad happened'
});
return;
}
res.send({
path: responseServerPath
});
}
);
});
I hope it helps.
Turned out I had to end up hiring someone to do it, because I can't find any examples online of anybody uploading a file through backbone, even without updating any database interaction. Everybody has the same basic advice about what tools to use to upload the files, but I can't for the life of me find ONE example of someone implementing it.
I am planning on making the code available to everybody, so they can see how it works.

MODX - user profile photo upload

I am trying to allow users to upload photos to their profiles. I am sure I am doing something wrong...
What I currently have configured:
Update Profile Form
[[!UpdateProfile? &useExtended=`1` &preHooks=`user_profile_image` &postHooks=`redirect_profile_update`]]
<div class="update-profile">
<div class="updprof-error">[[+error.message]]</div>
[[+login.update_success:if=`[[+login.update_success]]`:is=`1`:then=`[[%login.profile_updated? &namespace=`login` &topic=`updateprofile`]]`]]
<form class="form" enctype="multipart/form-data" action="[[~[[*id]]]]" method="post">
<input type="hidden" name="nospam:blank" value="" />
<label for="fullname"><i class="icon-user"></i> <strong>[[!%login.fullname? &namespace=`login` &topic=`updateprofile`]]</strong>
<span class="error">[[+error.fullname]]</span>
</label>
<input type="text" name="fullname" id="fullname" value="[[+fullname]]" />
<label for="email"><i class="icon-envelope"></i> <strong>[[!%login.email]]</strong>
<span class="error">[[+error.email]]</span>
</label>
<input type="text" name="email:required:email" id="email" value="[[+email]]" />
<label for="test_field">Test Field
<span class="error">[[+error.custom_field]]</span>
</label>
<input type="text" name="test_field" id="test_field" value="[[+test_field]]" /><br/>
<div class="row clearfix">
<div class="label">Photo<span class="error">[[+fi.error.nomination_file]]</span></div>
<div class="input"><input id="nomination_file" name="nomination_file:required" type="file" value="[[+fi.nomination_file]]" maxlength="100000" /></div>
</div>
<br class="clear" />
<button class="btn-info btn btn-large" type="submit" name="login-updprof-btn">Update Profile</button>
</form>
</div>
User_profile_image snippet
<?php
// initialize output;
$output = true;
// get the current user name to create the file name as
$userName = $modx->user->get('username');
// valid extensions
$ext_array = array(`jpg', 'jpeg', 'gif', 'png');
// create unique path for this form submission
$uploadpath = 'assets/uploads/';
// you can create some logic to automatically
// generate some type of folder structure here.
// the path that you specify will automatically
// be created by the script if it doesn't already
// exist.
// EXAMPLE:
// this would put all file uploads into a new,
// unique folder every day.
// $uploadpath = 'assets/'uploads/'.date('Y-m-d').'/';
// get full path to unique folder
$target_path = $modx->config['base_path'] . $uploadpath;
// get uploaded file names:
$submittedfiles = array_keys($_FILES);
// loop through files
foreach ($submittedfiles as $sf) {
// Get Filename and make sure its good.
$filename = basename( $_FILES[$sf]['name'] );
// Get file's extension
$ext = pathinfo($filename, PATHINFO_EXTENSION);
$ext = mb_strtolower($ext); // case insensitive
// is the file name empty (no file uploaded)
if($filename != '') {
// is this the right type of file?
if(in_array($ext, $ext_array)) {
//create file called the user name + pic
$filename = $userName . "pic".'.'.$ext ;
// full path to new file
$myTarget = $target_path . $filename;
// create directory to move file into if it doesn't exist
mkdir($target_path, 0755, true);
// is the file moved to the proper folder successfully?
if(move_uploaded_file($_FILES[$sf]['tmp_name'], $myTarget)) {
// set a new placeholder with the new full path (if you need it in subsequent hooks)
$modx->setPlaceholder('fi.'.$sf.'_new', $myTarget);
// set the permissions on the file
if (!chmod($myTarget, 0644)) { /*some debug function*/ }
} else {
// File not uploaded
$errorMsg = 'There was a problem uploading the file.';
$hook->addError($sf, $errorMsg);
$output = false; // generate submission error
}
} else {
// File type not allowed
$errorMsg = 'Type of file not allowed.';
$hook->addError($sf, $errorMsg);
$output = false; // generate submission error
}
// if no file, don't error, but return blank
} else {
$hook->setValue($sf, '');
}
}
return $output;
1) fix quote in this line
$ext_array = array(`jpg', 'jpeg', 'gif', 'png');
2) remove all :required in name fields.
3) instead
$modx->setPlaceholder('fi.'.$sf.'_new', $myTarget);
type
$hook->setValue($sf, $uploadpath . $filename);
4) after mkdir($target_path, 0755, true); add
if(file_exists($myTarget) {
chmod($myTarget,0755); //Change the file permissions if allowed
unlink($myTarget); //remove the file
}
For anyone who references this post:
move user_profile_image back to the prehooks like this:
&preHooks=`user_profile_image`
and at line 59 add the missing ")" like this:
if(file_exists($myTarget)) {

Resources